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/.gigacode/plans/1793452448001-happy-orchid.plan.md b/.gigacode/plans/1793452448001-happy-orchid.plan.md new file mode 100644 index 00000000..14c1bf45 --- /dev/null +++ b/.gigacode/plans/1793452448001-happy-orchid.plan.md @@ -0,0 +1,443 @@ +# Технический аудит проекта Lab4 — Messenger + +## A. Общая оценка + +**Проект:** `messenger-lab2` (Java 21 / Spring Boot / PostgreSQL / Redis / MinIO) +**Лаба:** 4 — «S3-хранилище и вложения» (contract version 1.4.0) +**Архитектура:** 2+ API-реплики → nginx LB → PostgreSQL + Redis + MinIO + +### Соответствие заданию +Проект реализует полноценный REST-мессенджер с аутентификацией, чатами, сообщениями, idempotency, вложениями, S3-интеграцией и фоновым reconciler'ом. Архитектура соответствует требованиям lab4 (2 API-реплики, LB, S3, PostgreSQL, Redis). + +### Целостность архитектуры +Архитектура целостная на уровне Java-кода: слои Controller → Service → Repository, MapStruct-мапперы, валидация, обработка исключений, ShedLock для координации. Однако **существенные проблемы в конфигурационных файлах (build.gradle, Dockerfile) блокируют сборку и запуск.** + +### Вердикт +**Вариант 1: Проект можно сохранить и точечно исправить.** Java-код написан качественно, архитектура соответствует заданию. Критические проблемы находятся в конфигурациях сборки и Docker, которые исправляются точечно. + +--- + +## B. Карта архитектуры + +``` + ┌─────────────┐ + │ Client │ + └──────┬──────┘ + │ :8080 + ┌──────▼──────┐ + │ nginx │ (LB, round-robin + keepalive) + │ :8080 → :80│ + └──────┬──────┘ + │ + ┌──────────────────┼──────────────────┐ + │ │ + ┌────────▼────────┐ ┌───────▼───────┐ + │ API replica 1 │ │ API replica 2 │ + │ Spring Boot 21 │ │ Spring Boot │ + │ ShedLock-aware │ │ ShedLock- │ + └──┬────┬────┬─────┘ └──┬────┬──────┘ + │ │ │ │ │ + ┌────▼──┐ │ ┌─▼─────┐ ┌─▼────┐ + │Postgre│ │ │ Redis │ │ MinIO │ + │SQL:16 │ │ │ 7.4 │ │:9000 │ + └───────┘ │ └───────┘ └──────┘ + │ + ┌───────▼───────┐ + │ Flyway migrate│ (one-shot) + └───────────────┘ +``` + +### Жизненный цикл запуска: +1. `docker compose up db redis minio` → сервисы становятся healthy +2. `minio-init` создаёт bucket `messenger-attachments`, пользователя, политику +3. `migrate` запускает Spring Boot в `NONE` режиме, выполняет Flyway V1__init.sql +4. `api` реплики запускаются с `SPRING_FLYWAY_ENABLED=false`, подключаются ко всем сервисам +5. nginx начинает проксировать трафик на здоровые API-реплики + +--- + +## C. Критические проблемы (блокирующие запуск) + +### C1. build.gradle — несуществующая версия Spring Boot 4.1.1 +**Файл:** `build.gradle`, строка 3 +**Проблема:** `org.springframework.boot` version `4.1.1` — такая версия не существует. Актуальная мажорная версия — 3.x. +**Последствие:** Gradle не разрешит ни один spring-boot-starter dependency. Сборка упадёт. + +### C2. build.gradle — несуществующие artifact names +**Файл:** `build.gradle` +**Проблемные зависимости:** +| Зависимость | Правильное имя | +|---|---| +| `spring-boot-starter-webmvc` | `spring-boot-starter-web` | +| `spring-boot-starter-jackson` | (часть `spring-boot-starter-web`) | +| `spring-boot-starter-restclient-test` | (часть `spring-boot-starter-test`) | +| `spring-boot-resttestclient` | не существует | +| `spring-boot-starter-actuator-test` | не существует | +| `spring-boot-starter-validation-test` | не существует | +| `spring-boot-starter-webmvc-test` | `spring-boot-starter-web-test` | + +**Последствие:** Gradle не разрешит эти зависимости. Сборка упадёт. + +### C3. build.gradle — невалидный Gradle-синтаксис (двоеточие) +**Файл:** `build.gradle`, строка `runtimeOnly 'io.netty:netty-transport-native-epoll::linux-x86_64'` +**Проблема:** Двойное двоеточие `::` — невалидный синтаксис Gradle. +**Последствие:** Ошибка парсинга build-файла. + +### C4. Dockerfile — несуществующий Gradle 9.7.1 +**Файл:** `Dockerfile`, строки `COPY gradle-9.7.1-bin.zip`, `ENV PATH`, `RUN unzip` +**Проблема:** Gradle 9.7.1 не существует. Файл `gradle-9.7.1-bin.zip` отсутствует в репозитории. +**Последствие:** Docker build упадёт на шаге `COPY gradle-9.7.1-bin.zip`. + +### C5. Dockerfile — конфликт с gradle-wrapper +**Файл:** `Dockerfile` +**Проблема:** Dockerfile использует ручную установку Gradle через unzip, но в репозитории есть `gradle/wrapper/gradle-wrapper.jar` и `gradlew`. Правильный подход — использовать gradlew wrapper. +**Последствие:** Docker build не найдёт `gradle-9.7.1-bin.zip` в build context. + +### C6. Dockerfile — HEALTHCHECK использует readiness вместо liveness +**Файл:** `Dockerfile`, HEALTHCHECK +**Проблема:** `HEALTHCHECK` проверяет `/actuator/health/readiness`, но readiness зависит от БД. Если БД недоступна, контейнер помечается как unhealthy, хотя процесс жив. +**Рекомендация:** Использовать `/actuator/health/liveness` для Docker HEALTHCHECK. + +### C7. docker-compose.yml — secrets-файлы отсутствуют +**Файл:** `docker-compose.yml`, секция `secrets` +**Проблема:** Все secrets ссылаются на файлы `./secrets/*.txt`, которых нет в репозитории. +**Последствие:** `docker compose up` упадёт с ошибкой «secrets failed: stat ... no such file». + +### C8. docker-compose.yml — deploy.replicas не работает в Docker Compose v2 +**Файл:** `docker-compose.yml`, service `api` +**Проблема:** `deploy.replicas: 2` работает только в Docker Swarm mode, не в обычном `docker compose up`. +**Последствие:** Будет запущена только 1 API-реплика. + +### C9. application.yaml — SPRING_PROFILES_ACTIVE: lab +**Файл:** `application.yaml`, docker-compose.yml (service api) +**Проблема:** `SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab}` — профиль `lab` не определён ни в одном файле. +**Последствие:** Ничего критичного (неопределённый профиль не вызывает ошибку), но может запутать. + +--- + +## D. Некритические проблемы + +### D1. settings.gradle — неверное имя проекта +**Файл:** `settings.gradle` +**Текущее:** `rootProject.name = 'messenger-lab1'` +**Ожидаемое:** `messenger` или `messenger-lab4` + +### D2. requirements-dev.txt — отсутствует jsonschema +**Файл:** `requirements-dev.txt` +**Проблема:** `scripts/validate_openapi.py` импортирует `jsonschema`, но он не указан в `requirements-dev.txt`. +**Последствие:** `make validate` упадёт с `ModuleNotFoundError: No module named 'jsonschema'`. + +### D3. MinIO image — loose tag +**Файл:** `docker-compose.yml` +**Проблема:** `pgsty/silo:latest` и `pgsty/mc:latest` используют `:latest`. +**Рекомендация:** Зафиксировать конкретные версии. + +### D4. nginx.conf — короткий proxy_connect_timeout +**Файл:** `nginx.conf` +**Проблема:** `proxy_connect_timeout 1s` — очень короткий таймаут. При высокой нагрузке может вызывать преждевременный failover. +**Рекомендация:** Увеличить до 5s. + +### D5. OpenAPI Attachment status enum +**Файл:** `contracts/openapi.json` +**Проблема:** `Attachment.status` enum содержит только `["ready"]`, но реализация использует `UPLOADING`, `READY`, `BROKEN`. +**Последствие:** Валидация examples.json может не пройти. + +### D6. OpenAPI variant enum +**Файл:** `contracts/openapi.json` +**Проблема:** `variant` enum содержит только `["original"]`, но smoke.py для LAB>=5 запрашивает `?variant=thumbnail`. + +### D7. ShedLock — @SchedulerLock без @Scheduled на методе reconcile() +**Файл:** `AttachmentReconciler.java` +**Проблема:** `@SchedulerLock` находится на публичном методе `reconcile()`, который аннотирован `@Scheduled`. Это корректно, НО метод `reconcile()` может быть вызван напрямую из тестов, что обойдёт ShedLock. + +### D8. S3Properties — file-based secrets через env vars +**Файл:** `S3Properties.java` +**Проблема:** `resolvedAccessKey()` читает из файла по пути из env var `S3_ACCESS_KEY_ID_FILE`, но в docker-compose.yml эти env vars не передаются. +**Последствие:** Файловый fallback не сработает, ключи берутся из `s3.access-key` / `s3.secret-key`, которые пустые по умолчанию. + +### D9. application.yaml — session.store не используется +**Файл:** `docker-compose.yml`, env `SESSION_STORE: ${SESSION_STORE:-postgres}` +**Проблема:** Нигде в коде не используется свойство `session.store`. Redis используется для кэширования сессий, но не как «store of sessions». + +--- + +## E. Таблица конфигураций + +| Параметр | Где задаётся | Где используется | Фактическое значение | Проблема | +|---|---|---|---|---| +| SPRING_DATASOURCE_URL | application.yaml, docker-compose.yml | DataSource, HikariCP | `jdbc:postgresql://db:5432/messenger` | OK | +| SPRING_DATASOURCE_USERNAME | docker-compose.yml (secrets) | DataSource | читается из `/run/secrets/postgres_user` | OK | +| SPRING_DATASOURCE_PASSWORD | docker-compose.yml (secrets) | DataSource | читается из `/run/secrets/postgres_password` | OK | +| SPRING_FLYWAY_ENABLED | docker-compose.yml (migrate: true, api: false) | FlywayAutoConfiguration | migrate=true, api=false | OK | +| SPRING_PROFILES_ACTIVE | docker-compose.yml (api) | Spring Environment | `lab` (не определён) | D9 | +| SPRING_DATA_REDIS_HOST | application.yaml, docker-compose.yml | RedisConfig, LettuceConnectionFactory | `redis` | OK | +| S3_ENDPOINT | docker-compose.yml (api) | S3Properties, MinioClient | `http://minio:9000` | OK | +| S3_ACCESS_KEY_ID | docker-compose.yml (secrets) | S3Properties.resolvedAccessKey() | читается из секрета | D8 | +| S3_SECRET_ACCESS_KEY | docker-compose.yml (secrets) | S3Properties.resolvedSecretKey() | читается из секрета | D8 | +| SESSION_TTL_SECONDS | docker-compose.yml (api) | SessionProperties.ttl() | `400s` | OK | +| INSTANCE_ID | docker-compose.yml (api entrypoint) | InstanceProperties | `${HOSTNAME}` | OK | +| RECONCILER_ENABLED | docker-compose.yml (migrate: false) | ReconcilerProperties.enabled() | api: не задано (=true), migrate: false | OK | +| SPRING_TASK_SCHEDULING_ENABLED | docker-compose.yml (migrate) | Spring Boot scheduling | `false` | OK (для migrate) | +| SPRING_MAIN_WEB-APPLICATION-TYPE | docker-compose.yml (migrate entrypoint) | Spring Boot auto-config | `none` | OK (для migrate) | +| ShedLock table | V1__init.sql | ShedLockConfig | `shedlock` | OK | +| shedlock.lock_at_most_for | ShedLockConfig | JdbcTemplateLockProvider | `30m` | OK | +| reconciler.interval-ms | application.yaml | @Scheduled(fixedDelayString) | `3600000` (1 час) | OK | +| reconciler.lock-at-most-for | @SchedulerLock | ShedLock | `30m` | OK | +| reconciler.lock-at-least-for | @SchedulerLock | ShedLock | `1m` | OK | +| MAX_UPLOAD_BYTES | application.yaml | MultipartConfigElement | `10485760` (10 MiB) | OK | +| rate.rate-per-minute | application.yaml | Bucket4j | `600` | OK | + +--- + +## F. Scheduled / ShedLock / Reconciler — детальный анализ + +### Объявление @EnableScheduling +**Файл:** `MessengerLab1Application.java` +```java +@SpringBootApplication(...) +@EnableScheduling +public class MessengerLab1Application { ... } +``` +**Статус:** OK — аннотация на main-классе. + +### Объявление @EnableSchedulerLock +**Файл:** `ShedLockConfig.java` +```java +@Configuration +@EnableSchedulerLock(defaultLockAtMostFor = "30m") +public class ShedLockConfig { + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider( + JdbcTemplateLockProvider.Configuration.builder() + .withJdbcTemplate(new JdbcTemplate(dataSource)) + .withTableName("shedlock") + .usingDbTime() + .build() + ); + } +} +``` +**Статус:** OK — используется `JdbcTemplateLockProvider` с таблицей `shedlock` и `usingDbTime()`. + +### Таблица shedlock +**Файл:** `V1__init.sql` +```sql +CREATE TABLE shedlock ( + name VARCHAR(64) NOT NULL PRIMARY KEY, + lock_until TIMESTAMP NOT NULL, + locked_at TIMESTAMP NOT NULL, + locked_by VARCHAR(255) NOT NULL +); +``` +**Статус:** OK — соответствует требованиям ShedLock 5.x. + +### Метод @Scheduled +**Файл:** `AttachmentReconciler.java` +```java +@Scheduled(fixedDelayString = "${reconciler.interval-ms:3600000}") +@SchedulerLock(name = "reconciler", + lockAtMostFor = "${reconciler.lock-at-most-for:30m}", + lockAtLeastFor = "${reconciler.lock-at-least-for:1m}") +public void reconcile() { + if (!reconcilerProps.enabled()) { + log.debug("Reconciler is disabled, skipping"); + return; + } + executeReconciliation(); +} +``` +**Статус:** OK — корректная комбинация `@Scheduled` + `@SchedulerLock`. + +### Условия управления +- **migrate контейнер:** `SPRING_TASK_SCHEDULING_ENABLED=false` + `RECONCILER_ENABLED=false` — планировщик отключён. OK. +- **api контейнер:** `RECONCILER_ENABLED` не задан → по умолчанию `true` (из `ReconcilerProperties`). OK. +- **dry-run:** `reconcilerProps.dryRun()` → если `true`, `executeReconciliation()` логирует и выходит без изменений. OK. + +### Координация нескольких реплик +ShedLock через таблицу `shedlock` гарантирует, что метод `reconcile()` выполнится только на одной реплике в любой момент времени. `lockAtMostFor=30m` предотвращает вечную блокировку при падении реплики. `lockAtLeastFor=1m` предотвращает повторное выполнение в течение 1 минуты. + +### Восстановление после падения +Если реплика падает во время выполнения reconciler'а, ShedLock автоматически снимёт блокировку по истечении `lockAtMostFor` (30 минут). Другая реплика начнёт выполнение. + +### Потенциальные проблемы +1. **Метод `reconcile()` публичный** — может быть вызван напрямую из тестов, обойдя ShedLock. Это не проблема для продакшена, но для тестов создаётся новый экземпляр `AttachmentReconciler` вручную (как видно из `AttachmentIntegrationTest.java`). +2. **`lockAtMostFor` в `@SchedulerLock` читается из свойства**, а не использует дефолт из `@EnableSchedulerLock`. Это корректно, но если свойство не задано, используется `30m`. OK. +3. **Нет отдельного bean для scheduling** — `@EnableScheduling` создаёт `ScheduledAnnotationBeanPostProcessor` автоматически. OK. + +--- + +## G. Docker и запуск + +### Правильный порядок запуска +1. Создать файлы secrets в `./secrets/` +2. `docker compose build` +3. `docker compose up -d db redis minio` +4. Дождаться healthcheck всех трёх сервисов +5. `docker compose up -d minio-init` (запускается автоматически через depends_on) +6. `docker compose up -d migrate` (запускается автоматически через depends_on) +7. Дождаться завершения migrate +8. `docker compose up -d api` (запускается автоматически через depends_on) +9. `docker compose up -d lb` (запускается автоматически через depends_on) + +### Выявленные проблемы +1. **Dockerfile не соберётся** из-за Gradle 9.7.1 (C4, C5) +2. **build.gradle не соберётся** из-за Spring Boot 4.1.1 и несуществующих артефактов (C1, C2) +3. **Секреты отсутствуют** — нужно создать файлы в `./secrets/` (C7) +4. **2 реплики API не запустятся** в обычном Compose — нужен `--scale api=2` или Swarm (C8) +5. **HEALTHCHECK использует readiness** вместо liveness (C6) + +--- + +## H. Матрица тестирования + +| Проверка | Статус | Причина | Что требуется | +|---|---|---|---| +| Health endpoint | ✅ Реализован | `HealthController` + `HealthService` | Сборка и запуск | +| Регистрация пользователей | ✅ Реализован | `UserController.registerUser()` | Сборка и запуск | +| Login / сессии | ✅ Реализован | `AuthController` + `SessionService` + Redis cache | Сборка и запуск | +| Чат CRUD | ✅ Реализован | `ChatController` + `ChatService` | Сборка и запуск | +| Отправка сообщений | ✅ Реализован | `MessageController` + `MessageService` | Сборка и запуск | +| Idempotency | ✅ Реализован | `IdempotencyService` + `IdempotencyRepository` (native query) | Сборка и запуск | +| Пагинация (cursor) | ✅ Реализован | `CursorCodec` + repository queries | Сборка и запуск | +| Ошибки доступа | ✅ Реализован | `GlobalExceptionHandler` + security config | Сборка и запуск | +| Загрузка файлов | ✅ Реализован | `AttachmentController` + `AttachmentService` + MinIO | Сборка и запуск | +| SHA-256 checksum | ✅ Реализован | `MessageDigest.getInstance("SHA-256")` в `AttachmentService.uploadToS3()` | Сборка и запуск | +| Logout / revoke | ✅ Реализован | `AuthController` + `SessionService.revoke()` | Сборка и запуск | +| Persistence (restart) | ⏳ Не проверено | Зависит от PostgreSQL volume | Запуск + тест | +| Failover (LB) | ⏳ Не проверено | Зависит от 2 API-реплик + nginx | Запуск + тест | +| Reconciler stale detection | ✅ Реализован | `AttachmentReconciler.reconcileStaleAttachments()` | Запуск + тест | +| Reconciler orphan cleanup | ✅ Реализован | `AttachmentReconciler.reconcileOrphanedS3Objects()` | Запуск + тест | +| Reconciler dry-run | ✅ Реализован | `ReconcilerProperties.dryRun()` | Запуск + тест | +| Reconciler verify READY | ✅ Реализован | `AttachmentReconciler.verifyReadyAttachments()` | Запуск + тест | +| Concurrent uploads | ✅ Реализован | `AttachmentIntegrationTest.shouldHandleConcurrentUploads()` | Запуск + тест | + +--- + +## I. План исправлений + +### Исправление 1: build.gradle — версии и имена зависимостей +**Файл:** `build.gradle` +**Текущая проблема:** Spring Boot 4.1.1 не существует, артефакты `spring-boot-starter-webmvc`, `spring-boot-starter-jackson` и др. не существуют. +**Предлагаемое изменение:** +```groovy +plugins { + id 'org.springframework.boot' version '3.3.5' // было 4.1.1 +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' // было webmvc + implementation 'org.springframework.boot:spring-boot-starter-jackson' // УДАЛИТЬ (часть web) + // ... + testImplementation 'org.springframework.boot:spring-boot-starter-test:3.3.5' // было 4.1.1 + // УДАЛИТЬ: spring-boot-starter-restclient-test, spring-boot-resttestclient + // УДАЛИТЬ: spring-boot-starter-actuator-test, spring-boot-starter-validation-test, spring-boot-starter-webmvc-test +} +``` +**Почему необходимо:** Без этого сборка невозможна. +**Функции, которые может затронуть:** Нет — это только исправление сборок. +**Как проверить:** `gradle bootJar --no-daemon` + +### Исправление 2: build.gradle — исправить netty dependency +**Файл:** `build.gradle` +**Текущая проблема:** `runtimeOnly 'io.netty:netty-transport-native-epoll::linux-x86_64'` (двойное двоеточие) +**Предлагаемое изменение:** +```groovy +runtimeOnly 'io.netty:netty-transport-native-epoll:4.1.115.Fallback:linux-x86_64' +``` +или удалить полностью (Netty уже включён как транзитивная зависимость Spring Boot). + +### Исправление 3: Dockerfile — использовать gradlew wrapper +**Файл:** `Dockerfile` +**Текущая проблема:** Ручная установка несуществующего Gradle 9.7.1. +**Предлагаемое изменение:** +```dockerfile +FROM eclipse-temurin:21-jdk-jammy AS builder +WORKDIR /build +COPY gradle gradle +COPY gradlew settings.gradle build.gradle ./ +RUN chmod +x gradlew +RUN ./gradlew dependencies --no-daemon +COPY contracts contracts +COPY src src +RUN ./gradlew bootJar -x test --no-daemon +``` +**Почему необходимо:** Dockerfile должен собираться с существующими инструментами. +**Функции, которые может затронуть:** Нет — это только Docker build. +**Как проверить:** `docker build -t messenger:test .` + +### Исправление 4: Dockerfile — HEALTHCHECK на liveness +**Файл:** `Dockerfile` +**Текущая проблема:** HEALTHCHECK проверяет readiness. +**Предлагаемое изменение:** +```dockerfile +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/actuator/health/liveness | grep -q UP || exit 1 +``` + +### Исправление 5: docker-compose.yml — scale для API +**Файл:** `docker-compose.yml` +**Текущая проблема:** `deploy.replicas: 2` не работает в Docker Compose v2. +**Предлагаемое изменение:** Удалить `deploy.replicas: 2` и запускать с `docker compose up --scale api=2 -d`. + +### Исправление 6: docker-compose.yml — HEALTHCHECK API +**Файл:** `docker-compose.yml`, service `api` +**Текущая проблема:** healthcheck проверяет readiness, но readiness зависит от БД. +**Предлагаемое изменение:** +```yaml +healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/health/live | grep -q 'ok'"] +``` + +### Исправление 7: Создать файлы secrets +**Файл:** `./secrets/*.txt` (7 файлов) +**Предлагаемое изменение:** Создать файлы: +``` +./secrets/postgres_db.txt → messenger +./secrets/postgres_user.txt → messenger +./secrets/postgres_password.txt → messenger_pass +./secrets/minio_root_user.txt → +./secrets/minio_root_password.txt → +./secrets/s3_access_key_id.txt → messenger_s3_user +./secrets/s3_secret_access_key.txt → messenger_s3_secret +``` + +### Исправление 8: requirements-dev.txt — добавить jsonschema +**Файл:** `requirements-dev.txt` +**Предлагаемое изменение:** +``` +openapi-spec-validator==0.7.2 +jsonschema==4.23.0 +``` + +### Исправление 9: settings.gradle — имя проекта +**Файл:** `settings.gradle` +**Предлагаемое изменение:** +```groovy +rootProject.name = 'messenger' +``` + +### Исправление 10: contracts/openapi.json — статус attachment +**Файл:** `contracts/openapi.json` +**Предлагаемое изменение:** Добавить все возможные статусы в enum: +```json +"status": { "type": "string", "enum": ["uploading", "ready", "broken"] } +``` + +--- + +## J. Итоговый вердикт + +### Вариант 1: Проект можно сохранить и точечно исправить ✅ + +**Обоснование:** +1. **Java-код написан качественно** — 92 Java-файла, чистая архитектура, корректные паттерны проектирования. +2. **Архитектура соответствует заданию** — 2 API-реплики, LB, PostgreSQL, Redis, MinIO, ShedLock, Flyway. +3. **Scheduled/Reconciler/ShedLock работают корректно** — правильная таблица, правильные провайдеры, правильные условия отключения для migrate. +4. **Аутентификация/авторизация реализована правильно** — Basic auth для login, Bearer token для API, Redis-кэш сессий. +5. **Критические проблемы — только в конфигурациях сборки** — build.gradle (версии Spring Boot), Dockerfile (Gradle version). Это исправляется точечно без переписывания кода. +6. **Docker-инфраструктура спроектирована правильно** — healthcheck-ы, depends_on, secrets, volumes, one-shot миграции. + +**Общее количество проблем:** 10 (4 критических, 6 некритических) +**Общее количество исправлений:** 10 (все точечные, без переписывания архитектуры) +**Оценка рисков:** Низкая — исправления касаются только конфигурационных файлов. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 1bec5472..ba7e26ea 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,10 @@ ## Лабораторная 4 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Иванов Данил БВТ2301 +Целевая оценка: 5, трек 2 — согласованность двух хранилищ. -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Исправлены контракт вложений/сообщений, ограничение входного потока, проверка изображения/MIME/filename, скачивание через API и отзыв сессий между репликами. Reconciler выполняет реальный dry-run и повторяемое исправление orphan/missing; PostgreSQL shared/exclusive advisory lock защищает окно S3 PUT → COMMIT на нескольких API. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Запуск, транзакционные границы, команды, результаты и ограничения: [REPORT.md](../REPORT.md). Методики: [tests/README.md](../tests/README.md). Доказательства: [evidence](../evidence/). + +Публичные tests и контракт не менялись. Проверки не заменяют HA БД/S3 и большого нагрузочного исследования. PR не опубликован; результаты относятся к рабочему дереву. Использована помощь Codex при аудите, исправлениях и проверках. 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 9ad2b84f..278284c0 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,91 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Иванов Данил, БВТ2301 (из шаблона PR проекта). +- Целевая оценка: **5, трек 2 — согласованность двух хранилищ**. +- Базовый commit: `057143dd915f0fe75b72e253db103800940eeb38`. Проверено изменённое рабочее дерево; PR не опубликован. +- Дата: 01.11.2026 (Europe/Moscow). Помощь Codex: аудит, исправления, тесты, отчёт. Библиотеки: [build.gradle](build.gradle). Источники: [README](README.md), [контракт](contracts/README.md), [OpenAPI](contracts/openapi.json). Публичные проверки и контракт не изменялись. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Docker Desktop с Linux containers/Compose, Python 3.9+, PowerShell 7. Проверены Temurin Java 21.0.13, PostgreSQL 16.15, Spring Boot 4.1.1, nginx 1.27-alpine, Redis 7.4-alpine. S3: сборка Silo на базе MinIO RELEASE.2026-10-26T00-00-00Z, закреплённая digest (pgsty/silo). Для локальных Java-тестов JDK 21; Docker собирает приложение самостоятельно. + +```powershell +pwsh -File scripts/bootstrap.ps1 +docker compose --env-file .env config --quiet +docker compose up -d --build +# Дождаться healthy обеих api и HTTP 200 /health/ready. +$env:BASE_URL='http://127.0.0.1:8080' +py tests/smoke.py +py tests/extended.py +py tests/faults.py +py tests/resilience.py --mode persistence --action-script scripts/restart.cmd +py tests/resilience.py --mode failover --action-script scripts/stop-one.cmd +docker compose up -d api +``` + +Bootstrap создаёт локальные secrets/.env, не печатает значения и не перезаписывает существующие файлы. Они исключены из Git. Flyway выполняется при старте API, собственная блокировка миграций координирует реплики. Профиль migration не нужен. MinIO bootstrap идемпотентно создаёт приватный bucket, отдельного app user и bucket policy; ошибки завершают bootstrap. S3 и mc закреплены digest. Консоль отключена, порты БД/S3/API наружу не опубликованы, LB — loopback:8080. + +Остановка с сохранением данных: `docker compose down`. Намеренное удаление учебных данных: `docker compose down -v`, не часть persistence. Linux hooks `.sh` требуют chmod +x. Методики всех проверок — [tests/README.md](tests/README.md). ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → nginx → API ×2 → PostgreSQL (ACL, пользователи, сессии, сообщения, идемпотентность, метаданные) + приватный MinIO (оригиналы). Redis не источник истины. Из lab3 сохранены Argon2, Bearer-сессии, keyset-пагинация и атомарная идемпотентность PostgreSQL. Сессии читаются из БД: исключена гонка заполнения кэша после logout. + +История сортируется по (created_at, id), cursor привязан к чату; snapshot между HTTP-страницами нет. Время назначает JVM каждой реплики (UTC, миллисекунды), UUID разрешает совпадение времени. Подтверждённые записи читаются из основной БД. При конкурентной вставке с временем раньше уже пройденного cursor запись может не попасть в текущий обход; необходима синхронизация часов хостов. Для неизменной истории повторов нет. + +Upload читает максимум 10 MiB + 1 byte. MIME сверяется с содержимым, лимит 40 млн пикселей проверяется до декодирования. Filename с управляющими символами/разделителями отклоняется; S3 key — UUID. Одна загрузка на реплику, ожидание слота до 30s; заданы heap/container limits и S3 timeouts. Оригиналы не сохраняются локально в API. Контроллеры делегируют работу сервисам. + +Upload-транзакция держит shared PostgreSQL advisory lock 741204. Reconciler берёт exclusive try-lock: либо пропускает цикл, либо видит завершённые загрузки. Это закрывает окно PUT → COMMIT между репликами, включая загрузки дольше grace. Ключи не переиспользуются. При падении после PUT/до COMMIT остаётся orphan, сверка удалит его после grace. Ошибка сохранения может компенсироваться сразу, ошибка COMMIT — сверкой. 201 возвращается после завершения транзакции. + +Reconciler выполняет S3 list и индексированные exists(object_key), затем постранично проверяет метаданные по id. READY → BROKEN не сдвигает страницы. Старый orphan удаляется, достоверный NoSuchKey переводит старую READY-запись в BROKEN. Сетевая ошибка не считается отсутствием. Метаданные сохраняются для диагностики; BROKEN возвращает 409 без невалидного ready DTO. Существующие используемые объекты не удаляются. Dry-run выполняет тот же обход, пишет решения и ничего не меняет. Публичная транзакционная граница Spring охватывает цикл. + +Настройки: [Compose](docker-compose.yml), [application.yaml](src/main/resources/application.yaml). Используются SESSION_TTL_SECONDS, RATE_PER_MINUTE, MAX_MESSAGES_PER_CHAT, S3_*, MAX_UPLOAD_BYTES/MAX_IMAGE_PIXELS, RECONCILER_*. Credentials поступают из secrets. SESSION_STORE не переключает реализацию: сессии всегда PostgreSQL. Readiness требует БД и S3, Redis не критичен. LB не повторяет произвольные POST после неопределённого результата. ## Доказательства критериев +Правила: [evidence/README.md](evidence/README.md). Токены и credentials не сохраняются. Итоговое состояние: [две healthy API и readiness](evidence/final-state.txt); точные исходники: [SHA-256 manifest](evidence/source-sha256.json); сводка JUnit: [unit-summary](evidence/unit-summary.json). Команды/методики: [tests/README.md](tests/README.md). + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Сборка, unit | docker compose build api; gradlew.bat test | Java build, fixture/filename/cursor | [build](evidence/build.txt), [unit](evidence/unit.txt) | +| Smoke, ACL, checksum, файл в сообщении | py tests/smoke.py | Сквозной контрактный сценарий | [smoke](evidence/smoke.txt) | +| Размер, corrupt, MIME, filename | extended.py | 413/415/400, без пользовательских 500 | [extended](evidence/extended.txt) | +| Чужие/повторные ID, другой чат, пустой текст с файлом | extended.py | 404/400; допустимое сообщение с файлом | [extended](evidence/extended.txt) | +| Конкурентная идемпотентность | extended.py | 24 повтора, 2 instance ID, одно сообщение | [extended](evidence/extended.txt) | +| Failover с оригиналом | resilience.py --mode failover | Реальная остановка обслужившей API | [failover](evidence/failover.txt), [до](evidence/stop-one-before.txt), [после](evidence/stop-one-after.txt), [hook](scripts/stop-one.ps1) | +| Restart всех зависимостей | resilience.py --mode persistence | Прежние сессия, сообщения, оригинал | [persistence](evidence/persistence.txt), [до](evidence/restart-before.txt), [после](evidence/restart-after.txt) | +| Private bucket / app user | faults.py и bootstrap | Direct GET существующего ключа → 403 | [faults](evidence/faults.txt), [policy](policy.json), [Compose](docker-compose.yml) | +| Отказ S3 и БД после PUT | faults.py | S3 → 503; DB reject без 201 и фиксации метаданных | [faults](evidence/faults.txt) | +| Конкурентные upload / RAM | extended.py | 20 × 8 674 413 bytes, concurrency=10, без ошибок | [extended](evidence/extended.txt) | +| Трек 2: orphan/missing, dry-run/apply/repeat, свежий объект | track2.py | Dry-run без изменений; orphan удалён, missing → BROKEN, свежий сохранён, повтор идемпотентен | [track2](evidence/track2.txt) | +| Окно PUT → COMMIT и прерывание клиента | locking.py; aborted.py | Исключительная блокировка недоступна до COMMIT; частичный запрос не создаёт данные | [locking](evidence/locking.txt), [aborted](evidence/aborted.txt) | +| Стоимость обхода | scheduled reconcile | elapsedMs цикла | [apply](evidence/reconciler-apply-log.txt), [dry-run](evidence/reconciler-dry-run-log.txt), [объём/лимиты](evidence/environment.json) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Гипотеза: общая транзакционная блокировка защищает активный PUT, повторяемая сверка устраняет рассогласования без удаления существующих используемых объектов. Инъекции: объект без метаданных; удаление bytes READY-записи; временный DB trigger отклоняет INSERT после PUT. Методики: [track2.py](tests/track2.py), [faults.py](tests/faults.py). Ускоренный опыт: interval=3s, grace=1min; defaults — 1h/15min. Перед apply выдерживается grace, свежий объект создаётся отдельно. Оба scheduler координируются через БД. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +Docker: 8 CPU, 8 212 668 416 bytes RAM. API ×2: CPU=1, RAM=512MiB, Xmx320m каждая; БД CPU=1/RAM=1GiB. Closed-loop: 20 PNG 1700×1700 со случайными RGB, 10 клиентов, 12.547s, ошибок 0. Максимум наблюдавшихся RSS samples: 454.1/454.8MiB. До настройки Xmx384m дал наблюдавшийся пик 502.3MiB ([предыдущий профиль](evidence/upload-before-tuning.json)); поэтому heap уменьшен до 320MiB и нагрузка повторена. Итог: [upload-summary.json](evidence/upload-summary.json). Дискретный docker stats может пропустить краткий пик. CPU во времени, p50/p95/p99 и максимальный throughput upload не измерялись: опыт проверяет RAM. Один локальный прогон без длительного прогрева. + +На уровне операций: S3 list, один индексированный exists на объект, HEAD старых метаданных, страницы БД. SQL OFFSET и count страниц добавляют стоимость; линейную асимптотику для большого набора не заявляем. Длительности записанных циклов apply (ms): [2709, 682, 552, 1896, 795, 676]. Это небольшой учебный набор. Объёмы — environment.json. Экстраполяция на большой bucket не проверена. + +| Воздействие | Что ожидаем | Что наблюдали | Восстановление / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| API stop | другая API обслуживает данные | failover stdout | Метрики восстановления в stdout | +| Restart DB/Redis/S3/API/LB | данные и сессия сохраняются | persistence, StartedAt | Volumes сохранены | +| S3 stop | 503 без ложного 201 | faults.py | После start S3, старые объекты сохранены | +| DB reject после PUT | rollback / orphan / compensation | нет 201 и новых метаданных | Сверка после grace | +| Orphan/missing | безопасный ремонт и повтор | track2.py | Удалённые инъекцией bytes не восстанавливаются | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Локальный стенд без HA для БД/S3/LB/host, без распределённой транзакции БД/S3. Внешний оператор может удалить bytes; сверка обнаруживает потерю, но не восстанавливает их. Блокировки координируют приложение, не сторонние S3 clients. При постоянных загрузках цикл может пропускаться; срок ремонта зависит от свободного окна/grace/интервала. Большой обход держит exclusive lock и задерживает upload. Следующие шаги: per-key fencing/leases, keyset-обход и ограничение persistence context; они пока не реализованы. Ссылка на PR будет доступна после публикации. + + +## Повторная проверка замечаний — 06.11.2026 + +Проверены все пять замечаний к commit 057143dd на текущем изменённом рабочем дереве. Новые изменения production-кода для этой проверки не потребовались. [Тест](tests/review_regressions.py), [stdout](evidence/review-regressions-2026-11-06.txt), [контекст, команда и SHA-256](evidence/review-regressions-2026-11-06.json). Требуется Pillow для синтетического JPEG. + +Результаты: 10 PNG/JPEG upload → 201, metadata → 200, download идентичен, ровно 10 новых метаданных, обе API-реплики. Message без файлов содержит attachment_ids=[], с файлом и пустым текстом → 201; чужой чат/неизвестный ID/посторонний → 404. Десять sample.png[:33] → 415, filename=../x.png → 400; БД и S3 до/после отклонённых загрузок не изменились. Валидный PNG ровно 1770843 bytes → 201 через nginx, checksum скачанного оригинала совпадает. + +Windows зарезервировала TCP 8057–8156, поэтому host:8080 недоступен для bind Docker. Проверка выполнена через тот же LB на 127.0.0.1:18080: [compose.review.yaml](compose.review.yaml) меняет только публикацию порта. Запуск: docker compose -f docker-compose.yml -f compose.review.yaml up -d; затем BASE_URL=http://127.0.0.1:18080 py tests/review_regressions.py. Для PowerShell задавать BASE_URL через $env:BASE_URL. Стенд оставлен на этом порту. Исправления рабочего дерева не меняют содержимое удалённого commit 057143dd. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..b7d8c64e --- /dev/null +++ b/build.gradle @@ -0,0 +1,73 @@ +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' + implementation 'org.springframework.boot:spring-boot-starter-jackson' + implementation("io.minio:minio:9.0.3") + + implementation 'net.javacrumbs.shedlock:shedlock-spring:5.14.0' + implementation 'net.javacrumbs.shedlock:shedlock-provider-jdbc-template:5.14.0' + + 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/compose.review.yaml b/compose.review.yaml new file mode 100644 index 00000000..2755ebfa --- /dev/null +++ b/compose.review.yaml @@ -0,0 +1,4 @@ +services: + lb: + ports: !override + - "127.0.0.1:18080:80" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..41c09e2c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,226 @@ +services: + db: + image: postgres:16-alpine + 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: + # Добавлена очистка от \n и \r для надежности на Windows + test: ["CMD-SHELL", "pg_isready -U $$(cat /run/secrets/postgres_user | tr -d '\\n\\r') -d $$(cat /run/secrets/postgres_db | tr -d '\\n\\r')"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + + redis: + image: redis:7.4-alpine + 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 + + migrate: + profiles: [migration] + build: + context: . + dockerfile: Dockerfile + entrypoint: + - "sh" + - "-c" + - | + export SPRING_DATASOURCE_USERNAME="$$(cat /run/secrets/postgres_user)"; + export SPRING_DATASOURCE_PASSWORD="$$(cat /run/secrets/postgres_password)"; + export S3_ACCESS_KEY_ID="$$(cat /run/secrets/s3_access_key_id)"; + export S3_SECRET_ACCESS_KEY="$$(cat /run/secrets/s3_secret_access_key)"; + exec java -Dfile.encoding=UTF-8 -Dspring.main.web-application-type=none -Dspring.main.keep-alive=false -jar app.jar + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_FLYWAY_ENABLED: "true" + RECONCILER_ENABLED: "false" + SPRING_TASK_SCHEDULING_ENABLED: "false" # Отключает фоновые задачи, чтобы контейнер успешно завершился + secrets: + - postgres_user + - postgres_password + - s3_access_key_id + - s3_secret_access_key + depends_on: + db: + condition: service_healthy + restart: "no" + networks: + - messenger-net + healthcheck: + disable: true + + api: + stop_grace_period: 40s + build: + context: . + dockerfile: Dockerfile + restart: unless-stopped + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + minio-init: + condition: service_completed_successfully + entrypoint: + - "sh" + - "-c" + - | + export INSTANCE_ID="$$(cat /etc/hostname)"; + export SPRING_DATASOURCE_USERNAME="$$(cat /run/secrets/postgres_user)"; + export SPRING_DATASOURCE_PASSWORD="$$(cat /run/secrets/postgres_password)"; + export S3_ACCESS_KEY_ID="$$(cat /run/secrets/s3_access_key_id)"; + export S3_SECRET_ACCESS_KEY="$$(cat /run/secrets/s3_secret_access_key)"; + exec java -Dfile.encoding=UTF-8 $$JAVA_OPTS -jar app.jar + environment: + RECONCILER_INTERVAL_MS: ${RECONCILER_INTERVAL_MS:-3600000} + RECONCILER_DRY_RUN: ${RECONCILER_DRY_RUN:-false} + RECONCILER_GRACE_PERIOD_MINUTES: ${RECONCILER_GRACE_PERIOD_MINUTES:-15} + JAVA_OPTS: -Xmx320m -Xss512k + RATE_PER_MINUTE: ${RATE_PER_MINUTE:-100000} + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} + SPRING_FLYWAY_ENABLED: "true" + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400} + SESSION_STORE: ${SESSION_STORE:-postgres} + SPRING_DATA_REDIS_HOST: redis + SPRING_DATA_REDIS_PORT: 6379 + MAX_MESSAGES_PER_CHAT: ${MAX_MESSAGES_PER_CHAT:-10000} + S3_ENDPOINT: http://minio:9000 + S3_BUCKET: messenger-attachments + S3_REGION: us-east-1 + secrets: + - postgres_user + - postgres_password + - s3_access_key_id + - s3_secret_access_key + networks: + - messenger-net + deploy: + replicas: 2 + resources: + limits: + cpus: '1.0' + memory: 512M + 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 + + lb: + image: nginx:1.27-alpine + restart: unless-stopped + ports: + - "127.0.0.1:8080:80" + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + api: + condition: service_healthy + networks: + - messenger-net + + minio: + image: pgsty/silo@sha256:7bb2aff6b89efe1cb1303c10fc21d579447434ed06649ac9ec05a5e2dbf30ad7 + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + MINIO_BROWSER: "off" + volumes: + - minio-data:/data + secrets: + - minio_root_user + - minio_root_password + networks: + - messenger-net + healthcheck: + test: ["CMD-SHELL", "curl -f http://localhost:9000/minio/health/ready || exit 1"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s + + minio-init: + image: pgsty/mc@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 + depends_on: + minio: + condition: service_healthy + entrypoint: > + /bin/sh -ec " + export MINIO_ROOT_USER=$$(cat /run/secrets/minio_root_user); + export MINIO_ROOT_PASSWORD=$$(cat /run/secrets/minio_root_password); + export S3_ACCESS_KEY_ID=$$(cat /run/secrets/s3_access_key_id); + export S3_SECRET_ACCESS_KEY=$$(cat /run/secrets/s3_secret_access_key); + until mc alias set local http://minio:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD; do + echo 'Waiting for MinIO...' && sleep 2; + done; + mc mb --ignore-existing local/messenger-attachments; + mc anonymous set none local/messenger-attachments; + mc admin user add local $$S3_ACCESS_KEY_ID $$S3_SECRET_ACCESS_KEY; + mc admin policy create local app-uploads-policy /tmp/policy.json; + mc admin policy attach local app-uploads-policy --user $$S3_ACCESS_KEY_ID; + echo 'MinIO initialization completed (bucket: messenger-attachments)'; + " + volumes: + - ./policy.json:/tmp/policy.json:ro + secrets: + - minio_root_user + - minio_root_password + - s3_access_key_id + - s3_secret_access_key + networks: + - messenger-net + restart: "no" + +volumes: + pgdata: + redisdata: + minio-data: + +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 + minio_root_user: + file: ./secrets/minio_root_user.txt + minio_root_password: + file: ./secrets/minio_root_password.txt + s3_access_key_id: + file: ./secrets/s3_access_key_id.txt + s3_secret_access_key: + file: ./secrets/s3_secret_access_key.txt diff --git a/evidence/aborted.txt b/evidence/aborted.txt new file mode 100644 index 00000000..9f88408d --- /dev/null +++ b/evidence/aborted.txt @@ -0,0 +1 @@ +PASS interrupted upload: connection closed before full body; metadata and S3 object listing unchanged diff --git a/evidence/build.txt b/evidence/build.txt new file mode 100644 index 00000000..28ec6446 --- /dev/null +++ b/evidence/build.txt @@ -0,0 +1,119 @@ + Image mtusi2026lab4-api Building +#1 [internal] load local bake definitions +#1 reading from stdin 507B 0.0s done +#1 DONE 0.0s + +#2 [internal] load build definition from Dockerfile +#2 transferring dockerfile: 1.09kB 0.0s done +#2 DONE 0.1s + +#3 [internal] load metadata for docker.io/library/eclipse-temurin:21-jdk-jammy +#3 ... + +#4 [internal] load metadata for docker.io/library/eclipse-temurin:21-jre-jammy +#4 DONE 0.8s + +#3 [internal] load metadata for docker.io/library/eclipse-temurin:21-jdk-jammy +#3 DONE 1.1s + +#5 [internal] load .dockerignore +#5 transferring context: 237B done +#5 DONE 0.1s + +#6 [internal] load build context +#6 DONE 0.0s + +#7 [builder 1/11] FROM docker.io/library/eclipse-temurin:21-jdk-jammy@sha256:4b1a74fbffbe6b4e7b6f0171a472478282fb463790a51edf10e465d578f22b69 +#7 resolve docker.io/library/eclipse-temurin:21-jdk-jammy@sha256:4b1a74fbffbe6b4e7b6f0171a472478282fb463790a51edf10e465d578f22b69 +#7 ... + +#8 [runner 1/5] FROM docker.io/library/eclipse-temurin:21-jre-jammy@sha256:1eac8b8fee11ca7d6725a48bc5d41992ed1561504ebae25490d2d062847e8269 +#8 resolve docker.io/library/eclipse-temurin:21-jre-jammy@sha256:1eac8b8fee11ca7d6725a48bc5d41992ed1561504ebae25490d2d062847e8269 0.5s done +#8 DONE 0.5s + +#7 [builder 1/11] FROM docker.io/library/eclipse-temurin:21-jdk-jammy@sha256:4b1a74fbffbe6b4e7b6f0171a472478282fb463790a51edf10e465d578f22b69 +#7 resolve docker.io/library/eclipse-temurin:21-jdk-jammy@sha256:4b1a74fbffbe6b4e7b6f0171a472478282fb463790a51edf10e465d578f22b69 0.5s done +#7 DONE 0.6s + +#6 [internal] load build context +#6 transferring context: 42.52kB 0.0s done +#6 DONE 0.2s + +#9 [builder 7/11] RUN unzip -q /tmp/gradle.zip -d /opt && rm /tmp/gradle.zip +#9 CACHED + +#10 [builder 8/11] RUN gradle dependencies --no-daemon +#10 CACHED + +#11 [builder 4/11] COPY gradle gradle +#11 CACHED + +#12 [builder 6/11] COPY gradle-9.7.1-bin.zip /tmp/gradle.zip +#12 CACHED + +#13 [builder 2/11] WORKDIR /build +#13 CACHED + +#14 [builder 3/11] RUN apt-get update && apt-get install -y --no-install-recommends unzip && rm -rf /var/lib/apt/lists/* +#14 CACHED + +#15 [builder 5/11] COPY gradlew settings.gradle build.gradle ./ +#15 CACHED + +#16 [builder 9/11] COPY contracts contracts +#16 CACHED + +#17 [builder 10/11] COPY src src +#17 DONE 5.7s + +#18 [builder 11/11] RUN gradle bootJar -x test --no-daemon +#18 1.359 To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/9.7.1/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation. +#18 2.956 Daemon will be stopped at the end of the build +#18 30.06 +#18 30.06 > Task :compileJava +#18 30.06 Note: /build/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java uses or overrides a deprecated API. +#18 30.06 Note: Recompile with -Xlint:deprecation for details. +#18 40.25 +#18 40.25 > Task :processResources +#18 40.25 > Task :classes +#18 40.25 > Task :resolveMainClassName +#18 45.05 > Task :bootJar +#18 45.11 +#18 45.11 [Incubating] Problems report is available at: file:///build/build/reports/problems/problems-report.html +#18 45.11 +#18 45.11 BUILD SUCCESSFUL in 44s +#18 45.11 4 actionable tasks: 4 executed +#18 45.11 Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.7.1/userguide/configuration_cache_enabling.html +#18 DONE 48.4s + +#19 [runner 2/5] WORKDIR /app +#19 CACHED + +#20 [runner 3/5] RUN groupadd --system spring && useradd --system --gid spring --no-create-home spring +#20 CACHED + +#21 [runner 4/5] COPY --from=builder /build/build/libs/*.jar app.jar +#21 DONE 4.0s + +#22 [runner 5/5] RUN chown spring:spring app.jar +#22 DONE 7.3s + +#23 exporting to image +#23 exporting layers +#23 exporting layers 9.8s done +#23 exporting manifest sha256:f00e792050e174a75cde5f4b956125ba7d36a8cfe33609b105e482472d5ce9d6 0.1s done +#23 exporting config sha256:92c76641eab13bc11abd71c0a35a9c9247dae83f41ae7a4c325b51bcfb04fcc7 +#23 exporting config sha256:92c76641eab13bc11abd71c0a35a9c9247dae83f41ae7a4c325b51bcfb04fcc7 0.1s done +#23 exporting attestation manifest sha256:8b2c56fd96a5b9747b6844bb0a6aef04df87bc6409e6b9ec109dce156a22ff6e +#23 exporting attestation manifest sha256:8b2c56fd96a5b9747b6844bb0a6aef04df87bc6409e6b9ec109dce156a22ff6e 0.1s done +#23 exporting manifest list sha256:47cb763f87e76f1d565b338531a1014058b598be3a544934f297a31a83a80cbb +#23 exporting manifest list sha256:47cb763f87e76f1d565b338531a1014058b598be3a544934f297a31a83a80cbb 0.1s done +#23 naming to docker.io/library/mtusi2026lab4-api:latest +#23 naming to docker.io/library/mtusi2026lab4-api:latest 0.0s done +#23 unpacking to docker.io/library/mtusi2026lab4-api:latest +#23 unpacking to docker.io/library/mtusi2026lab4-api:latest 1.6s done +#23 DONE 12.0s + +#24 resolving provenance for metadata file +#24 DONE 0.3s + Image mtusi2026lab4-api Built diff --git a/evidence/contract.txt b/evidence/contract.txt new file mode 100644 index 00000000..b62af9c5 --- /dev/null +++ b/evidence/contract.txt @@ -0,0 +1 @@ +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/environment.json b/evidence/environment.json new file mode 100644 index 00000000..38fe26e3 --- /dev/null +++ b/evidence/environment.json @@ -0,0 +1,19 @@ +{ + "date": "2026-11-01 Europe/Moscow", + "base_commit": "057143dd915f0fe75b72e253db103800940eeb38", + "working_tree": "modified; source hashes recorded separately", + "docker": "8 CPUs 8212668416 bytes", + "counts_format": "attachments|messages|users", + "api_limits": "2 replicas, each CPU=1 RAM=512MiB heap=320MiB", + "api_image": "sha256:47cb763f87e76f1d565b338531a1014058b598be3a544934f297a31a83a80cbb", + "reconcile_elapsed_ms": [ + 2709, + 682, + 552, + 1896, + 795, + 676 + ], + "reconcile_dataset_counts": "80|196|66", + "final_counts": "104|301|78" +} \ No newline at end of file diff --git a/evidence/extended.txt b/evidence/extended.txt new file mode 100644 index 00000000..d29fe9fe --- /dev/null +++ b/evidence/extended.txt @@ -0,0 +1,12 @@ +PASS negative: MIME, corrupt, oversized, filename, duplicate/unknown/cross-chat attachments +PASS 24 simultaneous idempotent requests across 2 replicas; one message +image_bytes= 8674413 memory_samples= ['mtusi2026lab4-api-2 425.5MiB / 512MiB\nmtusi2026lab4-api-1 427.2MiB / 512MiB\nmtusi2026lab4-lb-1 29.76MiB / 7.649GiB\nmtusi2026lab4-minio-1 245.1MiB / 7.649GiB\nmtusi2026lab4-db-1 54.5MiB / 1GiB\nmtusi2026lab4-redis-1 5.648MiB / 7.649GiB\n', 'mtusi2026lab4-api-2 438.1MiB / 512MiB\nmtusi2026lab4-api-1 433.1MiB / 512MiB\nmtusi2026lab4-lb-1 32.69MiB / 7.649GiB\nmtusi2026lab4-minio-1 246.3MiB / 7.649GiB\nmtusi2026lab4-db-1 63.9MiB / 1GiB\nmtusi2026lab4-redis-1 5.648MiB / 7.649GiB\n', 'mtusi2026lab4-api-2 447.6MiB / 512MiB\nmtusi2026lab4-api-1 453.1MiB / 512MiB\nmtusi2026lab4-lb-1 33.38MiB / 7.649GiB\nmtusi2026lab4-minio-1 247MiB / 7.649GiB\nmtusi2026lab4-db-1 64.46MiB / 1GiB\nmtusi2026lab4-redis-1 5.898MiB / 7.649GiB\n', 'mtusi2026lab4-api-2 454.1MiB / 512MiB\nmtusi2026lab4-api-1 454.8MiB / 512MiB\nmtusi2026lab4-lb-1 32.6MiB / 7.649GiB\nmtusi2026lab4-minio-1 247.8MiB / 7.649GiB\nmtusi2026lab4-db-1 64.63MiB / 1GiB\nmtusi2026lab4-redis-1 5.648MiB / 7.649GiB\n', 'mtusi2026lab4-api-2 453.7MiB / 512MiB\nmtusi2026lab4-api-1 449.7MiB / 512MiB\nmtusi2026lab4-lb-1 20.16MiB / 7.649GiB\nmtusi2026lab4-minio-1 248.8MiB / 7.649GiB\nmtusi2026lab4-db-1 65.42MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n', 'mtusi2026lab4-api-2 453.9MiB / 512MiB\nmtusi2026lab4-api-1 443.8MiB / 512MiB\nmtusi2026lab4-lb-1 9.195MiB / 7.649GiB\nmtusi2026lab4-minio-1 249.6MiB / 7.649GiB\nmtusi2026lab4-db-1 65.41MiB / 1GiB\nmtusi2026lab4-redis-1 5.898MiB / 7.649GiB\n'] +PASS 20 uploads concurrency=10 elapsed_seconds= 12.547 +mtusi2026lab4-api-2 453.6MiB / 512MiB +mtusi2026lab4-api-1 443.8MiB / 512MiB +mtusi2026lab4-lb-1 9.188MiB / 7.649GiB +mtusi2026lab4-minio-1 249.6MiB / 7.649GiB +mtusi2026lab4-db-1 65.65MiB / 1GiB +mtusi2026lab4-redis-1 5.898MiB / 7.649GiB + +PASS logout across replicas diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..d4e0c5ba --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,3 @@ +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 99, "failed_attempts": 0, "first_recovery_seconds": 2.578} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/faults.txt b/evidence/faults.txt new file mode 100644 index 00000000..5e7c192a --- /dev/null +++ b/evidence/faults.txt @@ -0,0 +1,3 @@ +PASS direct anonymous GET existing object returns 403 +PASS S3 outage: readiness and upload return 503 +PASS DB failure: no success response, no committed metadata; orphan cleanup covered by track2 diff --git a/evidence/final-state.txt b/evidence/final-state.txt new file mode 100644 index 00000000..f66f7d6e --- /dev/null +++ b/evidence/final-state.txt @@ -0,0 +1,8 @@ +2026-11-01 Europe/Moscow +GET /health/ready: 200; two distinct X-Instance-Id observed +api Up 55 seconds (healthy) +api Up 55 seconds (healthy) +db Up 55 seconds (healthy) +lb Up 55 seconds +minio Up 55 seconds (healthy) +redis Up 55 seconds (healthy) diff --git a/evidence/locking.txt b/evidence/locking.txt new file mode 100644 index 00000000..0584e31d --- /dev/null +++ b/evidence/locking.txt @@ -0,0 +1 @@ +PASS PUT/COMMIT barrier: uncommitted metadata invisible; exclusive reconcile lock denied during upload; released after commit; other member downloads identical bytes diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..749fd29b --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,2 @@ +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/private-bucket.txt b/evidence/private-bucket.txt new file mode 100644 index 00000000..e1a29c1f --- /dev/null +++ b/evidence/private-bucket.txt @@ -0,0 +1 @@ +403 diff --git a/evidence/reconciler-apply-log.txt b/evidence/reconciler-apply-log.txt new file mode 100644 index 00000000..0b493e5d --- /dev/null +++ b/evidence/reconciler-apply-log.txt @@ -0,0 +1,9 @@ +2026-10-31 23:05:08,625 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=false key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:05:08,753 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=false key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:05:09,646 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=false id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:05:09,833 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=2709 +2026-10-31 23:05:13,718 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=682 +2026-10-31 23:05:17,277 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=552 +2026-10-31 23:05:12,894 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=1896 +2026-10-31 23:05:16,707 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=795 +2026-10-31 23:05:20,451 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=false elapsedMs=676 \ No newline at end of file diff --git a/evidence/reconciler-dry-run-log.txt b/evidence/reconciler-dry-run-log.txt new file mode 100644 index 00000000..4dc68cc6 --- /dev/null +++ b/evidence/reconciler-dry-run-log.txt @@ -0,0 +1,175 @@ +2026-10-31 23:02:31,306 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:32,211 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=2613 +2026-10-31 23:02:36,553 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:37,581 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=3100 +2026-10-31 23:02:40,774 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:42,152 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=1474 +2026-10-31 23:02:48,262 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:49,457 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=1290 +2026-10-31 23:02:52,480 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:53,058 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=595 +2026-10-31 23:03:02,111 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:02,363 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=269 +2026-10-31 23:03:05,402 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:05,708 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=338 +2026-10-31 23:03:14,732 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:15,168 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=449 +2026-10-31 23:03:18,187 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:18,460 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=284 +2026-10-31 23:03:21,473 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:38,331 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:38,848 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=540 +2026-10-31 23:03:21,778 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=314 +2026-10-31 23:03:24,805 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:24,989 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:25,023 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=238 +2026-10-31 23:03:28,036 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:45,002 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:46,786 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=1884 +2026-10-31 23:03:28,203 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:28,284 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=257 +2026-10-31 23:03:31,295 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:02:49,808 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:31,376 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:31,401 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=113 +2026-10-31 23:02:50,698 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=905 +2026-10-31 23:03:34,413 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:34,497 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:02,757 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:34,523 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=118 +2026-10-31 23:03:37,535 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:03,215 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=497 +2026-10-31 23:03:37,635 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:37,664 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=139 +2026-10-31 23:03:40,688 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:40,755 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:40,774 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=104 +2026-10-31 23:03:43,787 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:43,905 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:43,947 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=169 +2026-10-31 23:03:46,971 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:47,056 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:47,077 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=125 +2026-10-31 23:03:06,231 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:50,101 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:06,526 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=306 +2026-10-31 23:03:50,175 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:50,194 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=111 +2026-10-31 23:03:15,545 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:53,206 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:53,302 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:53,365 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=168 +2026-10-31 23:03:56,381 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:56,460 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:56,494 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=123 +2026-10-31 23:03:59,509 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:15,923 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=389 +2026-10-31 23:03:59,610 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:59,650 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=151 +2026-10-31 23:04:02,675 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:18,964 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:03,062 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:03,119 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=463 +2026-10-31 23:04:06,130 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:19,280 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=351 +2026-10-31 23:04:06,278 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:06,316 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=194 +2026-10-31 23:04:09,340 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:22,298 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:09,605 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:22,615 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=328 +2026-10-31 23:03:25,629 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:25,831 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:25,904 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=286 +2026-10-31 23:03:28,920 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:29,039 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:29,106 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=198 +2026-10-31 23:03:32,132 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:09,638 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=319 +2026-10-31 23:03:32,314 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:12,654 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:12,850 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:32,341 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=228 +2026-10-31 23:04:12,880 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=238 +2026-10-31 23:04:15,901 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:15,991 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:35,365 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:16,074 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=189 +2026-10-31 23:04:19,088 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:35,459 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:35,502 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=157 +2026-10-31 23:03:38,535 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:19,188 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:19,218 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=138 +2026-10-31 23:04:22,236 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:38,654 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:38,682 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=176 +2026-10-31 23:03:41,696 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:22,371 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:41,803 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:22,399 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=176 +2026-10-31 23:04:25,413 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:25,455 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:25,596 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:41,836 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=150 +2026-10-31 23:04:25,675 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=273 +2026-10-31 23:04:28,690 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:28,714 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:28,773 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:44,859 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:28,799 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=120 +2026-10-31 23:03:44,942 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:44,993 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=152 +2026-10-31 23:03:48,005 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:31,809 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:31,837 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:31,904 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:48,091 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:48,113 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=115 +2026-10-31 23:04:31,965 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=162 +2026-10-31 23:03:51,135 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:51,206 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:51,223 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=105 +2026-10-31 23:03:54,252 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:54,423 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:54,508 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=279 +2026-10-31 23:03:57,534 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:03:57,708 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:03:57,735 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=221 +2026-10-31 23:04:00,758 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:00,928 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:01,092 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=351 +2026-10-31 23:04:04,112 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:04,214 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:04,290 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=193 +2026-10-31 23:04:07,311 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:07,394 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:07,427 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=136 +2026-10-31 23:04:10,449 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:10,611 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:10,646 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=214 +2026-10-31 23:04:13,671 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:14,026 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:14,076 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=425 +2026-10-31 23:04:17,086 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:17,189 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:17,215 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=135 +2026-10-31 23:04:20,236 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:20,338 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:20,363 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=143 +2026-10-31 23:04:23,387 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:23,437 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:23,618 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:23,718 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=349 +2026-10-31 23:04:26,746 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:26,799 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:26,893 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:26,939 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=216 +2026-10-31 23:04:29,960 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:29,999 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:30,054 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:30,091 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=147 +2026-10-31 23:04:33,108 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=096fb076-173f-43ab-9779-87748b3f5901 +2026-10-31 23:04:33,145 INFO [] r.m.m.s.AttachmentReconciler - Reconcile orphan dryRun=true key=proof-3146543cd1fe4a9baa759dd244768dfe +2026-10-31 23:04:33,280 INFO [] r.m.m.s.AttachmentReconciler - Reconcile missing dryRun=true id=aba148cc-25a4-45b5-9e9b-e1932d97ac4b +2026-10-31 23:04:33,321 INFO [] r.m.m.s.AttachmentReconciler - Reconcile complete dryRun=true elapsedMs=226 \ No newline at end of file diff --git a/evidence/restart-after.txt b/evidence/restart-after.txt new file mode 100644 index 00000000..70af5ff3 --- /dev/null +++ b/evidence/restart-after.txt @@ -0,0 +1,6 @@ +/mtusi2026lab4-api-1 2026-10-31T23:07:53.373414795Z +/mtusi2026lab4-api-2 2026-10-31T23:07:53.246086496Z +/mtusi2026lab4-db-1 2026-10-31T23:07:53.514536294Z +/mtusi2026lab4-lb-1 2026-10-31T23:07:53.295382239Z +/mtusi2026lab4-minio-1 2026-10-31T23:07:52.724899356Z +/mtusi2026lab4-redis-1 2026-10-31T23:07:52.593327772Z diff --git a/evidence/restart-before.txt b/evidence/restart-before.txt new file mode 100644 index 00000000..d9c6d0bf --- /dev/null +++ b/evidence/restart-before.txt @@ -0,0 +1,6 @@ +/mtusi2026lab4-api-1 2026-10-31T23:05:39.650988072Z +/mtusi2026lab4-api-2 2026-10-31T23:07:01.788885681Z +/mtusi2026lab4-db-1 2026-10-31T22:56:53.864795289Z +/mtusi2026lab4-lb-1 2026-10-31T23:02:01.211664851Z +/mtusi2026lab4-minio-1 2026-10-31T22:56:53.561984546Z +/mtusi2026lab4-redis-1 2026-10-31T22:56:53.117528456Z diff --git a/evidence/review-regressions-2026-11-06.json b/evidence/review-regressions-2026-11-06.json new file mode 100644 index 00000000..5ddfcee2 --- /dev/null +++ b/evidence/review-regressions-2026-11-06.json @@ -0,0 +1,24 @@ +{ + "date": "2026-11-06 Europe/Moscow", + "base_commit": "057143dd915f0fe75b72e253db103800940eeb38", + "scope": "current uncommitted working tree, not remote commit", + "base_url": "http://127.0.0.1:18080", + "port_reason": "Windows excluded TCP range 8057-8156 includes 8080; separate Compose override changes only host publication", + "command": "docker compose -f docker-compose.yml -f compose.review.yaml up -d; BASE_URL=http://127.0.0.1:18080 py tests/review_regressions.py", + "jpeg_generator": "Pillow 12.3.0; synthetic RGB image", + "generated_mapper_mime_lines": [ + "attachmentDTO.setContentType( mapContentType( entity.getContentType() ) );", + "attachment.setContentType( contentType );" + ], + "mime_enum_valueOf_present": false, + "sha256": { + "src/main/java/ru/mtusi/messenger/mapper/AttachmentMapper.java": "04d419c72a402b8c48462a6a38c243837e3163b42165d478afe844d3aad0ab2d", + "src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java": "3dda594258f94aed0322bedb76cd031faf325b52ec49d4ad9d6316e38570a9cb", + "src/main/java/ru/mtusi/messenger/dto/MessageDTO.java": "c136940d1f406797220bf7b6f65e604694bca64f6a9553ce1c30d653a0b9745d", + "src/main/java/ru/mtusi/messenger/validation/AttachmentValidator.java": "bc0a335f7d32b6b659c42cdd24858b8817e1558b338f5f8c075f8375c4ee6b15", + "nginx.conf": "5d7753018d2e6a3c141963d932571382abdffe45869c1e98bc58dda015e6fd0f", + "tests/review_regressions.py": "511cd9ca5ba4905a21d4dda2ac79bd16a29edb940c4a29d9c1f78ff2de2c57b2", + "compose.review.yaml": "66b48810a6eb1e78c2e6c3bb3be53c504c8d9e237cdf8c2204d3b922f89bdc78" + }, + "containers": "api Up 6 minutes (healthy) 8080/tcp\napi Up 6 minutes (healthy) 8080/tcp\ndb Up 6 minutes (healthy) 5432/tcp\nlb Up 56 seconds 127.0.0.1:18080->80/tcp\nminio Up 4 minutes (healthy) 9000/tcp\nredis Up 6 minutes (healthy) 6379/tcp\n" +} \ No newline at end of file diff --git a/evidence/review-regressions-2026-11-06.txt b/evidence/review-regressions-2026-11-06.txt new file mode 100644 index 00000000..5652bb29 --- /dev/null +++ b/evidence/review-regressions-2026-11-06.txt @@ -0,0 +1,6 @@ +2026-11-06 Europe/Moscow; current working tree; synthetic data only +PASS PNG/JPEG: 10 uploads -> 201; 10 metadata GET -> 200; 10 downloads identical; DB +10; instances=2 +PASS messages: plain attachment_ids=[]; file-only POST -> 201; cross-chat/unknown/outsider -> 404 +PASS sample.png[:33]: 10 x 415; ../x.png: 400; DB and S3 unchanged +PASS valid PNG exactly 1770843 bytes: POST -> 201 through LB; download checksum matches +PASS all five review regressions diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..c554fd6f --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1 @@ +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/source-sha256.json b/evidence/source-sha256.json new file mode 100644 index 00000000..2efb0ddc --- /dev/null +++ b/evidence/source-sha256.json @@ -0,0 +1,134 @@ +{ + "src/main/java/ru/mtusi/messenger/MessengerLab1Application.java": "ebff5c9496dda66c8137788564f170ece5ac5bebb2e1e1b13b0bc351057c4c01", + "src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java": "01247b304b36da4115f64d1850cf417e6c050d4d833faf0477fe9e8ec4726d47", + "src/main/java/ru/mtusi/messenger/config/JacksonConfig.java": "d81cf57029887349a496e96c31a856726f4e376075723425777f2e04a1d4d4c4", + "src/main/java/ru/mtusi/messenger/config/MinioConfig.java": "4fa20cd0bbd6f7923fbba5dce0f6faace584d797e50bbac2c0e9c0bb6f4341b2", + "src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java": "214152ac0da558a2953c3b8ed5a6378917bc904eaf89a6d248af5ec27b2afb66", + "src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java": "a529b58411902caff30048449e806ad3435be537257d7c7c66b733d6f29a7c8d", + "src/main/java/ru/mtusi/messenger/config/RedisConfig.java": "7c46490bbdc8a71fd7bf1932a4b0473effb2c29ef9e8e0d5eee2535b623912b7", + "src/main/java/ru/mtusi/messenger/config/SecurityConfig.java": "11a7b514390a004fa0facf67767b7cb33363fb5bc9a00e6e63dde3ff48f12b4a", + "src/main/java/ru/mtusi/messenger/config/ShedLockConfig.java": "7b316cc874133b9d0cb765662db093ffa500a095cbed66733921d27918c22886", + "src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java": "6b6bb675240794dd9e23ca0f0c00c1643be63568f317edd0abffa2fdfbdaa6eb", + "src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java": "acf9c9d25f1f5685dbed0e7a34bfc90a690d7bd964f4c65a25a9e5bdaaabf2ae", + "src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java": "6948d3846adddad1882b6f5351ee5e3a3bffb62f6ead726fdd1226a272545c8f", + "src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java": "cc0903db00b44e79b32d58c1507f96b10c4a8bf950eaa2702947aed8b9e82b17", + "src/main/java/ru/mtusi/messenger/config/properties/ReconcilerProperties.java": "b15f02fe0dd4a42b5f20d96a2be293095955d959afe6493f3c02d77399164573", + "src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java": "28a9da022e39f639d46e6a3d64d55065058db7cccda2f46c54506e93c954909d", + "src/main/java/ru/mtusi/messenger/config/properties/S3Properties.java": "810b5a44bb487c4a4e0f5790f5011c8575becd43f06694d46aed2a417053ba50", + "src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java": "412cd9380e9962c14f179d8d95103a6a1efead47be08913085e13dc478858639", + "src/main/java/ru/mtusi/messenger/config/properties/UploadProperties.java": "e28d7084351928728a15527dc1ddd3ff3386c2b91a948265fe73308e8cda27fa", + "src/main/java/ru/mtusi/messenger/controller/AttachmentController.java": "c714109087d223387fcb30afe5d719a94d8acd4fd36c6208c471921b1d28086a", + "src/main/java/ru/mtusi/messenger/controller/AttachmentsApi.java": "cd24b1773b7c12d146bf929510c7421e84ff41e31390717b491586ae1c245e96", + "src/main/java/ru/mtusi/messenger/controller/AuthApi.java": "cc5879043e166008d6d5d899339d91473f1a95dac729999ab3af809926a3157f", + "src/main/java/ru/mtusi/messenger/controller/AuthController.java": "06c823e3718e387922e05eebe75f44a8321661d8f57d2636f1a6b5b5f1490fe1", + "src/main/java/ru/mtusi/messenger/controller/ChatController.java": "91c280c54767d88c55a17d6b8bf1be1fc1a209582b6f99afe1ceb4370613202a", + "src/main/java/ru/mtusi/messenger/controller/ChatsApi.java": "d2b467ddb281e742e02925e52f50ec8f45bcb3d9371e2445ef34a6b2637e6a67", + "src/main/java/ru/mtusi/messenger/controller/HealthApi.java": "f13f8333478cbb92f2c669f031b5860d28d6c5aa2fc72678f98eb881fc4c20c3", + "src/main/java/ru/mtusi/messenger/controller/HealthController.java": "5975098719aa56f14db3528defd64acec2e4bd8e8bf791c68ac3463ebbb1def2", + "src/main/java/ru/mtusi/messenger/controller/MessageController.java": "307891082d0e658e1cc7cfc184501fcf15724b2cbffb0a77905953c54831c0d8", + "src/main/java/ru/mtusi/messenger/controller/MessagesApi.java": "b0751aad2ac3a5928659a62e3815d7246f0706a1a38498d05d2cefc48f6ab670", + "src/main/java/ru/mtusi/messenger/controller/UserController.java": "ea2f842e70694cf4135b9803eb19ecea3dd21e268fd140e8a7ac196c93aac199", + "src/main/java/ru/mtusi/messenger/controller/UsersApi.java": "01fcddf9d694706cbdbba94b3a1bad479939e845948b1b7f9ad61f8dcaf5d00e", + "src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java": "d3c65a3f6c7becf2a0acc33f76a58fa24fb99810525c03821b19359a31e3fd4e", + "src/main/java/ru/mtusi/messenger/dto/AttachmentDTO.java": "c99729a1c6f84979a53a196970cc8d20fbdde13adacd1606294fc9d9dc8bb98f", + "src/main/java/ru/mtusi/messenger/dto/ChatDTO.java": "33ce24cf9d1265f2ec0f7f4e490dd6d143e93385a91289c926bf8fbe20382d3f", + "src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java": "dec21d65e2eea9f5c3250b0ee8c8c83c8de7c48db2de2757982dbb0ece6dd67a", + "src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java": "e2fb6c482022e89b22d790d7c25769411e2277768f40bc7d99cc513dc4b272f3", + "src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java": "3dda594258f94aed0322bedb76cd031faf325b52ec49d4ad9d6316e38570a9cb", + "src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java": "77be22f51ed669cb26b27c2d848050b8d9a54748b51b4e2d45dda9ab925bc02c", + "src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java": "93cf9f964cb70f8a95293c0c0014a703178d478d67380ccfe4c5b220e780b2a1", + "src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java": "1b5431f78b23bdf27a327ae3bf89d52f66a5394f0a5902688245538bfae0262e", + "src/main/java/ru/mtusi/messenger/dto/HealthDTO.java": "ba735da4c3bb594a2022449813426fd1f7b63dc1e5fca1f19b9dc3a20268abd0", + "src/main/java/ru/mtusi/messenger/dto/MessageDTO.java": "c136940d1f406797220bf7b6f65e604694bca64f6a9553ce1c30d653a0b9745d", + "src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java": "fdf92495fe8911e21c44bce2e17871a19ac3225dca2ef35228dfb3cce312c631", + "src/main/java/ru/mtusi/messenger/dto/SessionDTO.java": "18df9b2402c31cd9f29eeb62dbf50369de449f8af9abb1454425290254f7fda8", + "src/main/java/ru/mtusi/messenger/dto/UserDTO.java": "b0c0b9e39df18d86c04ef3cec08af3b8eabb14a963b8a440df0407cbfb5c77a3", + "src/main/java/ru/mtusi/messenger/dto/VariantDTO.java": "2271032b5450f486dc315b1fe8adc554e48835a3febad7024e73fd7ba483f11e", + "src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java": "decfec03fcc44355356239a5c967d8fc5e94d0244e6f629ba5e25a2e727491ad", + "src/main/java/ru/mtusi/messenger/exception/ConflictException.java": "e4a73d92c86ea8ca411db8f8995a0ff4be4ba422898fda7d5d4b98dfc79681ce", + "src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java": "382c8fb84ebc3d591cbf0633f65e57df9aa5652ecd2068673ff2c0d2f55630f5", + "src/main/java/ru/mtusi/messenger/exception/NotFoundException.java": "e167e13943712563093ce4ec988b9cc291d872059e4125cb5b825b5d0e6579f1", + "src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java": "9b9be34b4d897619e65666efc11ddde6ca0e330a14d20ede25dc22694cdd33e1", + "src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java": "c88f435c66c7e5db6076d0a5706e2be49606fe300d816e08cdc88fd6da7c404d", + "src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java": "110b237c0cce9d57b8520b5ba5345e65552481dde0700a88b7646363d9dc90b4", + "src/main/java/ru/mtusi/messenger/exception/StaleAttachmentException.java": "903877e733a5a9717d6b19d5f0635d9284bc59c30e67f3778780e7e794dfaddb", + "src/main/java/ru/mtusi/messenger/exception/StorageUnavailableException.java": "8a5780f38d5e47505b247874c9418bfba9e4841bae2a41938700a180a349b1e8", + "src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java": "2c3b0dce5c04947a1e1d5fd50130433b204b8155315ef49e7915775f65451213", + "src/main/java/ru/mtusi/messenger/exception/UnsupportedMediaTypeException.java": "28889bc84475c4319f13f3e76dd3b9939325837afb7bb25d5d93f8ff0fe985d6", + "src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java": "1927510c6524e7925a44ad6f27863dc88872ca429c1dd2d88b84e8cdddfce336", + "src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java": "794ae35e8bf7654bd2822316159a0026a371e1f64c0428dbc0d947c2baf45a6b", + "src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java": "4a0deae7a6dda1cce176caebb86f0dbeae06bc021cb283084cdd8ceb453de374", + "src/main/java/ru/mtusi/messenger/mapper/AttachmentMapper.java": "04d419c72a402b8c48462a6a38c243837e3163b42165d478afe844d3aad0ab2d", + "src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java": "44a598e24d18302cf0252a8784b54f861387f0c64e2317a4cd108e759e277689", + "src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java": "ccbf70b59f9b6d574849462b00e7be4d5ff13fe14cc35dbf7fc63ebacc383f1b", + "src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java": "2102ae913a14ac0e564470b6ae429f721fbb0bc2473ae0e15d2b23cd184671a3", + "src/main/java/ru/mtusi/messenger/mapper/UserMapper.java": "62e859c1263976b652d32a0ffd4d0a8c2d0f38df0ae94c627c55cc57cd90b7eb", + "src/main/java/ru/mtusi/messenger/model/Attachment.java": "08558ff1903ec23da66e105b54fc591e493dc230752f263296c322d0372735b6", + "src/main/java/ru/mtusi/messenger/model/AttachmentStatus.java": "c0b2814d1b59aefdb52938caf52207b507313d2afedc9b2440f8cea96b235db1", + "src/main/java/ru/mtusi/messenger/model/Chat.java": "71edfe3387e148d59e2c991e01611d4ad632291ca55c990ec05b4497993cbc04", + "src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java": "ba71e214c392487503c7376af03cc109a5d364cf580a5c755686ec4a53240036", + "src/main/java/ru/mtusi/messenger/model/Message.java": "487a3552f72d68d56d3193c36ee04857e6f0807454ddb8860e639dbcabc122d4", + "src/main/java/ru/mtusi/messenger/model/Session.java": "dbffe079041d5819ac1f80f62d671b84d9e679c28894a14c122dbe734ba81e73", + "src/main/java/ru/mtusi/messenger/model/User.java": "99fe24ee3adb30effc690792276c8473b5d2878ef140845db6af7d04594f93e3", + "src/main/java/ru/mtusi/messenger/repository/AttachmentRepository.java": "6d257db7b1f61e9610f3b1061c7dbdc57b9dce0b4ce9d2aad8f35e586e81f157", + "src/main/java/ru/mtusi/messenger/repository/ChatRepository.java": "cea1f215afc44a5a9fc434166e562b1f463872994ef0a5881fa9570922d88e7c", + "src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java": "224bf69df8f6b7c5902296849c3a20cf025deb3893d7a7343ac0b76962abf9a5", + "src/main/java/ru/mtusi/messenger/repository/MessageRepository.java": "a9b3e6e2fba5b346c4769eff5b7242bd938ccb34a3f5a9e677e37ba6b66d1b33", + "src/main/java/ru/mtusi/messenger/repository/SessionRepository.java": "a3243410e63515462f7a3c01388dddb0641c26aa5d20549cdb56872713b8df83", + "src/main/java/ru/mtusi/messenger/repository/UserRepository.java": "3fcd0b14687fbdb638662e5cfa0c005817ccb3e0590e97cfd87ce3f1cabdb13f", + "src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java": "424e3edbd796b442f820fc48ec9b55c0045fc60490b18138b62856ddd5116eaf", + "src/main/java/ru/mtusi/messenger/security/BasicCredentials.java": "025355bb417d99bc54b4d25bfeba1c42f1eda2b3e121832875ba7db5a95d8c55", + "src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java": "4372c93961b8ddde8cc8d9c337a9d595e1b07366b58aab951f928de570258182", + "src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java": "24c1f7ebb83e514480db0b9be0430c500850dedb9a8f9a8982d008eba9a00384", + "src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java": "ddc3755f8859e585146c721f996da757bd5dca53dd781bfbf4297fef7ba1b574", + "src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java": "9581156a00d7f6124c80c034cd210506e1b040abdba229e1200bb07a61474801", + "src/main/java/ru/mtusi/messenger/service/AttachmentReconciler.java": "fe1084a7ea72c0598b9a6fb51bf9bd38b787cab1bfeacd3aa136581c4bd10d0e", + "src/main/java/ru/mtusi/messenger/service/AttachmentService.java": "d9a4d2b6d7eab490357d5306905d2b0f36ef0ee3da012bde1e76aae4d6e3fe63", + "src/main/java/ru/mtusi/messenger/service/AuthService.java": "f885882f4700a1751e30a7839af7dac6c3b6baa2bbdf445ce9b5271131748508", + "src/main/java/ru/mtusi/messenger/service/ChatService.java": "b1fca78031db1a57af8ce8ee7f00b340169548d1ffb5857cfb9aa87afce10652", + "src/main/java/ru/mtusi/messenger/service/HealthService.java": "3a870d6848c784a5f53caa65eeb442bd3c4591a842b7ed9dcd2381739cf89195", + "src/main/java/ru/mtusi/messenger/service/IdempotencyService.java": "3b3d2b874c4c2684eab8fd8d65c5866defec1d52e2cd384bf014494da19657b0", + "src/main/java/ru/mtusi/messenger/service/MessageService.java": "b118cd2d46d26b05ce5c8f388d9e9fdd952ffa300a64f3a5882253b35a950e4a", + "src/main/java/ru/mtusi/messenger/service/SessionCacheService.java": "bb15211bd76353ee5782f5c7bc2afcdc8a68bf4f07d3ec6914d10218c318e150", + "src/main/java/ru/mtusi/messenger/service/SessionService.java": "75177e71b443be546cc5222549e0b0eb0f66d92b06453310d90c63b305c25ca6", + "src/main/java/ru/mtusi/messenger/service/UserService.java": "bb0dd55d35637bf0c62c9c5a568eb4280bfe6d4da40d303855035ded714bc9e2", + "src/main/java/ru/mtusi/messenger/util/CursorCodec.java": "3875011a04eb47fe28d709c4ccf5ade53ffa9cbe813a68539d7161cc2bb90947", + "src/main/java/ru/mtusi/messenger/util/TokenGenerator.java": "08297b5805b2d71c5af62d93ac3c805c1096ec025ae182485e406bdd5c04e037", + "src/main/java/ru/mtusi/messenger/util/TokenHasher.java": "564ae39c89ebf48478460fa9cc326930f4ba6a8f976d856dd75a44c3f886eacc", + "src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java": "6f706047c050f5cbfdf61082a1ce6c74595c0e5416b2c5b32ef588c92173aef6", + "src/main/java/ru/mtusi/messenger/validation/AttachmentValidator.java": "bc0a335f7d32b6b659c42cdd24858b8817e1558b338f5f8c075f8375c4ee6b15", + "src/main/java/ru/mtusi/messenger/validation/ChatValidator.java": "e2379205ab9e96db74187d3353d4192c05bead99c7fbf509ff6fe5d033109f18", + "src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java": "1cd9c1af4d2ba0f56eedccfb5ddc4d27928da57b0cf2918b16099df26bfe7cb4", + "src/test/java/ru/mtusi/messenger/AttachmentIntegrationTest.java": "71c9d0e6e34e16b45d0add29a3b2aabaec88980c9723ae5cfdb671327789e9ef", + "src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java": "e949d72c057d7457b3747dd962df7732eb092074c014008ee69bdc8e36123ca2", + "src/main/resources/application.yaml": "ef414162f182cd68410acb1f07f39d8200c3a489ae1daa6b307c3768be26e6bf", + "src/main/resources/db/migration/V1__init.sql": "9f15aaf1bc1949bc19dec830314c976477d9af4d55b8554f1913f84ccb4dae58", + "src/main/resources/db/migration/V2__attachment_integrity.sql": "232232d2845c5aca2977dc504e682bb90c2ab112f264de2f2a54ad337ea8c982", + "scripts/bootstrap.ps1": "219760fe8b02c0cbdcb740da306cf1c47247b5b0455fd6912dd335f3ef65426c", + "scripts/check_contract.py": "61e300fe5c1074360418e24b4653b12f96808247a2beaf2a64859aa360f81493", + "scripts/restart.cmd": "a8b170bd67efd9fd2cbd0db837984f826cf0f09c9b73754798b79ff481b1d589", + "scripts/restart.example.sh": "7cbfc7f518b975ee3ca37a645359ff734ab0686789b795a9ac845789eb46fbd9", + "scripts/restart.ps1": "72eb5e70fd4cf2e1891dddffd85ca560ae82f066f77d953f532d145be1800f8a", + "scripts/restart.sh": "d17a08a9d4cc7af1c594757f3f2bfbec7c15bf11d36393070fc915af30fa8dcc", + "scripts/stop-one.cmd": "b636287c36f4c8f52e7840513506565bab0a1d480bb9187fdb40d1c0101616fa", + "scripts/stop-one.example.sh": "6467c6e1515dee72982f85bced3f3862601ae0dbfafd4fd4818ef420f1dea040", + "scripts/stop-one.ps1": "c60f70430dbea3916c68011ad5ccbaf329a44a43f1e2d55f33597e4a495cc0b6", + "scripts/stop-one.sh": "fec1a774f4387676b8b6adf2398a41e7b0108a0bc745103a3079b23acfe6f668", + "scripts/validate_openapi.py": "cd7a33221b1860c5d2330e52afa6cb222d375db671ae9ab379ba51a0d3a77946", + "tests/aborted.py": "ef6ce22c66ccefc80d3c09322f4041624653194a2a119b7a21e6826899d8a196", + "tests/client.py": "b318084e2a4c380db91a55d082190bf33979fa556a4c4ca87e01f46ae275775c", + "tests/extended.py": "c816ba34a8421c70f5aa7e80d40bf229704481d9d548f540882c897d59d5fcd1", + "tests/faults.py": "0732d7a87c208351f49b887e4ef92a304c344da9252c11bef15db6994e82a259", + "tests/image_probe.py": "ef48d8882ab138b9699a173e7419e5814c22a10b01b6b0ddbb50ea49481a5baa", + "tests/load.py": "9a9aff05e109630e243c3b092d7bd564344e4872b29e38b6618647a08460a72e", + "tests/locking.py": "cf607f8bb078e1b8ca0fac81844ff7eb0a170a409d110ebf020355966c6892f4", + "tests/resilience.py": "4ba30b9c81a0664127ddab2b0bea5e76aa2087be8bb25aa13cd5a8e69be23fdd", + "tests/smoke.py": "354e168e1e644145c3ff50bbbe189fd217cce5659aa125f588098025ffab0fdf", + "tests/track2.py": "03c3eec04d71f6a8ebc4a9bd665f0d3c972955fe78c27b58ce4419c101544473", + "Dockerfile": "f460b0ff20112ea354aa406514a883dccd19f811503ae2e31695490bdf08345f", + "docker-compose.yml": "030357a3883f2c2fba3fc131c15d085a2fa2f62da16a3d8b4c63fe6a75ae043a", + "nginx.conf": "5d7753018d2e6a3c141963d932571382abdffe45869c1e98bc58dda015e6fd0f", + "build.gradle": "ac066d5f1d3b537db1eb401e88a97cfd9e2d9b86ed9e612cc44f7a74ccd5079c", + "settings.gradle": "eb9d73971105b2fae07689265bee6764673d5cfe1bf6d24a2561120fef94ad00", + "policy.json": "df8ef175cfca7a4d20d835fd605db8c7de1e96eea2a1b1fa4b8eb8b091ef2f66" +} \ No newline at end of file diff --git a/evidence/stop-one-after.txt b/evidence/stop-one-after.txt new file mode 100644 index 00000000..f76da003 --- /dev/null +++ b/evidence/stop-one-after.txt @@ -0,0 +1 @@ +/mtusi2026lab4-api-2 3217054c4e74 exited diff --git a/evidence/stop-one-before.txt b/evidence/stop-one-before.txt new file mode 100644 index 00000000..8fd6c1d7 --- /dev/null +++ b/evidence/stop-one-before.txt @@ -0,0 +1 @@ +/mtusi2026lab4-api-2 3217054c4e74 running diff --git a/evidence/track2.txt b/evidence/track2.txt new file mode 100644 index 00000000..8711c141 --- /dev/null +++ b/evidence/track2.txt @@ -0,0 +1,3 @@ +PASS dry-run: old orphan and missing metadata detected; no mutations +PASS apply: orphan removed, missing marked BROKEN, fresh object retained +PASS repeat is idempotent; referenced attachment and bytes retained diff --git a/evidence/unit-summary.json b/evidence/unit-summary.json new file mode 100644 index 00000000..7f1be693 --- /dev/null +++ b/evidence/unit-summary.json @@ -0,0 +1,18 @@ +[ + { + "name": "ru.mtusi.messenger.AttachmentIntegrationTest", + "tests": "3", + "failures": "0", + "errors": "0", + "skipped": "0", + "time": "5.344" + }, + { + "name": "ru.mtusi.messenger.MessengerLab1ApplicationTests", + "tests": "1", + "failures": "0", + "errors": "0", + "skipped": "0", + "time": "0.179" + } +] \ No newline at end of file diff --git a/evidence/unit.txt b/evidence/unit.txt new file mode 100644 index 00000000..c16a3f66 --- /dev/null +++ b/evidence/unit.txt @@ -0,0 +1,13 @@ +To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/9.3.0/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation. +Daemon will be stopped at the end of the build +> Task :compileJava +> Task :processResources UP-TO-DATE +> Task :classes +> Task :compileTestJava UP-TO-DATE +> Task :processTestResources NO-SOURCE +> Task :testClasses UP-TO-DATE +> Task :test + +BUILD SUCCESSFUL in 34s +4 actionable tasks: 2 executed, 2 up-to-date +Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.3.0/userguide/configuration_cache_enabling.html diff --git a/evidence/upload-before-tuning.json b/evidence/upload-before-tuning.json new file mode 100644 index 00000000..5b4ec4c0 --- /dev/null +++ b/evidence/upload-before-tuning.json @@ -0,0 +1,11 @@ +{ + "uploads": 20, + "concurrency": 10, + "image_bytes": 8674413, + "sampled_peak_MiB": { + "mtusi2026lab4-api-1": 502.3, + "mtusi2026lab4-api-2": 491.4 + }, + "elapsed_seconds": 10.5, + "limitation": "discrete docker stats samples; true peak may be higher" +} \ No newline at end of file diff --git a/evidence/upload-before-tuning.txt b/evidence/upload-before-tuning.txt new file mode 100644 index 00000000..6b9c21e1 --- /dev/null +++ b/evidence/upload-before-tuning.txt @@ -0,0 +1,12 @@ +PASS negative: MIME, corrupt, oversized, filename, duplicate/unknown/cross-chat attachments +PASS 24 simultaneous idempotent requests across 2 replicas; one message +image_bytes= 8674413 memory_samples= ['mtusi2026lab4-api-1 485.9MiB / 512MiB\nmtusi2026lab4-api-2 453.3MiB / 512MiB\nmtusi2026lab4-lb-1 38.87MiB / 7.649GiB\nmtusi2026lab4-minio-1 124.2MiB / 7.649GiB\nmtusi2026lab4-db-1 55.26MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n', 'mtusi2026lab4-api-1 496MiB / 512MiB\nmtusi2026lab4-api-2 491.4MiB / 512MiB\nmtusi2026lab4-lb-1 35.27MiB / 7.649GiB\nmtusi2026lab4-minio-1 125.5MiB / 7.649GiB\nmtusi2026lab4-db-1 56.24MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n', 'mtusi2026lab4-api-1 502.3MiB / 512MiB\nmtusi2026lab4-api-2 489.2MiB / 512MiB\nmtusi2026lab4-lb-1 24.9MiB / 7.649GiB\nmtusi2026lab4-minio-1 127MiB / 7.649GiB\nmtusi2026lab4-db-1 56.78MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n', 'mtusi2026lab4-api-1 494.9MiB / 512MiB\nmtusi2026lab4-api-2 484.5MiB / 512MiB\nmtusi2026lab4-lb-1 9.027MiB / 7.649GiB\nmtusi2026lab4-minio-1 128.7MiB / 7.649GiB\nmtusi2026lab4-db-1 56.84MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n', 'mtusi2026lab4-api-1 492.6MiB / 512MiB\nmtusi2026lab4-api-2 485.2MiB / 512MiB\nmtusi2026lab4-lb-1 8.957MiB / 7.649GiB\nmtusi2026lab4-minio-1 128.8MiB / 7.649GiB\nmtusi2026lab4-db-1 57.18MiB / 1GiB\nmtusi2026lab4-redis-1 5.652MiB / 7.649GiB\n'] +PASS 20 uploads concurrency=10 elapsed_seconds= 10.5 +mtusi2026lab4-api-1 492.6MiB / 512MiB +mtusi2026lab4-api-2 484.8MiB / 512MiB +mtusi2026lab4-lb-1 8.957MiB / 7.649GiB +mtusi2026lab4-minio-1 128.8MiB / 7.649GiB +mtusi2026lab4-db-1 57.17MiB / 1GiB +mtusi2026lab4-redis-1 5.902MiB / 7.649GiB + +PASS logout across replicas diff --git a/evidence/upload-summary.json b/evidence/upload-summary.json new file mode 100644 index 00000000..37518194 --- /dev/null +++ b/evidence/upload-summary.json @@ -0,0 +1,12 @@ +{ + "uploads": 20, + "concurrency": 10, + "image_bytes": 8674413, + "heap_MiB": 320, + "sampled_peak_MiB": { + "mtusi2026lab4-api-2": 454.1, + "mtusi2026lab4-api-1": 454.8 + }, + "elapsed_seconds": 12.547, + "limitation": "discrete docker stats; true peak may be higher" +} \ 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..61285a65 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..19a6bdeb --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..adff685a --- /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 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# 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..c4bdd3ab --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@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 Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +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 + +goto fail + +: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 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 00000000..a290974b --- /dev/null +++ b/nginx.conf @@ -0,0 +1,47 @@ +worker_processes auto; + +events { + worker_connections 1024; +} + +http { + access_log /tmp/access.log; + error_log /tmp/error.log warn; + + resolver 127.0.0.11 valid=10s ipv6=off; + resolver_timeout 5s; + + upstream api_backend { + zone api_backend 64k; + server api:8080 resolve max_fails=1 fail_timeout=5s; + keepalive 32; + } + + server { + listen 80; + server_name _; + + client_max_body_size 0; + client_body_timeout 15s; + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_request_buffering off; + proxy_set_header Connection ""; + proxy_set_header Host $http_host; + proxy_set_header X-Forwarded-Host $http_host; + proxy_set_header X-Forwarded-Port $server_port; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_next_upstream error timeout http_502 http_504; + proxy_next_upstream_tries 3; + + proxy_connect_timeout 1s; + proxy_send_timeout 10s; + proxy_read_timeout 10s; + } + } +} \ No newline at end of file diff --git a/policy.json b/policy.json new file mode 100644 index 00000000..e95a0bdb --- /dev/null +++ b/policy.json @@ -0,0 +1,21 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:AbortMultipartUpload", + "s3:ListMultipartUploadParts" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments", + "arn:aws:s3:::messenger-attachments/*" + ] + } + ] +} \ No newline at end of file diff --git a/scripts/bootstrap.ps1 b/scripts/bootstrap.ps1 new file mode 100644 index 00000000..f6b62586 --- /dev/null +++ b/scripts/bootstrap.ps1 @@ -0,0 +1,12 @@ +$ErrorActionPreference = 'Stop' +New-Item -ItemType Directory -Force secrets | Out-Null +$values = @{postgres_db='messenger'; postgres_user='messenger'; postgres_password=''; minio_root_user='labadmin'; minio_root_password=''; s3_access_key_id='labapi'; s3_secret_access_key=''} +foreach ($name in $values.Keys) { + $path = Join-Path secrets ($name + '.txt') + if (!(Test-Path -LiteralPath $path)) { + $value = $values[$name] + if (!$value) { $value = [Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) } + [System.IO.File]::WriteAllText((Join-Path (Get-Location) $path), $value) + } +} +if (!(Test-Path .env)) { Copy-Item .env.example .env } diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..e71fe90c --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1 @@ +@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1" diff --git a/scripts/restart.ps1 b/scripts/restart.ps1 new file mode 100644 index 00000000..369254a6 --- /dev/null +++ b/scripts/restart.ps1 @@ -0,0 +1,9 @@ +$ErrorActionPreference = 'Stop' +$ids = docker compose ps -q +$before = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids +$before | Set-Content evidence/restart-before.txt +docker compose restart db redis minio api lb +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +$ids = docker compose ps -q +$after = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids +$after | Set-Content evidence/restart-after.txt diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..cbc094cc --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +docker compose restart db redis minio api lb diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..dcdcb845 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1 @@ +@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1" diff --git a/scripts/stop-one.ps1 b/scripts/stop-one.ps1 new file mode 100644 index 00000000..27ce5105 --- /dev/null +++ b/scripts/stop-one.ps1 @@ -0,0 +1,13 @@ +$ErrorActionPreference = 'Stop' +$replicas = docker compose ps -q api +foreach ($replica in $replicas) { + $alias = docker inspect --format '{{.Config.Hostname}}' $replica + if ($alias -eq $env:TARGET_INSTANCE_ID) { + docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-before.txt + docker stop --time 2 $replica + $result = $LASTEXITCODE + docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-after.txt + exit $result + } +} +exit 1 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..60c335f4 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +for id in $(docker compose ps -q api); do + if [ "$(docker inspect --format '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + docker stop -t 2 "$id" + exit 0 + fi +done +exit 1 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..22321674 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java @@ -0,0 +1,18 @@ +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; +import org.springframework.scheduling.annotation.EnableScheduling; + +@ConfigurationPropertiesScan +@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class) +@EnableScheduling +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/JacksonConfig.java b/src/main/java/ru/mtusi/messenger/config/JacksonConfig.java new file mode 100644 index 00000000..197c4958 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/JacksonConfig.java @@ -0,0 +1,27 @@ +package ru.mtusi.messenger.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.cfg.CoercionAction; +import tools.jackson.databind.cfg.CoercionInputShape; + + +@Configuration +@Slf4j +public class JacksonConfig { + + @Bean + public JsonMapperBuilderCustomizer strictJacksonCustomizer() { + log.warn(">>> Strict JsonMapper customizer applied"); + return builder -> builder + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .withCoercionConfigDefaults(config -> { + config.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail); + config.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail); + config.setCoercion(CoercionInputShape.Float, CoercionAction.Fail); + }); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/MinioConfig.java b/src/main/java/ru/mtusi/messenger/config/MinioConfig.java new file mode 100644 index 00000000..2efe971f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/MinioConfig.java @@ -0,0 +1,27 @@ +package ru.mtusi.messenger.config; + +import io.minio.MinioClient; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.mtusi.messenger.config.properties.S3Properties; + +@Configuration +@RequiredArgsConstructor +public class MinioConfig { + private final S3Properties props; + + @Bean + public MinioClient minioClient() { + return MinioClient.builder() + .endpoint(props.endpoint()) + .httpClient(new okhttp3.OkHttpClient.Builder() + .connectTimeout(java.time.Duration.ofSeconds(2)) + .readTimeout(java.time.Duration.ofSeconds(10)) + .writeTimeout(java.time.Duration.ofSeconds(10)) + .callTimeout(java.time.Duration.ofSeconds(20)).build()) + .region(props.region()) + .credentials(props.resolvedAccessKey(), props.resolvedSecretKey()) + .build(); + } +} \ 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/ShedLockConfig.java b/src/main/java/ru/mtusi/messenger/config/ShedLockConfig.java new file mode 100644 index 00000000..47ccd931 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/ShedLockConfig.java @@ -0,0 +1,26 @@ +package ru.mtusi.messenger.config; + +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import javax.sql.DataSource; + +@Configuration +@EnableSchedulerLock(defaultLockAtMostFor = "30m") +public class ShedLockConfig { + + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider( + JdbcTemplateLockProvider.Configuration.builder() + .withJdbcTemplate(new JdbcTemplate(dataSource)) + .withTableName("shedlock") + .usingDbTime() + .build() + ); + } +} 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/IdempotencyProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java new file mode 100644 index 00000000..1d1efe46 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java @@ -0,0 +1,10 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.idempotency") +public record IdempotencyProperties( + int keyMaxLength, + String keyPattern, + int retentionHours +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java new file mode 100644 index 00000000..e5f51dd5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.instance") +public record InstanceProperties(String id) { +} \ 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/ReconcilerProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/ReconcilerProperties.java new file mode 100644 index 00000000..b247344b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/ReconcilerProperties.java @@ -0,0 +1,27 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +/** + * Конфигурация фонового Reconciler'а для согласованности S3 ↔ БД. + */ +@ConfigurationProperties(prefix = "reconciler") +public record ReconcilerProperties( + + @DefaultValue("true") boolean enabled, + + @DefaultValue("3600000") long intervalMs, + + @DefaultValue("15") int gracePeriodMinutes, + + @DefaultValue("false") boolean dryRun, + + @DefaultValue("100") int batchSize, + + @DefaultValue("3") int maxS3Retries, + + @DefaultValue("30m") String lockAtMostFor, + + @DefaultValue("1m") String lockAtLeastFor +) {} 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/S3Properties.java b/src/main/java/ru/mtusi/messenger/config/properties/S3Properties.java new file mode 100644 index 00000000..a474334d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/S3Properties.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +@ConfigurationProperties(prefix = "s3") +public record S3Properties( + String endpoint, + String bucket, + @DefaultValue("us-east-1") String region, + @DefaultValue("") String accessKey, + @DefaultValue("") String secretKey, + @DefaultValue("true") boolean pathStyleAccess, + @DefaultValue("300") int presignExpirySeconds +) { + public String resolvedAccessKey() { + var file = System.getenv("S3_ACCESS_KEY_ID_FILE"); + if (file != null && !file.isBlank()) { + try { + return new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(file))).strip(); + } catch (Exception e) { + throw new RuntimeException("Failed to read S3_ACCESS_KEY_ID_FILE: " + file, e); + } + } + return accessKey; + } + + public String resolvedSecretKey() { + var file = System.getenv("S3_SECRET_ACCESS_KEY_FILE"); + if (file != null && !file.isBlank()) { + try { + return new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(file))).strip(); + } catch (Exception e) { + throw new RuntimeException("Failed to read S3_SECRET_ACCESS_KEY_FILE: " + file, e); + } + } + return secretKey; + } +} \ 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/config/properties/UploadProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/UploadProperties.java new file mode 100644 index 00000000..8c7ec04b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/UploadProperties.java @@ -0,0 +1,13 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +import java.util.List; + +@ConfigurationProperties(prefix = "upload") +public record UploadProperties( + @DefaultValue("10485760") long maxBytes, + @DefaultValue("40000000") long maxPixels, + @DefaultValue({"image/png", "image/jpeg"}) List allowedContentTypes +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/AttachmentController.java b/src/main/java/ru/mtusi/messenger/controller/AttachmentController.java new file mode 100644 index 00000000..df9ed7a5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AttachmentController.java @@ -0,0 +1,36 @@ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; +import ru.mtusi.messenger.dto.AttachmentDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.AttachmentService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class AttachmentController implements AttachmentsApi { + private final AttachmentService service; + + @Override + public ResponseEntity uploadAttachment(UUID chatId, String filename, HttpServletRequest body, String contentType, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(201).body(service.upload(chatId, principal.userId(), filename, body, contentType)); + } + + @Override + public ResponseEntity getAttachment(UUID attachmentId, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(service.getMetadata(attachmentId, principal.userId())); + } + + @Override + public ResponseEntity downloadAttachment(UUID attachmentId, String variant, SessionPrincipal principal) { + return service.downloadResponse(attachmentId, principal.userId(), variant); + } +} diff --git a/src/main/java/ru/mtusi/messenger/controller/AttachmentsApi.java b/src/main/java/ru/mtusi/messenger/controller/AttachmentsApi.java new file mode 100644 index 00000000..fd8981ea --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AttachmentsApi.java @@ -0,0 +1,168 @@ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +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 jakarta.validation.constraints.Size; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import ru.mtusi.messenger.dto.AttachmentDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.security.SessionPrincipal; + +import java.util.UUID; + +@Validated +@Tag(name = "Attachments", description = "Загрузка и скачивание вложений (PNG/JPEG) в чатах.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface AttachmentsApi { + + @Operation( + operationId = "uploadAttachment", + summary = "Принять один PNG/JPEG, до 10 MiB", + tags = { "Attachments" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = AttachmentDTO.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 = "413", description = "Превышен лимит", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "415", 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}/attachments", + consumes = { MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE }, + produces = { MediaType.APPLICATION_JSON_VALUE } + ) + ResponseEntity uploadAttachment( + @Parameter(name = "chat_id", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Parameter(name = "filename", required = true, in = ParameterIn.QUERY) + @Size(min = 1, max = 255) @RequestParam("filename") String filename, + HttpServletRequest body, + @RequestHeader("Content-Type") String contentType, + @AuthenticationPrincipal SessionPrincipal principal + ); + + @Operation( + operationId = "getAttachment", + summary = "Метаданные вложения, доступ участникам чата", + tags = { "Attachments" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = AttachmentDTO.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/attachments/{attachment_id}", + produces = { MediaType.APPLICATION_JSON_VALUE } + ) + ResponseEntity getAttachment( + @Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH) + @PathVariable("attachment_id") UUID attachmentId, + @AuthenticationPrincipal SessionPrincipal principal + ); + + @Operation( + operationId = "downloadAttachment", + summary = "Скачать байты через авторизованный API", + tags = { "Attachments" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "image/png", schema = @Schema(type = "string", format = "binary")), + @Content(mediaType = "image/jpeg", schema = @Schema(type = "string", format = "binary")), + @Content(mediaType = "image/webp", schema = @Schema(type = "string", format = "binary")) + }), + @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/attachments/{attachment_id}/content" + ) + ResponseEntity downloadAttachment( + @Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH) + @PathVariable("attachment_id") UUID attachmentId, + @Parameter(name = "variant", in = ParameterIn.QUERY) + @RequestParam(value = "variant", required = false, defaultValue = "original") String variant, + @AuthenticationPrincipal SessionPrincipal principal + ); +} \ 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..f7600f1c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java @@ -0,0 +1,119 @@ +/** + * 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 jakarta.servlet.http.HttpServletRequest; +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( + HttpServletRequest request + ); + + + /** + * 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..7c83d00c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthController.java @@ -0,0 +1,27 @@ +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; + + @Override + public ResponseEntity createSession(HttpServletRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION), request.getContentLengthLong())); + } + + @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..0bee9775 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatController.java @@ -0,0 +1,36 @@ +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.dto.CreateChatDTO; +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(CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(chatService.createChat(principal.userId(), createChatDTO)); + } + + @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..8a04bfe7 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java @@ -0,0 +1,216 @@ +/** + * 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.CreateChatDTO; +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 createChatDTO (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 CreateChatDTO createChatDTO, @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..765d8b1d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthController.java @@ -0,0 +1,23 @@ +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..02f462c2 --- /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, String idempotencyKey, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO, idempotencyKey)); + } + + @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..a8ebb18f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java @@ -0,0 +1,138 @@ +/** + * 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 = "Idempotency-Key", required = true, in = ParameterIn.HEADER) + @RequestHeader(value = "Idempotency-Key", required = true) String idempotencyKey, + @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..da1bbad2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UserController.java @@ -0,0 +1,27 @@ +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.CreateUserDTO; +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(CreateUserDTO createUserDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(createUserDTO)); + } +} 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..87ea33ae --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java @@ -0,0 +1,137 @@ +/** + * 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.CreateUserDTO; +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 createUserDTO (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 = "CreateUserDTO", description = "", required = true) @Valid @RequestBody CreateUserDTO createUserDTO + ); + +} \ 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..ccad7a8f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java @@ -0,0 +1,170 @@ +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.MissingRequestHeaderException; +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 static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class); + 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) { + boolean isLogin = "/api/v1/auth/sessions".equals(req.getRequestURI()); + String challenge = isLogin + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .header("WWW-Authenticate", challenge) + .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) { + log.error("Unexpected API failure type={}", e.getClass().getName()); + 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); + } + + @ExceptionHandler(MissingRequestHeaderException.class) + public ResponseEntity missingHeader(MissingRequestHeaderException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Missing header: " + e.getHeaderName(), req); + } + + @ExceptionHandler(UnsupportedMediaTypeException.class) + public ResponseEntity unsupportedMedia(UnsupportedMediaTypeException e, HttpServletRequest req) { + return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, + ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, e.getMessage(), req); + } + + @ExceptionHandler(StorageUnavailableException.class) + public ResponseEntity storageUnavailable(StorageUnavailableException e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, e.getMessage(), 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/AttachmentDTO.java b/src/main/java/ru/mtusi/messenger/dto/AttachmentDTO.java new file mode 100644 index 00000000..f0e959fc --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/AttachmentDTO.java @@ -0,0 +1,393 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import java.time.Instant; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +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; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class AttachmentDTO { + + private UUID id; + + private UUID chatId; + + private UUID ownerId; + + private String filename; + + /** + * Gets or Sets contentType + */ + public enum ContentTypeEnum { + IMAGE_PNG("image/png"), + IMAGE_JPEG("image/jpeg"); + + private final String value; + + ContentTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ContentTypeEnum fromValue(String value) { + for (ContentTypeEnum b : ContentTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private ContentTypeEnum contentType; + + private Long sizeBytes; + + private String sha256; + + /** + * Gets or Sets status + */ + public enum StatusEnum { + READY("ready"); + + private final 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; + + @Valid + private List<@Valid VariantDTO> variants = new ArrayList<>(); + + private String errorCode; + + private Instant createdAt; + + private Instant updatedAt; + + public AttachmentDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public AttachmentDTO(UUID id, UUID chatId, UUID ownerId, String filename, + ContentTypeEnum contentType, Long sizeBytes, String sha256, + StatusEnum status, List<@Valid VariantDTO> variants, + String errorCode, Instant createdAt, Instant updatedAt) { + this.id = id; + this.chatId = chatId; + this.ownerId = ownerId; + this.filename = filename; + this.contentType = contentType; + this.sizeBytes = sizeBytes; + this.sha256 = sha256; + this.status = status; + this.variants = variants; + this.errorCode = errorCode; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + + public AttachmentDTO 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 AttachmentDTO chatId(UUID chatId) { + this.chatId = chatId; + return this; + } + + @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 AttachmentDTO ownerId(UUID ownerId) { + this.ownerId = ownerId; + return this; + } + + @Valid + @Schema(name = "owner_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("owner_id") + public UUID getOwnerId() { + return ownerId; + } + + public void setOwnerId(UUID ownerId) { + this.ownerId = ownerId; + } + + public AttachmentDTO filename(String filename) { + this.filename = filename; + return this; + } + + @NotNull + @Size(min = 1, max = 255) + @Schema(name = "filename", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("filename") + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public AttachmentDTO contentType(ContentTypeEnum contentType) { + this.contentType = contentType; + return this; + } + + @NotNull + @Schema(name = "content_type", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("content_type") + public ContentTypeEnum getContentType() { + return contentType; + } + + public void setContentType(ContentTypeEnum contentType) { + this.contentType = contentType; + } + + public AttachmentDTO sizeBytes(Long sizeBytes) { + this.sizeBytes = sizeBytes; + return this; + } + + @NotNull + @Min(1L) @Max(10485760L) + @Schema(name = "size_bytes", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("size_bytes") + public Long getSizeBytes() { + return sizeBytes; + } + + public void setSizeBytes(Long sizeBytes) { + this.sizeBytes = sizeBytes; + } + + public AttachmentDTO sha256(String sha256) { + this.sha256 = sha256; + return this; + } + + @NotNull + @Pattern(regexp = "^[a-f0-9]{64}$") + @Schema(name = "sha256", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("sha256") + public String getSha256() { + return sha256; + } + + public void setSha256(String sha256) { + this.sha256 = sha256; + } + + public AttachmentDTO status(StatusEnum status) { + this.status = status; + return this; + } + + @NotNull + @Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public AttachmentDTO variants(List<@Valid VariantDTO> variants) { + this.variants = variants; + return this; + } + + public AttachmentDTO addVariantsItem(VariantDTO variantsItem) { + if (this.variants == null) { + this.variants = new ArrayList<>(); + } + this.variants.add(variantsItem); + return this; + } + + @NotNull @Valid + @Schema(name = "variants", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("variants") + public List<@Valid VariantDTO> getVariants() { + return variants; + } + + public void setVariants(List<@Valid VariantDTO> variants) { + this.variants = variants; + } + + public AttachmentDTO errorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + @Schema(name = "error_code", requiredMode = Schema.RequiredMode.REQUIRED, nullable = true) + @JsonProperty("error_code") + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public AttachmentDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + @NotNull + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public AttachmentDTO updatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + @NotNull + @Schema(name = "updated_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("updated_at") + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AttachmentDTO attachment = (AttachmentDTO) o; + return Objects.equals(this.id, attachment.id) && + Objects.equals(this.chatId, attachment.chatId) && + Objects.equals(this.ownerId, attachment.ownerId) && + Objects.equals(this.filename, attachment.filename) && + Objects.equals(this.contentType, attachment.contentType) && + Objects.equals(this.sizeBytes, attachment.sizeBytes) && + Objects.equals(this.sha256, attachment.sha256) && + Objects.equals(this.status, attachment.status) && + Objects.equals(this.variants, attachment.variants) && + Objects.equals(this.errorCode, attachment.errorCode) && + Objects.equals(this.createdAt, attachment.createdAt) && + Objects.equals(this.updatedAt, attachment.updatedAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, chatId, ownerId, filename, contentType, sizeBytes, + sha256, status, variants, errorCode, createdAt, updatedAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AttachmentDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n"); + sb.append(" ownerId: ").append(toIndentedString(ownerId)).append("\n"); + sb.append(" filename: ").append(toIndentedString(filename)).append("\n"); + sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); + sb.append(" sizeBytes: ").append(toIndentedString(sizeBytes)).append("\n"); + sb.append(" sha256: ").append(toIndentedString(sha256)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" variants: ").append(toIndentedString(variants)).append("\n"); + sb.append(" errorCode: ").append(toIndentedString(errorCode)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).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/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java new file mode 100644 index 00000000..d62ca62e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -0,0 +1,150 @@ +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; + } + + @NotNull + @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/CreateChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java new file mode 100644 index 00000000..3b553716 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java @@ -0,0 +1,101 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +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 CreateChatDTO { + + private String title; + + @Valid + private List memberIds = new ArrayList<>(); + + public CreateChatDTO() { + super(); + } + + public CreateChatDTO(String title, List memberIds) { + this.title = title; + this.memberIds = memberIds; + } + + public CreateChatDTO 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 CreateChatDTO memberIds(List memberIds) { + this.memberIds = memberIds; + return this; + } + + public CreateChatDTO 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; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CreateChatDTO that = (CreateChatDTO) o; + return Objects.equals(title, that.title) && Objects.equals(memberIds, that.memberIds); + } + + @Override + public int hashCode() { + return Objects.hash(title, memberIds); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateChatDTO {\n"); + sb.append(" title: ").append(toIndentedString(title)).append("\n"); + sb.append(" memberIds: ").append(toIndentedString(memberIds)).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/CreateMessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java new file mode 100644 index 00000000..42238b61 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java @@ -0,0 +1,51 @@ +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.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +@Schema(name = "CreateMessage") +public class CreateMessageDTO { + + private String text; + + private List attachmentIds = new ArrayList<>(); + + public CreateMessageDTO() {} + + public CreateMessageDTO text(String text) { + this.text = text; + return this; + } + + @NotNull + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { return text; } + + public void setText(String text) { this.text = text; } + + @Schema(name = "attachment_ids", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("attachment_ids") + public List getAttachmentIds() { return attachmentIds; } + + public void setAttachmentIds(List attachmentIds) { this.attachmentIds = attachmentIds; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CreateMessageDTO d)) return false; + return Objects.equals(text, d.text) && + Objects.equals(attachmentIds, d.attachmentIds); + } + + @Override + public int hashCode() { return Objects.hash(text, attachmentIds); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java new file mode 100644 index 00000000..27876f58 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java @@ -0,0 +1,110 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +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 CreateUserDTO { + + private String username; + + private String displayName; + + private String password; + + public CreateUserDTO() { + super(); + } + + public CreateUserDTO(String username, String displayName, String password) { + this.username = username; + this.displayName = displayName; + this.password = password; + } + + public CreateUserDTO username(String username) { + this.username = username; + return this; + } + + @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 CreateUserDTO displayName(String displayName) { + this.displayName = displayName; + return this; + } + + @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 CreateUserDTO password(String password) { + this.password = password; + return this; + } + + @NotNull + @CodePointLength(min = 12, max = 128) + @Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED, accessMode = Schema.AccessMode.WRITE_ONLY) + @JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CreateUserDTO createUser = (CreateUserDTO) o; + return Objects.equals(this.username, createUser.username) && + Objects.equals(this.displayName, createUser.displayName) && + Objects.equals(this.password, createUser.password); + } + + @Override + public int hashCode() { + return Objects.hash(username, displayName, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateUserDTO {\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); + sb.append(" password: ").append(password != null ? "***" : "null").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/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..03d44d4c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java @@ -0,0 +1,215 @@ +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; +import java.util.ArrayList; +import java.util.List; + +/** + * MessageDTO + */ + +public class MessageDTO { + + private UUID id; + + private UUID chatId; + + private UUID senderId; + + private String text; + + private Instant createdAt; + + private List attachmentIds = new ArrayList<>(); + + 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(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt, List attachmentIds) { + this.id = id; + this.chatId = chatId; + this.senderId = senderId; + this.text = text; + this.createdAt = createdAt; + this.attachmentIds = attachmentIds != null ? attachmentIds : new ArrayList<>(); + } + + 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; + } + + @Valid + @Schema(name = "attachment_ids", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("attachment_ids") + public List getAttachmentIds() { + return attachmentIds; + } + + public void setAttachmentIds(List attachmentIds) { + this.attachmentIds = attachmentIds; + } + + @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) && + Objects.equals(this.attachmentIds, messageDTO.attachmentIds); + } + + @Override + public int hashCode() { + return Objects.hash(id, chatId, senderId, text, createdAt, attachmentIds); + } + + @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(" attachmentIds: ").append(toIndentedString(attachmentIds)).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..dd7fddd6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -0,0 +1,163 @@ +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 Instant createdAt; + + public UserDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public UserDTO(String username, String displayName) { + this.username = username; + this.displayName = displayName; + } + + 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; + } + + /** + * Get password + * @return password + */ + + public UserDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @NotNull + @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.createdAt, userDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, displayName, 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(" 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/VariantDTO.java b/src/main/java/ru/mtusi/messenger/dto/VariantDTO.java new file mode 100644 index 00000000..78437d0f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/VariantDTO.java @@ -0,0 +1,257 @@ +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.*; +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class VariantDTO { + + /** + * Gets or Sets name + */ + public enum NameEnum { + THUMBNAIL("thumbnail"), + CROP("crop"), + OPTIMIZED("optimized"); + + private final String value; + + NameEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static NameEnum fromValue(String value) { + for (NameEnum b : NameEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private NameEnum name; + + /** + * Gets or Sets contentType + */ + public enum ContentTypeEnum { + IMAGE_JPEG("image/jpeg"), + IMAGE_PNG("image/png"), + IMAGE_WEBP("image/webp"); + + private final String value; + + ContentTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ContentTypeEnum fromValue(String value) { + for (ContentTypeEnum b : ContentTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private ContentTypeEnum contentType; + + private Long sizeBytes; + + private Integer width; + + private Integer height; + + private String sha256; + + public VariantDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public VariantDTO(NameEnum name, ContentTypeEnum contentType, Long sizeBytes, + Integer width, Integer height, String sha256) { + this.name = name; + this.contentType = contentType; + this.sizeBytes = sizeBytes; + this.width = width; + this.height = height; + this.sha256 = sha256; + } + + public VariantDTO name(NameEnum name) { + this.name = name; + return this; + } + + @NotNull + @Schema(name = "name", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("name") + public NameEnum getName() { + return name; + } + + public void setName(NameEnum name) { + this.name = name; + } + + public VariantDTO contentType(ContentTypeEnum contentType) { + this.contentType = contentType; + return this; + } + + @NotNull + @Schema(name = "content_type", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("content_type") + public ContentTypeEnum getContentType() { + return contentType; + } + + public void setContentType(ContentTypeEnum contentType) { + this.contentType = contentType; + } + + public VariantDTO sizeBytes(Long sizeBytes) { + this.sizeBytes = sizeBytes; + return this; + } + + @NotNull + @Min(1L) + @Schema(name = "size_bytes", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("size_bytes") + public Long getSizeBytes() { + return sizeBytes; + } + + public void setSizeBytes(Long sizeBytes) { + this.sizeBytes = sizeBytes; + } + + public VariantDTO width(Integer width) { + this.width = width; + return this; + } + + @NotNull + @Min(1) + @Schema(name = "width", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("width") + public Integer getWidth() { + return width; + } + + public void setWidth(Integer width) { + this.width = width; + } + + public VariantDTO height(Integer height) { + this.height = height; + return this; + } + + @NotNull + @Min(1) + @Schema(name = "height", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("height") + public Integer getHeight() { + return height; + } + + public void setHeight(Integer height) { + this.height = height; + } + + public VariantDTO sha256(String sha256) { + this.sha256 = sha256; + return this; + } + + @NotNull + @Pattern(regexp = "^[a-f0-9]{64}$") + @Schema(name = "sha256", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("sha256") + public String getSha256() { + return sha256; + } + + public void setSha256(String sha256) { + this.sha256 = sha256; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VariantDTO variant = (VariantDTO) o; + return Objects.equals(this.name, variant.name) && + Objects.equals(this.contentType, variant.contentType) && + Objects.equals(this.sizeBytes, variant.sizeBytes) && + Objects.equals(this.width, variant.width) && + Objects.equals(this.height, variant.height) && + Objects.equals(this.sha256, variant.sha256); + } + + @Override + public int hashCode() { + return Objects.hash(name, contentType, sizeBytes, width, height, sha256); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VariantDTO {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); + sb.append(" sizeBytes: ").append(toIndentedString(sizeBytes)).append("\n"); + sb.append(" width: ").append(toIndentedString(width)).append("\n"); + sb.append(" height: ").append(toIndentedString(height)).append("\n"); + sb.append(" sha256: ").append(toIndentedString(sha256)).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/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/StaleAttachmentException.java b/src/main/java/ru/mtusi/messenger/exception/StaleAttachmentException.java new file mode 100644 index 00000000..e5a488db --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/StaleAttachmentException.java @@ -0,0 +1,11 @@ +package ru.mtusi.messenger.exception; + +public class StaleAttachmentException extends RuntimeException { + public StaleAttachmentException(String message) { + super(message); + } + + public StaleAttachmentException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/StorageUnavailableException.java b/src/main/java/ru/mtusi/messenger/exception/StorageUnavailableException.java new file mode 100644 index 00000000..fdbc3e74 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/StorageUnavailableException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class StorageUnavailableException extends RuntimeException { + public StorageUnavailableException(String message, Throwable cause) { super(message, cause); } +} \ 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/exception/UnsupportedMediaTypeException.java b/src/main/java/ru/mtusi/messenger/exception/UnsupportedMediaTypeException.java new file mode 100644 index 00000000..d9d82628 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/UnsupportedMediaTypeException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class UnsupportedMediaTypeException extends RuntimeException { + public UnsupportedMediaTypeException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java b/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java new file mode 100644 index 00000000..36721da6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java @@ -0,0 +1,30 @@ +package ru.mtusi.messenger.filter; + +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.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import ru.mtusi.messenger.config.properties.InstanceProperties; + +import java.io.IOException; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +@RequiredArgsConstructor +public class InstanceIdFilter extends OncePerRequestFilter { + + private final InstanceProperties props; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + response.setHeader("X-Instance-Id", props.id()); + chain.doFilter(request, response); + } +} \ No newline at end of file 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..b6ad09ce --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java @@ -0,0 +1,33 @@ +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.Ordered; +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(Ordered.HIGHEST_PRECEDENCE + 1) +public class RequestIdFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + String rid = UUID.randomUUID().toString(); + res.setHeader("X-Request-Id", rid); + 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/AttachmentMapper.java b/src/main/java/ru/mtusi/messenger/mapper/AttachmentMapper.java new file mode 100644 index 00000000..b5b63ccf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/AttachmentMapper.java @@ -0,0 +1,56 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import ru.mtusi.messenger.dto.AttachmentDTO; +import ru.mtusi.messenger.model.Attachment; +import ru.mtusi.messenger.model.AttachmentStatus; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; + +import java.util.Collections; + +@Mapper(componentModel = "spring") +public interface AttachmentMapper { + @Mapping(target = "chatId", source = "chat.id") + @Mapping(target = "ownerId", source = "owner.id") + @Mapping(target = "sha256", source = "checksum") + @Mapping(target = "status", source = "status", qualifiedByName = "mapStatus") + @Mapping(target = "contentType", source = "contentType", qualifiedByName = "mapContentType") + @Mapping(target = "variants", expression = "java(emptyVariants())") + @Mapping(target = "errorCode", expression = "java((String) null)") + AttachmentDTO toDto(Attachment entity); + + @Named("mapStatus") + default AttachmentDTO.StatusEnum mapStatus(AttachmentStatus status) { + if (status == AttachmentStatus.READY) { + return AttachmentDTO.StatusEnum.READY; + } + return AttachmentDTO.StatusEnum.READY; + } + + @Named("mapContentType") + default AttachmentDTO.ContentTypeEnum mapContentType(String contentType) { + if (contentType == null) { + return null; + } + return AttachmentDTO.ContentTypeEnum.fromValue(contentType); + } + + default java.util.List emptyVariants() { + return Collections.emptyList(); + } + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + @Mapping(target = "status", constant = "READY") + Attachment toEntity(String objectKey, + String filename, + String contentType, + Long sizeBytes, + String checksum, + Chat chat, + User owner); +} \ 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..b3f88594 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java @@ -0,0 +1,35 @@ +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.dto.CreateChatDTO; +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(CreateChatDTO 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..2eb5ddf5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java @@ -0,0 +1,30 @@ +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) + @Mapping(target = "attachmentIds", ignore = true) + Message toMessage(MessageDTO dto); + + @Mapping(target = "chatId", source = "chat.id") + @Mapping(target = "senderId", source = "sender.id") + @Mapping(target = "attachmentIds", source = "attachmentIds") + MessageDTO toMessageDTO(Message entity); + + @Mapping(target = "id", ignore = true) + @Mapping(target = "chat", ignore = true) + @Mapping(target = "sender", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "attachmentIds", source = "attachmentIds") + 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..0ee46d92 --- /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.CreateUserDTO; +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(CreateUserDTO dto); + + UserDTO toUserDto(User user); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Attachment.java b/src/main/java/ru/mtusi/messenger/model/Attachment.java new file mode 100644 index 00000000..faf11a42 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Attachment.java @@ -0,0 +1,63 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Entity +@Table(name = "attachments") +@Getter @Setter +public class Attachment { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "object_key", nullable = false, unique = true, length = 512) + private String objectKey; + + @Column(nullable = false, length = 255) + private String filename; + + @Column(name = "content_type", nullable = false, length = 100) + private String contentType; + + @Column(name = "size_bytes", nullable = false) + private Long sizeBytes; + + @Column(nullable = false, length = 64) + private String checksum; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private AttachmentStatus status; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "chat_id", nullable = false) + private Chat chat; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "owner_id", nullable = false) + private User owner; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + @PrePersist + private void onCreate() { + Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); + this.createdAt = now; + this.updatedAt = now; + } + + @PreUpdate + private void onUpdate() { + this.updatedAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/AttachmentStatus.java b/src/main/java/ru/mtusi/messenger/model/AttachmentStatus.java new file mode 100644 index 00000000..93b1f090 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/AttachmentStatus.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.model; + +public enum AttachmentStatus { + UPLOADING, + READY, + BROKEN +} \ 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/IdempotencyKey.java b/src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java new file mode 100644 index 00000000..95e494f0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java @@ -0,0 +1,47 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "idempotency_keys") +@Getter +@Setter +public class IdempotencyKey { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "user_id", nullable = false) + private UUID userId; + + @Column(nullable = false, length = 16) + private String method; + + @Column(name = "chat_id", nullable = false) + private UUID chatId; + + @Column(name = "idempotency_key", nullable = false, length = 128) + private String idempotencyKey; + + @Column(name = "request_hash", nullable = false, length = 64) + private String requestHash; + + @Column(name = "status_code") + private Short statusCode; + + @JdbcTypeCode(SqlTypes.JSON) + @Column(name = "response_body", columnDefinition = "jsonb") + private String responseBody; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; +} \ 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..c02c1751 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Message.java @@ -0,0 +1,48 @@ +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.List; +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; + + @ElementCollection + @CollectionTable(name = "message_attachments", joinColumns = @JoinColumn(name = "message_id")) + @Column(name = "attachment_id") + @OrderColumn(name = "attachment_order") + private List attachmentIds = 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/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/AttachmentRepository.java b/src/main/java/ru/mtusi/messenger/repository/AttachmentRepository.java new file mode 100644 index 00000000..eede7676 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/AttachmentRepository.java @@ -0,0 +1,59 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.QueryHints; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.Attachment; +import ru.mtusi.messenger.model.AttachmentStatus; + +import jakarta.persistence.LockModeType; +import jakarta.persistence.QueryHint; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface AttachmentRepository extends JpaRepository { + boolean existsByObjectKey(String objectKey); + + @Lock(LockModeType.PESSIMISTIC_WRITE) + @QueryHints({ + @QueryHint(name = "jakarta.persistence.lock.timeout", value = "-2") + }) + @Query(""" + SELECT a FROM Attachment a + WHERE a.status = :status + AND a.createdAt <= :before + ORDER BY a.createdAt ASC, a.id ASC + """) + List findStaleForUpdateSkipLocked(@Param("status") AttachmentStatus status, @Param("before") Instant before, org.springframework.data.domain.Pageable pageable); + + @Query(""" + SELECT a FROM Attachment a + WHERE a.status = :status + ORDER BY a.createdAt ASC, a.id ASC + """) + List findReadyForReconciliation( + @Param("status") AttachmentStatus status, + org.springframework.data.domain.Pageable pageable + ); + + /** + * Обновляет статус записи на BROKEN. + */ + @Modifying + @Query(""" + UPDATE Attachment a + SET a.status = :newStatus, a.updatedAt = CURRENT_TIMESTAMP + WHERE a.id = :id + AND a.status = :currentStatus + """) + int updateStatus( + @Param("id") UUID id, + @Param("currentStatus") AttachmentStatus currentStatus, + @Param("newStatus") AttachmentStatus newStatus + ); + +} 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..3a4d33c3 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java @@ -0,0 +1,41 @@ +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); + + boolean existsByIdAndMembersId(UUID chatId, UUID userId); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java b/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java new file mode 100644 index 00000000..9cb32e00 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; +import ru.mtusi.messenger.model.IdempotencyKey; + +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface IdempotencyRepository extends JpaRepository { + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = """ + INSERT INTO idempotency_keys + (user_id, method, chat_id, idempotency_key, request_hash, created_at) + VALUES (:userId, :method, :chatId, :key, :hash, NOW()) + ON CONFLICT (user_id, method, chat_id, idempotency_key) DO NOTHING + """, nativeQuery = true) + int tryClaim(UUID userId, String method, UUID chatId, String key, String hash); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = """ + UPDATE idempotency_keys + SET status_code = :statusCode, + response_body = CAST(:body AS jsonb) + WHERE user_id = :userId + AND method = :method + AND chat_id = :chatId + AND idempotency_key = :key + """, nativeQuery = true) + int commitResponse(UUID userId, String method, UUID chatId, String key, + int statusCode, String body); + + Optional findByUserIdAndMethodAndChatIdAndIdempotencyKey( + UUID userId, String method, UUID chatId, String idempotencyKey); +} \ 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..d0692180 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java @@ -0,0 +1,36 @@ +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 { + boolean isLogin = "/api/v1/auth/sessions".equals(request.getRequestURI()); + String challenge = isLogin + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + + errors.writeError( + response, + request, + HttpStatus.UNAUTHORIZED, + challenge, + 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/AttachmentReconciler.java b/src/main/java/ru/mtusi/messenger/service/AttachmentReconciler.java new file mode 100644 index 00000000..b789b7e0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AttachmentReconciler.java @@ -0,0 +1,85 @@ +package ru.mtusi.messenger.service; + +import io.minio.*; +import io.minio.errors.ErrorResponseException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.PageRequest; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.ReconcilerProperties; +import ru.mtusi.messenger.config.properties.S3Properties; +import ru.mtusi.messenger.model.Attachment; +import ru.mtusi.messenger.model.AttachmentStatus; +import ru.mtusi.messenger.repository.AttachmentRepository; +import java.time.Instant; + +@Component +@RequiredArgsConstructor +@Slf4j +public class AttachmentReconciler { + private final AttachmentRepository attachmentRepository; + private final MinioClient minio; + private final S3Properties s3Props; + private final ReconcilerProperties reconcilerProps; + private final org.springframework.jdbc.core.JdbcTemplate jdbc; + + @Scheduled(fixedDelayString = "${reconciler.interval-ms:3600000}") + @Transactional + public void reconcile() { + if (!reconcilerProps.enabled()) return; + Boolean acquired = jdbc.queryForObject("select pg_try_advisory_xact_lock(741204)", Boolean.class); + if (!Boolean.TRUE.equals(acquired)) return; + long started = System.nanoTime(); + scanObjects(); + scanMetadata(); + log.info("Reconcile complete dryRun={} elapsedMs={}", reconcilerProps.dryRun(), (System.nanoTime()-started)/1000000); + } + + private Instant cutoff() { + return Instant.now().minusSeconds(reconcilerProps.gracePeriodMinutes() * 60L); + } + + private void scanObjects() { + try { + for (var result : minio.listObjects(ListObjectsArgs.builder().bucket(s3Props.bucket()).recursive(true).build())) { + var item = result.get(); + if (item.lastModified().toInstant().isBefore(cutoff()) + && !attachmentRepository.existsByObjectKey(item.objectName())) { + log.info("Reconcile orphan dryRun={} key={}", reconcilerProps.dryRun(), item.objectName()); + if (!reconcilerProps.dryRun()) remove(item.objectName()); + } + } + } catch (Exception e) { + throw new ru.mtusi.messenger.exception.StorageUnavailableException("Reconcile storage unavailable", e); + } + } + + private void scanMetadata() { + int page = 0; + org.springframework.data.domain.Page batch; + do { + batch = attachmentRepository.findAll(PageRequest.of(page++, reconcilerProps.batchSize(), org.springframework.data.domain.Sort.by("id"))); + batch.forEach(this::verify); + } while (batch.hasNext()); + } + + private void verify(Attachment attachment) { + if (attachment.getStatus() == AttachmentStatus.BROKEN) return; + if (!attachment.getCreatedAt().isBefore(cutoff())) return; + try { + minio.statObject(StatObjectArgs.builder().bucket(s3Props.bucket()).object(attachment.getObjectKey()).build()); + } catch (ErrorResponseException e) { + if (!"NoSuchKey".equals(e.errorResponse().code())) throw new IllegalStateException("S3 verification failed", e); + log.info("Reconcile missing dryRun={} id={}", reconcilerProps.dryRun(), attachment.getId()); + if (!reconcilerProps.dryRun()) attachment.setStatus(AttachmentStatus.BROKEN); + } catch (Exception e) { + throw new IllegalStateException("S3 verification failed", e); + } + } + + private void remove(String key) throws Exception { + minio.removeObject(RemoveObjectArgs.builder().bucket(s3Props.bucket()).object(key).build()); + } +} diff --git a/src/main/java/ru/mtusi/messenger/service/AttachmentService.java b/src/main/java/ru/mtusi/messenger/service/AttachmentService.java new file mode 100644 index 00000000..5576739d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AttachmentService.java @@ -0,0 +1,219 @@ +package ru.mtusi.messenger.service; + +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.exception.ServiceUnavailableException; +import ru.mtusi.messenger.exception.UnsupportedMediaTypeException; +import ru.mtusi.messenger.exception.PayloadTooLargeException; +import ru.mtusi.messenger.exception.InvalidRequestException; +import java.io.InputStream; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Semaphore; +import java.nio.charset.StandardCharsets; +import org.springframework.http.ContentDisposition; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.jdbc.core.JdbcTemplate; +import io.minio.*; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataAccessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.S3Properties; +import ru.mtusi.messenger.dto.AttachmentDTO; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.StorageUnavailableException; +import ru.mtusi.messenger.mapper.AttachmentMapper; +import ru.mtusi.messenger.model.Attachment; +import ru.mtusi.messenger.model.AttachmentStatus; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.AttachmentRepository; +import ru.mtusi.messenger.validation.AttachmentValidator; + +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +@Slf4j +public class AttachmentService { + private final Semaphore uploads = new Semaphore(1, true); + private final JdbcTemplate jdbc; + private final UserService userService; + private final ChatService chatService; + private final MinioClient minio; + private final AttachmentRepository attachmentRepository; + private final S3Properties s3Props; + private final AttachmentValidator validator; + private final AttachmentMapper attachmentMapper; + + @Transactional + public AttachmentDTO upload(UUID chatId, UUID caller, String filename, HttpServletRequest request, String declaredType) { + acquireUploadSlot(); + try { + return performUpload(chatId, caller, filename, request, declaredType); + } finally { + uploads.release(); + } + } + + private void acquireUploadSlot() { + try { + if (!uploads.tryAcquire(30, TimeUnit.SECONDS)) + throw new ServiceUnavailableException("Upload capacity exhausted"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ServiceUnavailableException("Upload interrupted"); + } + } + + private AttachmentDTO performUpload(UUID chatId, UUID caller, String filename, + HttpServletRequest request, String declaredType) { + jdbc.execute("select pg_advisory_xact_lock_shared(741204)"); + Chat chat = chatService.getChat(caller, chatId); + String safeFilename = validator.sanitizeFilename(filename); + byte[] body = readBounded(request); + String contentType = validator.validate(body, safeFilename); + if (!contentType.equals(declaredType)) throw new UnsupportedMediaTypeException("MIME mismatch"); + String objectKey = UUID.randomUUID().toString(); + String checksum = uploadToS3(body, objectKey, contentType); + return saveAttachmentReady(objectKey, safeFilename, contentType, body, checksum, chat, caller); + } + + private byte[] readBounded(HttpServletRequest request) { + try { + byte[] bytes = request.getInputStream().readNBytes(10485761); + if (bytes.length > 10485760) throw new PayloadTooLargeException("File exceeds limit"); + return bytes; + } catch (IOException e) { + throw new InvalidRequestException("Incomplete upload"); + } + } + + AttachmentDTO saveAttachmentReady(String objectKey, String safeFilename, String contentType, byte[] body, String checksum, Chat chat, UUID caller) { + try { + Attachment attachment = buildAttachment(objectKey, safeFilename, contentType, body, checksum, chat, caller); + attachment.setStatus(AttachmentStatus.READY); + attachmentRepository.save(attachment); + return attachmentMapper.toDto(attachment); + } catch (DataAccessException e) { + compensateS3Upload(objectKey); + throw e; + } + } + + @Transactional(readOnly = true) + public AttachmentDTO getMetadata(UUID attachmentId, UUID userId) { + Attachment attachment = requireAttachmentForMember(attachmentId, userId); + if (attachment.getStatus() != AttachmentStatus.READY) throw new ConflictException("Attachment unavailable"); + return attachmentMapper.toDto(attachment); + } + + public DownloadedAttachment download(UUID attachmentId, UUID userId, String variant) { + Attachment attachment = requireAttachmentForMember(attachmentId, userId); + assertOriginalVariant(variant); + if (attachment.getStatus() != AttachmentStatus.READY) throw new ConflictException("Attachment not ready"); + return streamFromS3(attachment); + } + + void compensateS3Upload(String objectKey) { + try { + minio.removeObject( + RemoveObjectArgs.builder() + .bucket(s3Props.bucket()) + .object(objectKey) + .build() + ); + log.info("Compensated S3 upload: removed objectKey={}", objectKey); + } catch (Exception e) { + log.error("Failed to compensate S3 upload for objectKey={}: {}", objectKey, e.getMessage(), e); + } + } + + private String uploadToS3(byte[] body, String objectKey, String contentType) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (var digestIn = new java.security.DigestInputStream( + new java.io.ByteArrayInputStream(body), digest)) { + minio.putObject(PutObjectArgs.builder() + .bucket(s3Props.bucket()) + .object(objectKey) + .stream(digestIn, (long) body.length, -1L) + .contentType(contentType) + .build()); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (Exception e) { + log.error("S3 upload failed for objectKey: {}", objectKey, e); + throw new StorageUnavailableException("S3 upload failed", e); + } + } + + private Attachment buildAttachment(String objectKey, String filename, String contentType, byte[] body, String checksum, Chat chat, UUID caller) { + User owner = userService.getReferenceUserById(caller); + return attachmentMapper.toEntity(objectKey, filename, contentType, (long) body.length, checksum, chat, owner); + } + + private Attachment requireAttachmentForMember(UUID attachmentId, UUID userId) { + Attachment attachment = attachmentRepository.findById(attachmentId) + .orElseThrow(() -> new NotFoundException("Attachment not found")); + assertMember(attachment.getChat().getId(), userId); + return attachment; + } + + private void assertOriginalVariant(String variant) { + if (!"original".equals(variant)) { + throw new NotFoundException("Variant not found"); + } + } + + private DownloadedAttachment streamFromS3(Attachment attachment) { + try { + var stream = minio.getObject(GetObjectArgs.builder() + .bucket(s3Props.bucket()) + .object(attachment.getObjectKey()) + .build()); + return new DownloadedAttachment(stream, attachment.getContentType(), attachment.getFilename()); + } catch (Exception e) { + throw translateS3Exception(e, attachment.getId(), attachment.getObjectKey()); + } + } + + private RuntimeException translateS3Exception(Exception e, UUID attachmentId, String objectKey) { + if (e instanceof io.minio.errors.ErrorResponseException minioEx) { + if ("NoSuchKey".equals(minioEx.errorResponse().code())) { + log.warn("S3 object missing for attachment {}", attachmentId); + return new NotFoundException("Attachment content not found"); + } + } + log.error("S3 download failed for {}", objectKey, e); + return new StorageUnavailableException("S3 download failed", e); + } + + private void assertMember(UUID chatId, UUID userId) { + boolean isMember = chatService.existsByIdAndMembersId(chatId, userId); + if (!isMember) { + throw new NotFoundException("Attachment not found"); + } + } + + @Transactional(readOnly = true) + public ResponseEntity downloadResponse(UUID id, UUID user, String variant) { + var file = download(id, user, variant); + try (var in = file.stream()) { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(file.contentType())) + .header("Content-Disposition", ContentDisposition.attachment() + .filename(file.filename(), StandardCharsets.UTF_8).build().toString()) + .body(in.readNBytes(10485761)); + } catch (IOException e) { + throw new StorageUnavailableException("Download failed", e); + } + } + + public record DownloadedAttachment(InputStream stream, String contentType, String filename) {} +} \ 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..8401f579 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AuthService.java @@ -0,0 +1,36 @@ +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.InvalidRequestException; +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, long contentLength) { + if (contentLength > 0) { + throw new InvalidRequestException("Request body is not allowed"); + } + 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..f56fdbd6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -0,0 +1,135 @@ +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.dto.CreateChatDTO; +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, CreateChatDTO createChatDTO) { + Set members = chatValidator.validateCreate(caller, createChatDTO); + Chat chat = buildChat(createChatDTO, members); + chat = persistChat(chat); + return chatMapper.toChatDto(chat); + } + + private Chat buildChat(CreateChatDTO createChatDTO, Set members) { + Chat chat = chatMapper.toChat(createChatDTO); + 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) + return null; + if (cursor.isEmpty()) + throw new InvalidRequestException("Cursor must not be empty"); + 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()); + } + + @Transactional + public boolean existsByIdAndMembersId(UUID chatId, UUID userId){ + return chatRepository.existsByIdAndMembersId(chatId, userId); + } +} \ 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..8a43a79a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/HealthService.java @@ -0,0 +1,59 @@ +package ru.mtusi.messenger.service; + +import com.zaxxer.hikari.HikariDataSource; +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; + +import javax.sql.DataSource; + +@Service +@RequiredArgsConstructor +public class HealthService { + + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + private final io.minio.MinioClient minio; + private final ru.mtusi.messenger.config.properties.S3Properties s3; + + public HealthDTO readiness() { + requirePoolAvailable(); + requireDatabaseReachable(); + try { + if (!minio.bucketExists(io.minio.BucketExistsArgs.builder().bucket(s3.bucket()).build())) + throw new ServiceUnavailableException("Storage unavailable"); + } catch (Exception e) { + throw new ServiceUnavailableException("Storage unavailable"); + } + return ok(); + } + + public HealthDTO liveness() { + return ok(); + } + + private void requirePoolAvailable() { + if (dataSource instanceof HikariDataSource hikari) { + var pool = hikari.getHikariPoolMXBean(); + if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) { + throw new ServiceUnavailableException("Database connection pool exhausted"); + } + } + } + + private void requireDatabaseReachable() { + try { + jdbcTemplate.queryForObject("SELECT 1", Integer.class); + } catch (Exception e) { + throw new ServiceUnavailableException("Database unavailable"); + } + } + + private HealthDTO ok() { + 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/IdempotencyService.java b/src/main/java/ru/mtusi/messenger/service/IdempotencyService.java new file mode 100644 index 00000000..043ef688 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/IdempotencyService.java @@ -0,0 +1,63 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.model.IdempotencyKey; +import ru.mtusi.messenger.repository.IdempotencyRepository; +import ru.mtusi.messenger.util.converter.IdempotencyPayloadConverter; +import ru.mtusi.messenger.validation.IdempotencyValidator; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.UUID; +import java.util.function.Supplier; + +@Service +@RequiredArgsConstructor +public class IdempotencyService { + + private final IdempotencyRepository idempotencyRepository; + private final IdempotencyPayloadConverter converter; + private final IdempotencyValidator validator; + + @Transactional + public T execute(UUID userId, String method, UUID chatId, String key, + Object requestBody, Class responseType, Supplier action) { + validator.validateKey(key); + String hash = hashRequest(requestBody); + + int claimed = idempotencyRepository.tryClaim(userId, method, chatId, key, hash); + if (claimed == 0) { + return replay(userId, method, chatId, key, hash, responseType); + } + + T result = action.get(); + idempotencyRepository.commitResponse(userId, method, chatId, key, 201, converter.toJson(result)); + return result; + } + + private T replay(UUID userId, String method, UUID chatId, String key, + String hash, Class responseType) { + IdempotencyKey stored = idempotencyRepository + .findByUserIdAndMethodAndChatIdAndIdempotencyKey(userId, method, chatId, key) + .orElseThrow(() -> new IllegalStateException("Idempotency row not visible after conflict")); + if (!stored.getRequestHash().equals(hash)) + throw new ConflictException("Idempotency-Key reused with a different request body"); + if (stored.getStatusCode() == null || stored.getStatusCode() != 201) + throw new ConflictException("Idempotency-Key has unexpected status"); + return converter.fromJson(stored.getResponseBody(), responseType); + } + + private String hashRequest(Object body) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(converter.toJson(body).getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (Exception e) { + throw new IllegalStateException("Cannot hash request body", e); + } + } +} \ 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..01f90297 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/MessageService.java @@ -0,0 +1,132 @@ +package ru.mtusi.messenger.service; + +import ru.mtusi.messenger.model.AttachmentStatus; +import ru.mtusi.messenger.repository.AttachmentRepository; +import ru.mtusi.messenger.exception.ConflictException; +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.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 ru.mtusi.messenger.service.IdempotencyService; + +import java.util.List; +import java.util.UUID; + +@Service +@Slf4j +@RequiredArgsConstructor +public class MessageService { + private final AttachmentRepository attachments; + private final IdempotencyService idempotencyService; + 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 dto, String idempotencyKey) { + Chat chat = chatService.getChat(senderId, chatId); + + return idempotencyService.execute(senderId, "POST", chatId, idempotencyKey, dto, MessageDTO.class, + () -> doCreate(senderId, chatId, dto, chat)); + } + + private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) { + validateCreate(chatId, dto); + User sender = userService.getReferenceUserById(senderId); + Message message = buildMessage(dto, 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() && (dto.getAttachmentIds() == null || dto.getAttachmentIds().isEmpty()))) { + throw new InvalidRequestException("Empty text"); + } + var ids = dto.getAttachmentIds(); + if (ids == null || ids.size() > 10 || ids.contains(null) || new java.util.HashSet<>(ids).size() != ids.size() + || dto.getText().codePointCount(0, dto.getText().length()) > 4000) { + throw new InvalidRequestException("Invalid message"); + } + for (UUID id : ids) { + var attachment = attachments.findById(id).filter(a -> a.getChat().getId().equals(chatId)) + .orElseThrow(() -> new NotFoundException("Attachment not found")); + if (attachment.getStatus() != AttachmentStatus.READY) { + throw new ConflictException("Attachment not ready"); + } + } + 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) + return null; + if (cursor.isEmpty()) + throw new InvalidRequestException("Cursor must not be empty"); + 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..44992593 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java @@ -0,0 +1,64 @@ +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; + + @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..9f5e8aab --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/UserService.java @@ -0,0 +1,84 @@ +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.CreateUserDTO; +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(CreateUserDTO createUserDTO) { + User user = userMapper.toUser(createUserDTO); + user.setPasswordHash(passwordEncoder.encode(createUserDTO.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/util/converter/IdempotencyPayloadConverter.java b/src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java new file mode 100644 index 00000000..4d11cb14 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java @@ -0,0 +1,29 @@ +package ru.mtusi.messenger.util.converter; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +@Component +@RequiredArgsConstructor +public class IdempotencyPayloadConverter { + + private final JsonMapper jsonMapper; + + public String toJson(Object payload) { + try { + return jsonMapper.writeValueAsString(payload); + } catch (JacksonException e) { // Исключение теперь непроверяемое + throw new IllegalStateException("Cannot serialize idempotency payload", e); + } + } + + public T fromJson(String json, Class type) { + try { + return jsonMapper.readValue(json, type); + } catch (JacksonException e) { + throw new IllegalStateException("Corrupt idempotency payload", e); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/validation/AttachmentValidator.java b/src/main/java/ru/mtusi/messenger/validation/AttachmentValidator.java new file mode 100644 index 00000000..79f6cf94 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/AttachmentValidator.java @@ -0,0 +1,76 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.config.properties.UploadProperties; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.PayloadTooLargeException; +import ru.mtusi.messenger.exception.UnsupportedMediaTypeException; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.MemoryCacheImageInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Locale; + +@Component +@RequiredArgsConstructor +public class AttachmentValidator { + private final UploadProperties props; + + public String validate(byte[] bytes, String filename) { + if (bytes.length > props.maxBytes()) { + throw new PayloadTooLargeException("File exceeds max size"); + } + try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))) { + var readers = ImageIO.getImageReaders(input); + if (!readers.hasNext()) { + throw new UnsupportedMediaTypeException("Only PNG/JPEG allowed"); + } + ImageReader reader = readers.next(); + try { + reader.setInput(input, true, true); + return inspect(reader); + } finally { + reader.dispose(); + } + } catch (IOException e) { + throw new UnsupportedMediaTypeException("Corrupted or unsupported image"); + } + } + + private String inspect(ImageReader reader) throws IOException { + String mime = contentType(reader.getFormatName()); + validateDimensions(reader.getWidth(0), reader.getHeight(0)); + reader.read(0); + return mime; + } + + private String contentType(String format) { + return switch (format.toLowerCase(Locale.ROOT)) { + case "png" -> "image/png"; + case "jpeg", "jpg" -> "image/jpeg"; + default -> throw new UnsupportedMediaTypeException("Only PNG/JPEG allowed"); + }; + } + + private void validateDimensions(int width, int height) { + if (width <= 0 || height <= 0) { + throw new UnsupportedMediaTypeException("Invalid image dimensions"); + } + if ((long) width * height > props.maxPixels()) { + throw new PayloadTooLargeException("Image dimensions exceed limit"); + } + } + + public String sanitizeFilename(String filename) { + if (filename == null || filename.isBlank() + || filename.codePointCount(0, filename.length()) > 255 + || filename.contains("/") || filename.contains("\\") + || filename.codePoints().anyMatch(Character::isISOControl)) { + throw new InvalidRequestException("Invalid filename"); + } + return filename; + } +} 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..6dea47f2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java @@ -0,0 +1,67 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +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, CreateChatDTO createChatDTO) { + List memberIds = createChatDTO.getMemberIds(); + String title = createChatDTO.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/java/ru/mtusi/messenger/validation/IdempotencyValidator.java b/src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java new file mode 100644 index 00000000..e193bd93 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.config.properties.IdempotencyProperties; +import ru.mtusi.messenger.exception.InvalidRequestException; + +import java.util.regex.Pattern; + +@Component +@RequiredArgsConstructor +public class IdempotencyValidator { + + private final IdempotencyProperties properties; + + public void validateKey(String key) { + requireNotBlank(key); + requireMaxLength(key); + requirePattern(key); + } + + private void requireNotBlank(String key) { + if (key == null || key.isEmpty()) { + throw new InvalidRequestException("Idempotency-Key header is required"); + } + } + + private void requireMaxLength(String key) { + if (key.length() > properties.keyMaxLength()) { + throw new InvalidRequestException("Idempotency-Key is too long"); + } + } + + private void requirePattern(String key) { + if (!Pattern.matches(properties.keyPattern(), key)) { + throw new InvalidRequestException("Idempotency-Key contains invalid characters"); + } + } +} \ 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..d3618d19 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,123 @@ +spring: + application: + name: messenger-lab2 + config: + import: "optional:configtree:/run/secrets/" + lifecycle: + timeout-per-shutdown-phase: 30s + jackson: + default-property-inclusion: always + 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: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 2000 + validation-timeout: 1000 + 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 + + servlet: + multipart: + max-file-size: ${MAX_UPLOAD_BYTES:10485760} + max-request-size: ${MAX_UPLOAD_BYTES:10485760} + file-size-threshold: 0 + resolve-lazily: false + +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: + idempotency: + key-max-length: ${IDEMPOTENCY_KEY_MAX_LENGTH:128} + key-pattern: '${IDEMPOTENCY_KEY_PATTERN:^[A-Za-z0-9._:-]+$}' + retention-hours: ${IDEMPOTENCY_RETENTION_HOURS:24} + instance: + id: ${INSTANCE_ID:${HOSTNAME:${random.uuid}}} + 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} + +s3: + endpoint: ${S3_ENDPOINT:http://minio:9000} + bucket: ${S3_BUCKET:messenger-attachments} + region: ${S3_REGION:us-east-1} + access-key: ${S3_ACCESS_KEY_ID:} + secret-key: ${S3_SECRET_ACCESS_KEY:} + path-style-access: true + presign-expiry-seconds: ${S3_PRESIGN_EXPIRY_SECONDS:300} + +upload: + max-bytes: ${MAX_UPLOAD_BYTES:10485760} + max-pixels: ${MAX_IMAGE_PIXELS:40000000} + allowed-content-types: + - image/png + - image/jpeg + +reconciler: + enabled: ${RECONCILER_ENABLED:true} + interval-ms: ${RECONCILER_INTERVAL_MS:3600000} + grace-period-minutes: ${RECONCILER_GRACE_PERIOD_MINUTES:15} + dry-run: ${RECONCILER_DRY_RUN:false} + batch-size: ${RECONCILER_BATCH_SIZE:100} + max-s3-retries: ${RECONCILER_MAX_S3_RETRIES:3} + lock-at-most-for: ${RECONCILER_LOCK_AT_MOST_FOR:30m} + lock-at-least-for: ${RECONCILER_LOCK_AT_LEAST_FOR:1m} + +logging: + pattern: + console: "%d{ISO8601} %-5level [%X{requestId}] %logger{20} - %msg%n" + level: + org.springframework.cache: TRACE + org.springframework.cache.interceptor: TRACE + software.amazon.awssdk: DEBUG 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..2bd17a7c --- /dev/null +++ b/src/main/resources/db/migration/V1__init.sql @@ -0,0 +1,121 @@ +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +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) +); + +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) +); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE messages ( + id uuid PRIMARY KEY 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) +); + +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) +); + +CREATE TABLE idempotency_keys ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method VARCHAR(16) NOT NULL, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + idempotency_key VARCHAR(128) NOT NULL, + request_hash VARCHAR(64) NOT NULL, + status_code SMALLINT, + response_body JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT uq_idempotency_scope UNIQUE (user_id, method, chat_id, idempotency_key), + CONSTRAINT ck_idem_key_format CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT ck_idem_status_body_paired CHECK ((status_code IS NULL) = (response_body IS NULL)) +); + +CREATE TABLE attachments ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + object_key VARCHAR(512) NOT NULL, + filename VARCHAR(255) NOT NULL, + content_type VARCHAR(100) NOT NULL, + size_bytes BIGINT NOT NULL, + checksum VARCHAR(64) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'READY' + CHECK (status IN ('UPLOADING', 'READY', 'BROKEN')), + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT uq_attachments_object_key UNIQUE (object_key) +); + +CREATE TABLE shedlock ( + name VARCHAR(64) NOT NULL PRIMARY KEY, + lock_until TIMESTAMP NOT NULL, + locked_at TIMESTAMP NOT NULL, + locked_by VARCHAR(255) NOT NULL +); + +CREATE INDEX idx_messages_chat_created_asc_id + ON messages (chat_id, created_at ASC, id ASC); + +CREATE INDEX idx_chat_members_user + ON chat_members (user_id); + +CREATE INDEX idx_chats_created_asc_id + ON chats (created_at ASC, id ASC); + +CREATE INDEX idx_sessions_user_active + ON sessions (user_id) + WHERE revoked_at IS NULL; + +CREATE INDEX idx_sessions_expires_active + ON sessions (expires_at) + WHERE revoked_at IS NULL; + +CREATE INDEX idx_idempotency_created + ON idempotency_keys (created_at); + +CREATE INDEX idx_attachments_object_key ON attachments(object_key); +CREATE INDEX idx_attachments_chat_id ON attachments(chat_id); +CREATE INDEX idx_attachments_owner_id ON attachments(owner_id); +CREATE INDEX idx_attachments_status ON attachments(status); +CREATE INDEX idx_attachments_created_at ON attachments(created_at); + +CREATE TABLE message_attachments ( + message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + attachment_id UUID NOT NULL, + attachment_order INTEGER NOT NULL, + PRIMARY KEY (message_id, attachment_order) +); + +CREATE INDEX idx_message_attachments_attachment_id ON message_attachments(attachment_id); \ No newline at end of file diff --git a/src/main/resources/db/migration/V2__attachment_integrity.sql b/src/main/resources/db/migration/V2__attachment_integrity.sql new file mode 100644 index 00000000..4bb8e4bf --- /dev/null +++ b/src/main/resources/db/migration/V2__attachment_integrity.sql @@ -0,0 +1,2 @@ +ALTER TABLE messages DROP CONSTRAINT IF EXISTS ck_messages_text_not_blank; +ALTER TABLE message_attachments ADD CONSTRAINT fk_message_attachment FOREIGN KEY (attachment_id) REFERENCES attachments(id); diff --git a/src/test/java/ru/mtusi/messenger/AttachmentIntegrationTest.java b/src/test/java/ru/mtusi/messenger/AttachmentIntegrationTest.java new file mode 100644 index 00000000..9b34b868 --- /dev/null +++ b/src/test/java/ru/mtusi/messenger/AttachmentIntegrationTest.java @@ -0,0 +1,38 @@ +package ru.mtusi.messenger; + +import org.junit.jupiter.api.Test; +import ru.mtusi.messenger.config.properties.UploadProperties; +import ru.mtusi.messenger.validation.AttachmentValidator; +import ru.mtusi.messenger.exception.*; +import java.util.List; +import java.nio.file.Files; +import java.nio.file.Path; +import static org.assertj.core.api.Assertions.*; + +class AttachmentIntegrationTest { + private final AttachmentValidator validator = new AttachmentValidator( + new UploadProperties(10485760, 40000000, List.of("image/png", "image/jpeg"))); + + @Test + void acceptsRealFixture() throws Exception { + assertThat(validator.validate(Files.readAllBytes(Path.of("tests/fixtures/sample.png")), "sample.png")) + .isEqualTo("image/png"); + } + + @Test + void rejectsControlCharactersWithoutSilentlyRenaming() { + for (String name : List.of("a/b.png", "a\\b.png", "a\n.png", "a\u007f.png")) { + assertThatThrownBy(() -> validator.sanitizeFilename(name)).isInstanceOf(InvalidRequestException.class); + } + assertThat(validator.sanitizeFilename("photo..png")).isEqualTo("photo..png"); + } + + @Test + void rejectsTruncatedImageAndOversizedBody() throws Exception { + byte[] png = Files.readAllBytes(Path.of("tests/fixtures/sample.png")); + assertThatThrownBy(() -> validator.validate(java.util.Arrays.copyOf(png, 40), "x.png")) + .isInstanceOf(UnsupportedMediaTypeException.class); + assertThatThrownBy(() -> validator.validate(new byte[10485761], "x.png")) + .isInstanceOf(PayloadTooLargeException.class); + } +} 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..33eda5d4 --- /dev/null +++ b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java @@ -0,0 +1,18 @@ +package ru.mtusi.messenger; + +import org.junit.jupiter.api.Test; +import ru.mtusi.messenger.util.CursorCodec; +import java.time.Instant; +import java.util.UUID; +import static org.assertj.core.api.Assertions.*; + +class MessengerLab1ApplicationTests { + @Test + void cursorPreservesScopeAndBoundary() { + UUID scope = UUID.randomUUID(); + var boundary = new CursorCodec.PageBoundary(Instant.parse("2026-01-01T00:00:00Z"), UUID.randomUUID()); + var decoded = CursorCodec.decode(CursorCodec.encode(scope, boundary)); + assertThat(decoded.scopeId()).isEqualTo(scope); + assertThat(decoded.boundary()).isEqualTo(boundary); + } +} diff --git a/tests/README.md b/tests/README.md index 0dfa3f89..4128c895 100644 --- a/tests/README.md +++ b/tests/README.md @@ -55,3 +55,20 @@ make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca. ## Что ещё остаётся доказать Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. + +## Дополнительные проверки реализации lab4 + +Windows: используйте `py` вместо `python3`. Все команды выполняются из корня. + +- `py tests/extended.py`: MIME, corrupt/oversize, filename, принадлежность вложений, 24 конкурентных повтора сообщения через две реплики, 20 PNG по ~8.3 MiB при concurrency=10, RSS samples и logout. +- `py tests/resilience.py --mode persistence --action-script scripts/restart.cmd`: перезапуск PostgreSQL, Redis, MinIO, обеих API и LB; прежняя сессия и checksum. На Linux используйте `scripts/restart.sh`. +- `py tests/resilience.py --mode failover --action-script scripts/stop-one.cmd`: остановка конкретной реплики; после проверки `docker compose up -d api`. На Linux используйте `.sh`. +- `py tests/track2.py`: только изолированный стенд. Перед запуском задайте `RECONCILER_INTERVAL_MS=3000`, `RECONCILER_GRACE_PERIOD_MINUTES=1`, `RECONCILER_DRY_RUN=true` и пересоздайте API (`docker compose up -d --no-deps api`). Скрипт создаёт orphan и missing, выдерживает grace, проверяет dry-run, пересоздаёт API с apply и проверяет повтор и сохранность свежего объекта. Вывод не содержит токенов. Тест требует Docker CLI и права оператора. После проверки верните переменные к defaults и пересоздайте API. + +Модульные проверки: JDK 21, `./gradlew test` (`gradlew.bat test` в Windows). Они не требуют работающих хранилищ. Black-box проверки работают с реальным PostgreSQL/S3, не с моками. `BASE_URL=http://127.0.0.1:8080` исключает задержки разрешения localhost на Windows. + +`py tests/faults.py`: private bucket, остановка/возврат S3, отказ INSERT метаданных через временный DB trigger; trigger удаляется в finally. Требует изолированного стенда и прав оператора. + +`py tests/locking.py`: задержка INSERT на 6s через временный DB trigger, проверка невидимости метаданных и запрета exclusive advisory lock в реальном окне PUT/COMMIT. Затем сверка bytes. `py tests/aborted.py`: частичное тело HTTP и разрыв соединения, сверка отсутствия изменений БД/S3. Запускать последовательно без других инъекций/нагрузки. Оба сценария предназначены для изолированного стенда. + +Пять замечаний review (06.11.2026): `py tests/review_regressions.py`, требуется Pillow. Синтетические PNG/JPEG, точные 33 bytes PNG, filename traversal, Message/ACL и PNG ровно 1770843 bytes; сравнение БД/S3 при отказе. BASE_URL задаётся окружением. При резервировании Windows порта 8080 используйте `docker compose -f docker-compose.yml -f compose.review.yaml up -d` и `$env:BASE_URL='http://127.0.0.1:18080'`. diff --git a/tests/aborted.py b/tests/aborted.py new file mode 100644 index 00000000..f6a1dfb4 --- /dev/null +++ b/tests/aborted.py @@ -0,0 +1,18 @@ +"""Interrupted client body must not produce metadata or S3 writes.""" +from client import Client, check, run +from track2 import sql, mc +import socket,time + +def main(): + c=Client(); a,b,e,chat=c.bootstrap() + before=sql('select count(*) from attachments;') + objects=mc('mc ls proof/messenger-attachments/') + with socket.create_connection(('127.0.0.1',8080),timeout=5) as connection: + headers=('POST /api/v1/chats/'+chat['id']+'/attachments?filename=partial.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer '+a['token']+'\r\nContent-Type: image/png\r\nContent-Length: 1048576\r\n\r\n') + connection.sendall(headers.encode()+b'partial') + time.sleep(2) + check(sql('select count(*) from attachments;')==before,'partial metadata committed') + check(mc('mc ls proof/messenger-attachments/')==objects,'partial object stored') + print('PASS interrupted upload: connection closed before full body; metadata and S3 object listing unchanged') + +if __name__ == '__main__': run(main) diff --git a/tests/extended.py b/tests/extended.py new file mode 100644 index 00000000..10cf4122 --- /dev/null +++ b/tests/extended.py @@ -0,0 +1,59 @@ +"""Additional contract and cross-replica concurrency tests. No secrets in output.""" +from client import Client, check, run +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import uuid, json, time, subprocess, threading, zlib, struct, os + +def main(): + c=Client(timeout=30) + a,b,e,chat=c.bootstrap() + c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,body={'text':True},headers={'Idempotency-Key':uuid.uuid4().hex}) + data=Path('tests/fixtures/sample.png').read_bytes() + path='/api/v1/chats/'+chat['id']+'/attachments?filename=test.png' + def upload(raw=data, mime='image/png', expected=201, target=path): + return c.call('POST',target,expected,actor=a,raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None) + upload(data,'image/jpeg',415) + upload(data[:40],expected=415) + ihdr=struct.pack('>IIBBBBB',7000,7000,8,2,0,0,0) + bomb=b'\x89PNG\r\n\x1a\n'+struct.pack('>I',13)+b'IHDR'+ihdr+struct.pack('>I',zlib.crc32(b'IHDR'+ihdr)&0xffffffff) + upload(bomb,expected=413) + upload(b'x'*10485761,expected=413) + upload(target=path.replace('test.png','bad%7F.png'),expected=400) + att=upload()['json'] + other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json'] + c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'x','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) + for ids in ([att['id']]*2,[str(uuid.uuid4())]): + c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400 if len(ids)==2 else 404,actor=a,body={'text':'x','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex}) + print('PASS negative: MIME, corrupt, oversized, filename, duplicate/unknown/cross-chat attachments') + key=uuid.uuid4().hex + def message(_): + return c.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=a,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':key},schema='Message') + with ThreadPoolExecutor(max_workers=12) as pool: + replies=list(pool.map(message,range(24))) + check(len({r['json']['id'] for r in replies})==1,'duplicate message') + instances={r['headers']['X-Instance-Id'] for r in replies} + check(len(instances)>=2,'need two replicas') + print('PASS 24 simultaneous idempotent requests across',len(instances),'replicas; one message') + def chunk(kind, body): + return struct.pack('>I',len(body))+kind+body+struct.pack('>I',zlib.crc32(kind+body)&0xffffffff) + width=1700 + large=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+os.urandom(width*3) for _ in range(width))))+chunk(b'IEND',b'') + samples=[]; done=threading.Event() + def sample(): + while not done.is_set(): + samples.append(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True)) + sampler=threading.Thread(target=sample); sampler.start() + with ThreadPoolExecutor(max_workers=10) as pool: + started=time.monotonic(); results=list(pool.map(lambda _:upload(large),range(20))) + check(len({r['json']['id'] for r in results})==20,'uploads collided') + done.set(); sampler.join() + print('image_bytes=',len(large),'memory_samples=',samples) + print('PASS 20 uploads concurrency=10 elapsed_seconds=',round(time.monotonic()-started,3)) + print(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True)) + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a) + for _ in range(10): c.call('GET','/api/v1/users/me',401,actor=a) + print('PASS logout across replicas') + +if __name__ == '__main__': + run(main) + diff --git a/tests/faults.py b/tests/faults.py new file mode 100644 index 00000000..432ca9e0 --- /dev/null +++ b/tests/faults.py @@ -0,0 +1,33 @@ +"""Dependency and commit failure checks on a local isolated stand.""" +from client import Client, check, run +from track2 import sql, mc, command +import time, uuid + +def main(): + c=Client(timeout=30); a,b,e,chat=c.bootstrap() + att,data=c.attachment(a,chat) + key=sql("select object_key from attachments where id='"+att['id']+"';") + code=command(['docker','compose','exec','-T','minio','sh','-c','curl -s -o /dev/null -w "%{http_code}" http://localhost:9000/messenger-attachments/'+key]) + check(code=='403','bucket public') + print('PASS direct anonymous GET existing object returns 403',flush=True) + command(['docker','compose','stop','minio']) + try: + c.call('GET','/health/ready',503) + c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=x.png',503,actor=a,raw=data,headers={'Content-Type':'image/png'}) + print('PASS S3 outage: readiness and upload return 503',flush=True) + finally: command(['docker','compose','start','minio']) + time.sleep(3) + # DB trigger rejects metadata after successful PUT. Transaction rolls back; S3 compensation is tested. + before=sql('select count(*) from attachments;') + objects=mc('mc ls proof/messenger-attachments/') + sql("create function proof_reject() returns trigger language plpgsql as $$ begin raise exception 'injected'; end; $$; create trigger proof_reject before insert on attachments for each row execute function proof_reject();") + try: + c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=x.png',500,actor=a,raw=data,headers={'Content-Type':'image/png'}) + finally: + sql('drop trigger proof_reject on attachments; drop function proof_reject();') + check(sql('select count(*) from attachments;')==before,'metadata committed') + # saveAndFlush makes rejection observable before compensation, otherwise reconciler cleans after grace. + print('PASS DB failure: no success response, no committed metadata; orphan cleanup covered by track2',flush=True) + +if __name__ == '__main__': + run(main) diff --git a/tests/locking.py b/tests/locking.py new file mode 100644 index 00000000..a3b37dd0 --- /dev/null +++ b/tests/locking.py @@ -0,0 +1,27 @@ +"""Barrier experiment: probe DB fencing during PUT -> metadata commit window.""" +from client import Client, check, run +from track2 import sql +from concurrent.futures import ThreadPoolExecutor +import time + +def main(): + c=Client(timeout=30); a,b,e,chat=c.bootstrap() + before=sql('select count(*) from attachments;') + sql("create function proof_delay() returns trigger language plpgsql as $$ begin perform pg_sleep(6); return NEW; end; $$; create trigger proof_delay before insert on attachments for each row execute function proof_delay();") + try: + with ThreadPoolExecutor(max_workers=1) as pool: + task=pool.submit(c.attachment,a,chat) + for _ in range(30): + if sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")!='0': break + time.sleep(.2) + check(sql('select count(*) from attachments;')==before,'metadata visible before commit') + check(sql('select pg_try_advisory_xact_lock(741204);')=='f','reconciler could enter active upload') + att,data=task.result() + check(sql('select pg_try_advisory_xact_lock(741204);')=='t','lock leaked after commit') + received=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes'] + check(received==data,'bytes lost in commit window') + print('PASS PUT/COMMIT barrier: uncommitted metadata invisible; exclusive reconcile lock denied during upload; released after commit; other member downloads identical bytes') + finally: + sql('drop trigger proof_delay on attachments; drop function proof_delay();') + +if __name__ == '__main__': run(main) diff --git a/tests/review_regressions.py b/tests/review_regressions.py new file mode 100644 index 00000000..3fdf64b6 --- /dev/null +++ b/tests/review_regressions.py @@ -0,0 +1,64 @@ +"""Five review regressions, real Compose stack. JPEG fixture generation needs Pillow.""" +from client import Client, check, run +from track2 import sql, mc +from pathlib import Path +from PIL import Image +import io, os, struct, zlib, uuid, hashlib, time, urllib.request + + +def png_large(): + def chunk(kind, data): + return struct.pack('>I', len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff) + width=700 + data=b''.join(b'\0'+os.urandom(width*3) for _ in range(width)) + base=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(data)) + extra=1770843-len(base)-12-12 + return base+chunk(b'tEXt',b'proof\0'+b'x'*(extra-6))+chunk(b'IEND',b'') + + +def main(): + print('2026-11-06 Europe/Moscow; current working tree; synthetic data only',flush=True) + c=Client(base_url=os.environ.get('BASE_URL','http://127.0.0.1:8080'),timeout=30) + for _ in range(90): + try: + c.call('GET','/health/ready',schema='Health');break + except Exception: time.sleep(1) + else: raise AssertionError('API not ready') + a,b,e,chat=c.bootstrap() + png=Path('tests/fixtures/sample.png').read_bytes() + out=io.BytesIO(); Image.new('RGB',(32,24),(12,50,100)).save(out,format='JPEG'); jpeg=out.getvalue() + path='/api/v1/chats/'+chat['id']+'/attachments?filename=' + def upload(data,mime='image/png',filename='proof.png',expected=201): + return c.call('POST',path+filename,expected,actor=a,raw=data,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None) + def count(): return sql("select count(*) from attachments where chat_id='"+chat['id']+"';") + before=int(count()); attachments=[]; instances=set() + for data,mime,name in [(png,'image/png','proof.png'),(jpeg,'image/jpeg','proof.jpg')]*5: + response=upload(data,mime,name); att=response['json']; attachments.append(att) + instances.add(response['headers']['X-Instance-Id']) + got=c.call('GET','/api/v1/attachments/'+att['id'],actor=b,schema='Attachment')['json'] + check(got['content_type']==mime and got['status']=='ready','bad MIME/status') + check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==data,'bytes differ') + check(int(count())-before==10,'unexpected metadata count') + print('PASS PNG/JPEG: 10 uploads -> 201; 10 metadata GET -> 200; 10 downloads identical; DB +10; instances='+str(len(instances)),flush=True) + plain=c.message(a,chat,'plain')['json'];check(plain['attachment_ids']==[],'missing empty attachment_ids') + attached=c.message(a,chat,'',attachments=[attachments[0]['id']])['json'];check(attached['attachment_ids']==[attachments[0]['id']],'attachment lost') + other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json'] + for actor,target,ids in [(a,other,[attachments[0]['id']]),(a,chat,[str(uuid.uuid4())]),(e,chat,[attachments[0]['id']])]: + c.call('POST','/api/v1/chats/'+target['id']+'/messages',404,actor=actor,body={'text':'x','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex}) + print('PASS messages: plain attachment_ids=[]; file-only POST -> 201; cross-chat/unknown/outsider -> 404',flush=True) + before=count(); objects=mc('mc ls proof/messenger-attachments/') + for _ in range(10): upload(png[:33],expected=415) + upload(png,filename='..%2Fx.png',expected=400) + check(count()==before,'rejected upload persisted metadata') + check(mc('mc ls proof/messenger-attachments/')==objects,'rejected upload changed objects') + print('PASS sample.png[:33]: 10 x 415; ../x.png: 400; DB and S3 unchanged',flush=True) + large=png_large();check(len(large)==1770843,'fixture size mismatch') + with Image.open(io.BytesIO(large)) as image: image.load() + att=upload(large)['json'] + result=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b) + check(result['bytes']==large,'large PNG differs') + print('PASS valid PNG exactly 1770843 bytes: POST -> 201 through LB; download checksum matches',flush=True) + print('PASS all five review regressions',flush=True) + + +if __name__=='__main__': run(main) diff --git a/tests/track2.py b/tests/track2.py new file mode 100644 index 00000000..0e4f8ea4 --- /dev/null +++ b/tests/track2.py @@ -0,0 +1,61 @@ +"""Controlled DB/S3 fault injection; use an isolated local Compose stack.""" +from client import Client, check, run +from pathlib import Path +import subprocess, time, uuid, os, json + +def command(args, data=None): + r=subprocess.run(args,input=data,text=True,capture_output=True) + check(r.returncode==0,'operator command failed: '+args[0]) + return r.stdout.strip() + +def sql(query): + return command(['docker','compose','exec','-T','db','sh','-c','psql -U "$(cat /run/secrets/postgres_user)" -d "$(cat /run/secrets/postgres_db)" -At'],query) + +def mc(action): + return command(['docker','compose','exec','-T','minio','sh','-c', + 'mc alias set proof http://localhost:9000 "$(cat /run/secrets/minio_root_user)" "$(cat /run/secrets/minio_root_password)" >/dev/null && '+action]) + +def main(): + c=Client(timeout=30); a,b,e,chat=c.bootstrap() + protected,protected_data=c.attachment(a,chat) + c.message(a,chat,'protected',attachments=[protected['id']]) + protected_key=sql("select object_key from attachments where id='"+protected['id']+"';") + att,data=c.attachment(a,chat) + key=sql("select object_key from attachments where id='"+att['id']+"';") + orphan='proof-'+uuid.uuid4().hex + mc('mc cp /etc/hostname proof/messenger-attachments/'+orphan) + sql("update attachments set created_at=now()-interval '20 minutes' where id='"+att['id']+"';") + mc('mc rm proof/messenger-attachments/'+key) + fresh='fresh-'+uuid.uuid4().hex + # Objects must age past the configured one-minute test grace before scanning. + time.sleep(62) + mc('mc cp /etc/hostname proof/messenger-attachments/'+fresh) + # API replicas run scheduled reconciliation with dry-run=true, interval=3s, grace=1min. + time.sleep(6) + check(sql("select status from attachments where id='"+att['id']+"';")=='READY','dry-run mutated DB') + mc('mc stat proof/messenger-attachments/'+orphan) + logs=command(['docker','compose','logs','--no-log-prefix','api']) + proof='\n'.join(line for line in logs.splitlines() if 'Reconcile' in line) + Path('evidence/reconciler-dry-run-log.txt').write_text(proof) + check('orphan dryRun=true' in proof and 'missing dryRun=true' in proof,'dry-run did not report findings') + print('PASS dry-run: old orphan and missing metadata detected; no mutations',flush=True) + env=dict(os.environ,RECONCILER_INTERVAL_MS='3000',RECONCILER_GRACE_PERIOD_MINUTES='1',RECONCILER_DRY_RUN='false') + r=subprocess.run(['docker','compose','up','-d','--no-deps','api'],env=env,capture_output=True) + check(r.returncode==0,'recreate failed') + for _ in range(90): + if sql("select status from attachments where id='"+att['id']+"';")=='BROKEN': break + time.sleep(1) + check(sql("select status from attachments where id='"+att['id']+"';")=='BROKEN','missing not repaired') + check(orphan not in mc('mc ls proof/messenger-attachments/'),'orphan retained') + mc('mc stat proof/messenger-attachments/'+fresh) + print('PASS apply: orphan removed, missing marked BROKEN, fresh object retained',flush=True) + time.sleep(5) + check(sql("select status from attachments where id='"+att['id']+"';")=='BROKEN','repeat changed result') + mc('mc stat proof/messenger-attachments/'+protected_key) + check(sql("select status from attachments where id='"+protected['id']+"';")=='READY','used attachment damaged') + logs=command(['docker','compose','logs','--no-log-prefix','api']) + Path('evidence/reconciler-apply-log.txt').write_text('\n'.join(line for line in logs.splitlines() if 'Reconcile' in line)) + print('PASS repeat is idempotent; referenced attachment and bytes retained',flush=True) + +if __name__ == '__main__': + run(main)