Ivanov Danil BVT2301 5, Track 2 #34
@@ -18,3 +18,4 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
!gradle-9.7.1-bin.zip
|
||||
@@ -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 → <redacted-local-secret>
|
||||
./secrets/minio_root_password.txt → <redacted-local-secret>
|
||||
./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 (все точечные, без переписывания архитектуры)
|
||||
**Оценка рисков:** Низкая — исправления касаются только конфигурационных файлов.
|
||||
@@ -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 при аудите, исправлениях и проверках.
|
||||
|
||||
+104
-27
@@ -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
|
||||
+25
@@ -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"]
|
||||
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
services:
|
||||
lb:
|
||||
ports: !override
|
||||
- "127.0.0.1:18080:80"
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
PASS interrupted upload: connection closed before full body; metadata and S3 object listing unchanged
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -0,0 +1 @@
|
||||
PASS PUT/COMMIT barrier: uncommitted metadata invisible; exclusive reconcile lock denied during upload; released after commit; other member downloads identical bytes
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
403
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/mtusi2026lab4-api-2 3217054c4e74 exited
|
||||
@@ -0,0 +1 @@
|
||||
/mtusi2026lab4-api-2 3217054c4e74 running
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
+7
@@ -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
|
||||
@@ -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" "$@"
|
||||
Vendored
+93
@@ -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
|
||||
+47
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -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/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -0,0 +1 @@
|
||||
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.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
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
docker compose restart db redis minio api lb
|
||||
@@ -0,0 +1 @@
|
||||
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-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
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'messenger-lab1'
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -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<String> allowedContentTypes
|
||||
) {}
|
||||
@@ -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<AttachmentDTO> 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<AttachmentDTO> getAttachment(UUID attachmentId, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(service.getMetadata(attachmentId, principal.userId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<byte[]> downloadAttachment(UUID attachmentId, String variant, SessionPrincipal principal) {
|
||||
return service.downloadResponse(attachmentId, principal.userId(), variant);
|
||||
}
|
||||
}
|
||||
@@ -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<AttachmentDTO> 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<AttachmentDTO> 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<byte[]> 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
|
||||
);
|
||||
}
|
||||
@@ -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<SessionDTO> 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<Void> revokeSession(
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
@@ -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<SessionDTO> createSession(HttpServletRequest request) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION), request.getContentLengthLong()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> revokeSession() {
|
||||
authService.logout();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -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<ChatDTO> createChat(CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(chatService.createChat(principal.userId(), createChatDTO));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<ChatDTO> getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<ChatPageDTO> listChats(Integer limit, String cursor , @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(chatService.listChats(principal.userId(), limit, cursor));
|
||||
}
|
||||
}
|
||||
@@ -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<ChatDTO> 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<ChatDTO> 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<ChatPageDTO> 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
|
||||
);
|
||||
|
||||
}
|
||||
@@ -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<HealthDTO> 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<HealthDTO> readiness(
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
@@ -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<HealthDTO> liveness() {
|
||||
return ResponseEntity.ok(healthService.liveness());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<HealthDTO> readiness() {
|
||||
return ResponseEntity.ok(healthService.readiness());
|
||||
}
|
||||
}
|
||||
@@ -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<MessageDTO> 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<MessagePageDTO> listMessages(UUID chatId, Integer limit, String cursor, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(messageService.listMessages(principal.userId(), chatId, limit, cursor));
|
||||
}
|
||||
}
|
||||
@@ -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<MessageDTO> 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<MessagePageDTO> 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
|
||||
);
|
||||
}
|
||||
@@ -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<UserDTO> currentUser(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(userService.currentUser(principal.userId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<UserDTO> registerUser(CreateUserDTO createUserDTO) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(createUserDTO));
|
||||
}
|
||||
}
|
||||
@@ -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<UserDTO> 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<UserDTO> registerUser(
|
||||
@Parameter(name = "CreateUserDTO", description = "", required = true) @Valid @RequestBody CreateUserDTO createUserDTO
|
||||
);
|
||||
|
||||
}
|
||||
+170
@@ -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<ErrorDTO> invalidRequest(InvalidRequestException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
public ResponseEntity<ErrorDTO> 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<ErrorDTO> notFound(NotFoundException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public ResponseEntity<ErrorDTO> conflict(ConflictException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(PayloadTooLargeException.class)
|
||||
public ResponseEntity<ErrorDTO> payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorDTO> validation(MethodArgumentNotValidException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorDTO> unreadable(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public ResponseEntity<ErrorDTO> missingParam(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<ErrorDTO> typeMismatch(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ResponseEntity<ErrorDTO> 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<ErrorDTO> methodValidation(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Validation failed", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ResponseEntity<ErrorDTO> methodNotAllowed(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Method not allowed", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(RateLimitedException.class)
|
||||
public ResponseEntity<ErrorDTO> 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<ErrorDTO> constraint(ConstraintViolationException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Validation failed", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorDTO> 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<ErrorDTO> serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler({
|
||||
CannotCreateTransactionException.class,
|
||||
DataAccessResourceFailureException.class
|
||||
})
|
||||
public ResponseEntity<ErrorDTO> dependencyUnavailable(Exception e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
"Dependency unavailable", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataAccessException.class)
|
||||
public ResponseEntity<ErrorDTO> dataAccess(DataAccessException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
|
||||
"Database error", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorDTO> missingHeader(MissingRequestHeaderException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Missing header: " + e.getHeaderName(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedMediaTypeException.class)
|
||||
public ResponseEntity<ErrorDTO> unsupportedMedia(UnsupportedMediaTypeException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(StorageUnavailableException.class)
|
||||
public ResponseEntity<ErrorDTO> storageUnavailable(StorageUnavailableException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE, e.getMessage(), req);
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorDTO> respond(HttpStatus status,
|
||||
ErrorErrorDTO.CodeEnum code,
|
||||
String message,
|
||||
HttpServletRequest req) {
|
||||
return ResponseEntity.status(status).body(errors.error(code, message, req));
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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<UUID> memberIds = new ArrayList<>();
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
public ChatDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor with only required parameters
|
||||
*/
|
||||
public ChatDTO(String title, List<UUID> 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<UUID> 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<UUID> getMemberIds() {
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
public void setMemberIds(List<UUID> 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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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<UUID> memberIds = new ArrayList<>();
|
||||
|
||||
public CreateChatDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CreateChatDTO(String title, List<UUID> 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<UUID> 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<UUID> getMemberIds() {
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
public void setMemberIds(List<UUID> 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 ");
|
||||
}
|
||||
}
|
||||
@@ -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<UUID> 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<UUID> getAttachmentIds() { return attachmentIds; }
|
||||
|
||||
public void setAttachmentIds(List<UUID> 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); }
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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<UUID> 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<UUID> 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<UUID> getAttachmentIds() {
|
||||
return attachmentIds;
|
||||
}
|
||||
|
||||
public void setAttachmentIds(List<UUID> 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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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 ");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
public InvalidRequestException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class PayloadTooLargeException extends RuntimeException {
|
||||
public PayloadTooLargeException(String message) { super(message); }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user