From 1fddc0e76ccdac6e7460377108dc72fae112e5ff Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 22 Oct 2026 20:59:59 +0300 Subject: [PATCH] init commit --- .dockerignore | 1 + .gitignore | 131 +++++++-- Dockerfile | 25 ++ build.gradle | 69 +++++ docker-compose.yml | 219 ++++++++++++++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 46175 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 248 ++++++++++++++++++ gradlew.bat | 93 +++++++ nginx.conf | 45 ++++ settings.gradle | 1 + .../messenger/MessengerLab1Application.java | 16 ++ .../messenger/cache/CacheHealthTracker.java | 19 ++ .../mtusi/messenger/config/JacksonConfig.java | 26 ++ .../mtusi/messenger/config/OpenApiConfig.java | 20 ++ .../messenger/config/RateLimitConfig.java | 25 ++ .../mtusi/messenger/config/RedisConfig.java | 105 ++++++++ .../messenger/config/SecurityConfig.java | 75 ++++++ .../config/properties/AppProperties.java | 8 + .../properties/IdempotencyProperties.java | 10 + .../config/properties/InstanceProperties.java | 7 + .../properties/RateLimitProperties.java | 6 + .../config/properties/RedisProperties.java | 16 ++ .../config/properties/SessionProperties.java | 10 + .../mtusi/messenger/controller/AuthApi.java | 119 +++++++++ .../messenger/controller/AuthController.java | 27 ++ .../messenger/controller/ChatController.java | 36 +++ .../mtusi/messenger/controller/ChatsApi.java | 216 +++++++++++++++ .../mtusi/messenger/controller/HealthApi.java | 89 +++++++ .../controller/HealthController.java | 23 ++ .../controller/MessageController.java | 30 +++ .../messenger/controller/MessagesApi.java | 138 ++++++++++ .../messenger/controller/UserController.java | 27 ++ .../mtusi/messenger/controller/UsersApi.java | 137 ++++++++++ .../GlobalExceptionHandler.java | 156 +++++++++++ .../java/ru/mtusi/messenger/dto/ChatDTO.java | 149 +++++++++++ .../ru/mtusi/messenger/dto/ChatPageDTO.java | 124 +++++++++ .../ru/mtusi/messenger/dto/CreateChatDTO.java | 101 +++++++ .../mtusi/messenger/dto/CreateMessageDTO.java | 40 +++ .../ru/mtusi/messenger/dto/CreateUserDTO.java | 110 ++++++++ .../java/ru/mtusi/messenger/dto/ErrorDTO.java | 87 ++++++ .../ru/mtusi/messenger/dto/ErrorErrorDTO.java | 178 +++++++++++++ .../ru/mtusi/messenger/dto/HealthDTO.java | 120 +++++++++ .../ru/mtusi/messenger/dto/MessageDTO.java | 189 +++++++++++++ .../mtusi/messenger/dto/MessagePageDTO.java | 125 +++++++++ .../ru/mtusi/messenger/dto/SessionDTO.java | 198 ++++++++++++++ .../java/ru/mtusi/messenger/dto/UserDTO.java | 162 ++++++++++++ .../messenger/exception/ApiErrorFactory.java | 74 ++++++ .../exception/ConflictException.java | 5 + .../exception/InvalidRequestException.java | 5 + .../exception/NotFoundException.java | 5 + .../exception/PayloadTooLargeException.java | 5 + .../exception/RateLimitedException.java | 7 + .../ServiceUnavailableException.java | 7 + .../exception/UnauthorizedException.java | 5 + .../messenger/filter/InstanceIdFilter.java | 30 +++ .../messenger/filter/RateLimitFilter.java | 49 ++++ .../messenger/filter/RequestIdFilter.java | 33 +++ .../ru/mtusi/messenger/mapper/ChatMapper.java | 35 +++ .../mtusi/messenger/mapper/MessageMapper.java | 23 ++ .../mtusi/messenger/mapper/SessionMapper.java | 17 ++ .../ru/mtusi/messenger/mapper/UserMapper.java | 20 ++ .../java/ru/mtusi/messenger/model/Chat.java | 53 ++++ .../mtusi/messenger/model/IdempotencyKey.java | 47 ++++ .../ru/mtusi/messenger/model/Message.java | 40 +++ .../ru/mtusi/messenger/model/Session.java | 42 +++ .../java/ru/mtusi/messenger/model/User.java | 48 ++++ .../messenger/repository/ChatRepository.java | 39 +++ .../repository/IdempotencyRepository.java | 39 +++ .../repository/MessageRepository.java | 39 +++ .../repository/SessionRepository.java | 12 + .../messenger/repository/UserRepository.java | 23 ++ .../security/ApiAuthenticationEntryPoint.java | 36 +++ .../messenger/security/BasicCredentials.java | 28 ++ .../security/SessionAuthenticationFilter.java | 45 ++++ .../SessionAuthenticationProvider.java | 33 +++ .../security/SessionAuthenticationToken.java | 34 +++ .../messenger/security/SessionPrincipal.java | 6 + .../mtusi/messenger/service/AuthService.java | 36 +++ .../mtusi/messenger/service/ChatService.java | 130 +++++++++ .../messenger/service/HealthService.java | 51 ++++ .../messenger/service/IdempotencyService.java | 63 +++++ .../messenger/service/MessageService.java | 116 ++++++++ .../service/SessionCacheService.java | 65 +++++ .../messenger/service/SessionService.java | 81 ++++++ .../mtusi/messenger/service/UserService.java | 84 ++++++ .../ru/mtusi/messenger/util/CursorCodec.java | 37 +++ .../mtusi/messenger/util/TokenGenerator.java | 17 ++ .../ru/mtusi/messenger/util/TokenHasher.java | 37 +++ .../IdempotencyPayloadConverter.java | 29 ++ .../messenger/validation/ChatValidator.java | 67 +++++ .../validation/IdempotencyValidator.java | 39 +++ src/main/resources/application.yaml | 89 +++++++ src/main/resources/db/migration/V1__init.sql | 94 +++++++ .../MessengerLab1ApplicationTests.java | 13 + 95 files changed, 5668 insertions(+), 27 deletions(-) create mode 100644 Dockerfile create mode 100644 build.gradle create mode 100644 docker-compose.yml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 nginx.conf create mode 100644 settings.gradle create mode 100644 src/main/java/ru/mtusi/messenger/MessengerLab1Application.java create mode 100644 src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java create mode 100644 src/main/java/ru/mtusi/messenger/config/JacksonConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/RedisConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/SecurityConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/AuthApi.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/AuthController.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/ChatController.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/ChatsApi.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/HealthApi.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/HealthController.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/MessageController.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/MessagesApi.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/UserController.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/UsersApi.java create mode 100644 src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/ChatDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/HealthDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/MessageDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/SessionDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/dto/UserDTO.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/ConflictException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/NotFoundException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java create mode 100644 src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java create mode 100644 src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java create mode 100644 src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java create mode 100644 src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java create mode 100644 src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/mapper/UserMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/model/Chat.java create mode 100644 src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java create mode 100644 src/main/java/ru/mtusi/messenger/model/Message.java create mode 100644 src/main/java/ru/mtusi/messenger/model/Session.java create mode 100644 src/main/java/ru/mtusi/messenger/model/User.java create mode 100644 src/main/java/ru/mtusi/messenger/repository/ChatRepository.java create mode 100644 src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java create mode 100644 src/main/java/ru/mtusi/messenger/repository/MessageRepository.java create mode 100644 src/main/java/ru/mtusi/messenger/repository/SessionRepository.java create mode 100644 src/main/java/ru/mtusi/messenger/repository/UserRepository.java create mode 100644 src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java create mode 100644 src/main/java/ru/mtusi/messenger/security/BasicCredentials.java create mode 100644 src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java create mode 100644 src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java create mode 100644 src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java create mode 100644 src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java create mode 100644 src/main/java/ru/mtusi/messenger/service/AuthService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/ChatService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/HealthService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/IdempotencyService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/MessageService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/SessionCacheService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/SessionService.java create mode 100644 src/main/java/ru/mtusi/messenger/service/UserService.java create mode 100644 src/main/java/ru/mtusi/messenger/util/CursorCodec.java create mode 100644 src/main/java/ru/mtusi/messenger/util/TokenGenerator.java create mode 100644 src/main/java/ru/mtusi/messenger/util/TokenHasher.java create mode 100644 src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java create mode 100644 src/main/java/ru/mtusi/messenger/validation/ChatValidator.java create mode 100644 src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java create mode 100644 src/main/resources/application.yaml create mode 100644 src/main/resources/db/migration/V1__init.sql create mode 100644 src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java diff --git a/.dockerignore b/.dockerignore index bc16e55..796eb7e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +!gradle-9.7.1-bin.zip \ No newline at end of file diff --git a/.gitignore b/.gitignore index b5a7189..ccdf7fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,109 @@ -# Local/private state +### Git ### +*.orig +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +### Java ### +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt +.mtj.tmp/ + +# Package files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# JVM crash logs +hs_err_pid* +replay_pid* + +### Gradle ### +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar + +### Maven ### +target/ +!.mvn/wrapper/maven-wrapper.jar +dependency-reduced-pom.xml + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr + +### Eclipse / STS ### +.apt_generated +.classpath +.factorypath +.project +.settings/ +.springBeans +.sts4-cache + +### VS Code ### +.vscode/ + +### Windows ### +Thumbs.db +ehthumbs.db +ehthumbs_vista.db +[Dd]esktop.ini +$RECYCLE.BIN/ +*.cab +*.msi +*.msix +*.msm +*.msp +*.lnk + +### macOS ### +.DS_Store +.AppleDouble +.LSOverride + +### Miscellaneous ### +*.sw? +.#* +*# +*~ +bin/ +/scratch +*.sublime-* + +### Environment / Secrets ### .env .env.* !.env.example secrets/ -certs/private/ -*.key -*.p12 -*.pfx -*.jks -*.pem -*.tfstate* -volumes/ -data/ -backups/ -# Runtime/build artifacts -.venv/ +secrets/*.txt +!secrets/.gitkeep + +### Python / venv ### __pycache__/ -*.py[cod] -node_modules/ -dist/ -build/ -target/ -bin/ -obj/ -coverage/ -*.log -.DS_Store -.idea/ -.vscode/ -# Keep small, sanitized evidence summaries in evidence/ under version control. -# Inspect git diff --cached: ignore rules are not a secret scanner. +*.pyc +.venv/ +.venv +venv/ + +### Lab evidence ### +evidence/**/*.dump +evidence/**/*.sql.gz +evidence/**/raw/ +evidence/**/*.raw \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..20085db --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM eclipse-temurin:21-jdk-jammy AS builder +WORKDIR /build +RUN apt-get update && apt-get install -y --no-install-recommends unzip \ + && rm -rf /var/lib/apt/lists/* +COPY gradle gradle +COPY gradlew settings.gradle build.gradle ./ +COPY gradle-9.7.1-bin.zip /tmp/gradle.zip +RUN unzip -q /tmp/gradle.zip -d /opt && rm /tmp/gradle.zip +ENV PATH="/opt/gradle-9.7.1/bin:$PATH" +RUN gradle dependencies --no-daemon +COPY contracts contracts +COPY src src +RUN gradle bootJar -x test --no-daemon + +FROM eclipse-temurin:21-jre-jammy AS runner +WORKDIR /app +RUN groupadd --system spring && useradd --system --gid spring --no-create-home spring +COPY --from=builder /build/build/libs/*.jar app.jar +RUN chown spring:spring app.jar +USER spring +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/actuator/health/readiness | grep -q UP || exit 1 +ENV JAVA_OPTS="-XX:MaxRAMPercentage=75 -Xss512k" +ENTRYPOINT ["sh", "-c", "exec java -Dfile.encoding=UTF-8 $JAVA_OPTS -jar app.jar"] \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..3f15f0a --- /dev/null +++ b/build.gradle @@ -0,0 +1,69 @@ +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' + + runtimeOnly 'io.netty:netty-transport-native-epoll::linux-x86_64' + + testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1' + + testImplementation 'org.springframework.boot:spring-boot-starter-restclient-test' + testImplementation 'org.springframework.boot:spring-boot-resttestclient' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3' + annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0' + annotationProcessor 'org.projectlombok:lombok' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + + testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test' + testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.withType(JavaCompile).configureEach { + options.compilerArgs << '-parameters' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..00d3bf7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,219 @@ +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: + test: ["CMD-SHELL", "pg_isready -U $$(cat /run/secrets/postgres_user) -d $$(cat /run/secrets/postgres_db)"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.25' + memory: 256M + + 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 + start_period: 5s + deploy: + resources: + limits: + cpus: '0.5' + memory: 256M + reservations: + cpus: '0.1' + memory: 64M + + migrate: + build: + context: . + dockerfile: Dockerfile + entrypoint: ["sh", "-c"] + command: + - "exec java -Dfile.encoding=UTF-8 -Dspring.main.web-application-type=none -jar app.jar" + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user + SPRING_DATASOURCE_PASSWORD_FILE: /run/secrets/postgres_password + SPRING_FLYWAY_ENABLED: "true" + secrets: + - postgres_user + - postgres_password + depends_on: + db: + condition: service_healthy + restart: "no" + networks: + - messenger-net + deploy: + resources: + limits: + cpus: '0.5' + memory: 512M + reservations: + cpus: '0.1' + memory: 128M + + api: + stop_grace_period: 40s + build: + context: . + dockerfile: Dockerfile + restart: unless-stopped + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + entrypoint: + - "sh" + - "-c" + - "export INSTANCE_ID=\"$$(cat /etc/hostname)\"; exec java -Dfile.encoding=UTF-8 $$JAVA_OPTS -jar app.jar" + environment: + RATE_PER_MINUTE: ${RATE_PER_MINUTE:-100000} + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user + SPRING_DATASOURCE_PASSWORD_FILE: /run/secrets/postgres_password + SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} + SPRING_FLYWAY_ENABLED: "false" + 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} + secrets: + - postgres_user + - postgres_password + networks: + - messenger-net + deploy: + replicas: 2 + resources: + limits: + cpus: '1.0' + memory: 512M + reservations: + cpus: '0.25' + memory: 256M + 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 + deploy: + resources: + limits: + cpus: '0.5' + memory: 128M + reservations: + cpus: '0.1' + memory: 32M + + minio: + image: quay.io/minio/minio:RELEASE.2025-09-07T16-13-09Z + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} + MINIO_BROWSER: "off" + volumes: + - minio-data:/data + 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: quay.io/minio/mc:RELEASE.2025-08-13T08-35-41Z + depends_on: + minio: + condition: service_healthy + entrypoint: > + /bin/sh -c " + 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/your-bucket-name; + mc anonymous set none local/your-bucket-name; + 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'; + " + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY} + volumes: + - ./policy.json:/tmp/policy.json:ro + 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 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..61285a659d17295f1de7c53e24fdf13ad755c379 GIT binary patch literal 46175 zcma&NWmKG9wk?cn;qLD4?(Xgo+}#P9AcecTOK=k0-KB7X7w!%r36RU%ea89j>2v%2 zy2jY`r|L&NwdbC5&AHZASAvGYhCo0-fPjFYcwhhD3mpOxLPbVff<-}9mQ7hfN=8*n zMn@YK0`jk~Y#ADPZt&s;&o%Vh+1OqX$SQPQUbO~kT2|`trE{h9WQ$5t)0<0SGK(9o zy!{fv+oYdReexE`UMYzV3-kOr>x=rJ7+6+0b5EnF$IG$Dt(hUAKx2>*-_*>j|Id49Q3}YN>5=$q?@D;}*%{N1&Ngq- zT;Qj#_R=+0ba4EqMNa487mOM?^?N!cyt;9!ID^&OIS$OX?qC^kSGrHw@&-mB@~L!$ zQMIB|qD849?j6c_o6Y9s2-@J%jl@tu1+mdGN~J$RK!v{juhQkNSMup%E!|Iwjp}G} z6l3PDwQp#b$A`v-92bY=W{dghjg1@gO53Q}P!4oN?n)(dY4}3I1erK<3&=O2;)*)+_&gzJwCFLYl&;nZCm zs21P5net@>H0V>H2FQ%TUoZBiSRH2w*u~K%d6Y|Fc_eO}lhQ1A!Z|)oX3+mS``s4O zQE>^#ibNrUi4P;{KRb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gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..19a6bde --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 0000000..b8be5fc --- /dev/null +++ b/nginx.conf @@ -0,0 +1,45 @@ +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 1m; + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + 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_503 http_504 non_idempotent; + proxy_next_upstream_tries 3; + + proxy_connect_timeout 1s; + proxy_send_timeout 10s; + proxy_read_timeout 10s; + } + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..650573b --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'messenger-lab1' diff --git a/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java new file mode 100644 index 0000000..5493866 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration; + +@ConfigurationPropertiesScan +@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class) +public class MessengerLab1Application { + + public static void main(String[] args) { + SpringApplication.run(MessengerLab1Application.class, args); + } + +} diff --git a/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java new file mode 100644 index 0000000..c3c1d66 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java @@ -0,0 +1,19 @@ +package ru.mtusi.messenger.cache; + +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Component +public class CacheHealthTracker { + + private final AtomicBoolean stale = new AtomicBoolean(false); + + public void markStale() { + stale.set(true); + } + + public boolean consumeStale() { + return stale.getAndSet(false); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/JacksonConfig.java b/src/main/java/ru/mtusi/messenger/config/JacksonConfig.java new file mode 100644 index 0000000..585c537 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/JacksonConfig.java @@ -0,0 +1,26 @@ +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.Integer, CoercionAction.Fail); + config.setCoercion(CoercionInputShape.Float, CoercionAction.Fail); + }); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java new file mode 100644 index 0000000..06edae6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +public class OpenApiConfig { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java new file mode 100644 index 0000000..3a60957 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java @@ -0,0 +1,25 @@ +package ru.mtusi.messenger.config; + +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.Bucket; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.mtusi.messenger.config.properties.RateLimitProperties; + +import java.time.Duration; + +@Configuration +@RequiredArgsConstructor +public class RateLimitConfig { + private final RateLimitProperties props; + + @Bean + public Bucket rateLimitBucket() { + Bandwidth limit = Bandwidth.builder() + .capacity(props.ratePerMinute()) + .refillGreedy(props.ratePerMinute(), Duration.ofMinutes(1)) + .build(); + return Bucket.builder().addLimit(limit).build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/RedisConfig.java b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java new file mode 100644 index 0000000..badf523 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java @@ -0,0 +1,105 @@ +package ru.mtusi.messenger.config; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.SocketOptions; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cache.Cache; +import org.springframework.cache.annotation.CachingConfigurer; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.CacheErrorHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import ru.mtusi.messenger.cache.CacheHealthTracker; +import ru.mtusi.messenger.config.properties.RedisProperties; +import ru.mtusi.messenger.config.properties.SessionProperties; +import ru.mtusi.messenger.service.SessionService; + +@Slf4j +@Configuration +@EnableCaching +@EnableConfigurationProperties(RedisProperties.class) +@RequiredArgsConstructor +public class RedisConfig implements CachingConfigurer { + private final SessionProperties sessionProperties; + private final RedisProperties redisProperties; + private final CacheHealthTracker cacheHealthTracker; + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + RedisStandaloneConfiguration server = + new RedisStandaloneConfiguration(redisProperties.host(), redisProperties.port()); + + SocketOptions socketOptions = SocketOptions.builder() + .connectTimeout(redisProperties.connectTimeout()) + .keepAlive(SocketOptions.KeepAliveOptions.builder() + .enable() + .idle(redisProperties.keepAliveIdle()) + .interval(redisProperties.keepAliveInterval()) + .count(3) + .build()) + .tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder() + .tcpUserTimeout(redisProperties.tcpUserTimeout()) + .enable() + .build()) + .build(); + + ClientOptions clientOptions = ClientOptions.builder() + .socketOptions(socketOptions) + .autoReconnect(true) + .build(); + + LettuceClientConfiguration client = LettuceClientConfiguration.builder() + .commandTimeout(redisProperties.commandTimeout()) + .shutdownTimeout(redisProperties.shutdownTimeout()) + .clientOptions(clientOptions) + .build(); + + return new LettuceConnectionFactory(server, client); + } + + @Bean + public RedisCacheManager cacheManager(RedisConnectionFactory cf) { + RedisCacheConfiguration cfg = RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(sessionProperties.ttl()) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair + .fromSerializer(new JacksonJsonRedisSerializer<>(SessionService.SessionRecord.class))); + return RedisCacheManager.builder(cf).cacheDefaults(cfg).build(); + } + + @Override + public CacheErrorHandler errorHandler() { + return new CacheErrorHandler() { + @Override + public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { + cacheHealthTracker.markStale(); + log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { + cacheHealthTracker.markStale(); + log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { + cacheHealthTracker.markStale(); + log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheClearError(RuntimeException e, Cache cache) { + cacheHealthTracker.markStale(); + log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage()); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java new file mode 100644 index 0000000..a2233e0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java @@ -0,0 +1,75 @@ +package ru.mtusi.messenger.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import ru.mtusi.messenger.security.ApiAuthenticationEntryPoint; +import ru.mtusi.messenger.security.SessionAuthenticationFilter; +import ru.mtusi.messenger.security.SessionAuthenticationProvider; +import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; +import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + private final SessionAuthenticationProvider sessionAuthenticationProvider; + private final ApiAuthenticationEntryPoint entryPoint; + + @Bean + public PasswordEncoder passwordEncoder() { + return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); + } + + @Bean + public AuthenticationManager authenticationManager() { + return new ProviderManager(sessionAuthenticationProvider); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, + AuthenticationManager authenticationManager, + BearerTokenResolver bearerTokenResolver) throws Exception { + SessionAuthenticationFilter sessionFilter = + new SessionAuthenticationFilter(bearerTokenResolver, authenticationManager); + + http + .csrf(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .logout(AbstractHttpConfigurer::disable) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/health/**").permitAll() + .requestMatchers( + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs", + "/v3/api-docs/**" + ).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/auth/sessions").permitAll() + .requestMatchers("/actuator/health", "/actuator/health/**").permitAll() + .anyRequest().authenticated()) + .addFilterBefore(sessionFilter, UsernamePasswordAuthenticationFilter.class) + .exceptionHandling(eh -> eh.authenticationEntryPoint(entryPoint)); + + return http.build(); + } + + @Bean + public BearerTokenResolver bearerTokenResolver() { + return new DefaultBearerTokenResolver(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java new file mode 100644 index 0000000..127495e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java @@ -0,0 +1,8 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.limits") +public record AppProperties( + int maxMessagesPerChat +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java new file mode 100644 index 0000000..1d1efe4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/IdempotencyProperties.java @@ -0,0 +1,10 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.idempotency") +public record IdempotencyProperties( + int keyMaxLength, + String keyPattern, + int retentionHours +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java new file mode 100644 index 0000000..e5f51dd --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/InstanceProperties.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.instance") +public record InstanceProperties(String id) { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java new file mode 100644 index 0000000..39d4646 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.rate") +public record RateLimitProperties(int ratePerMinute, int retryAfterSeconds) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java new file mode 100644 index 0000000..994ae25 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.redis") +public record RedisProperties( + String host, + int port, + Duration commandTimeout, + Duration connectTimeout, + Duration shutdownTimeout, + Duration keepAliveIdle, + Duration keepAliveInterval, + Duration tcpUserTimeout +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java new file mode 100644 index 0000000..6ff06f2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java @@ -0,0 +1,10 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.session") +public record SessionProperties( + Duration ttl +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthApi.java b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java new file mode 100644 index 0000000..f7600f1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java @@ -0,0 +1,119 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import ru.mtusi.messenger.dto.SessionDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Auth", description = "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface AuthApi { + + /** + * POST /api/v1/auth/sessions : Вход: Basic username:password; выдаёт сессию + * + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createSession", + summary = "Вход: Basic username:password; выдаёт сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = SessionDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "basicAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/auth/sessions", + produces = { "application/json" } + ) + + ResponseEntity createSession( + HttpServletRequest request + ); + + + /** + * DELETE /api/v1/auth/sessions/current : Отозвать текущую сессию + * + * @return Успех (status code 204) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "revokeSession", + summary = "Отозвать текущую сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "204", description = "Успех"), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/api/v1/auth/sessions/current", + produces = { "application/json" } + ) + + ResponseEntity revokeSession( + + ); + +} diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthController.java b/src/main/java/ru/mtusi/messenger/controller/AuthController.java new file mode 100644 index 0000000..7c83d00 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthController.java @@ -0,0 +1,27 @@ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.service.AuthService; + +@RestController +@RequiredArgsConstructor +public class AuthController implements AuthApi { + private final AuthService authService; + + @Override + public ResponseEntity createSession(HttpServletRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION), request.getContentLengthLong())); + } + + @Override + public ResponseEntity revokeSession() { + authService.logout(); + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatController.java b/src/main/java/ru/mtusi/messenger/controller/ChatController.java new file mode 100644 index 0000000..0bee977 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatController.java @@ -0,0 +1,36 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.ChatService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class ChatController implements ChatsApi { + private final ChatService chatService; + + @Override + public ResponseEntity createChat(CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(chatService.createChat(principal.userId(), createChatDTO)); + } + + @Override + public ResponseEntity getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId)); + } + + @Override + public ResponseEntity listChats(Integer limit, String cursor , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.listChats(principal.userId(), limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java new file mode 100644 index 0000000..8a04bfe --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java @@ -0,0 +1,216 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import java.util.UUID; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Chats", description = "Управление чатами и доступ к чатам текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface ChatsApi { + + /** + * POST /api/v1/chats : Создать чат; вызывающий должен входить в member_ids + * + * @param createChatDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createChat", + summary = "Создать чат; вызывающий должен входить в member_ids", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/chats", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity createChat( + @Parameter(name = "CreateChatDTO", description = "", required = true) @Valid @RequestBody CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats/{chat_id} : Получить доступный чат + * + * @param chatId (required) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "getChatDTO", + summary = "Получить доступный чат", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}", + produces = { "application/json" } + ) + + ResponseEntity getChat( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) @PathVariable("chat_id") UUID chatId, + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats : Чаты текущего пользователя + * + * @param limit (optional, default to 50) + * @param cursor (optional) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "listChats", + summary = "Чаты текущего пользователя", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatPageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats", + produces = { "application/json" } + ) + + ResponseEntity listChats( + @Min(1) @Max(100) @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthApi.java b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java new file mode 100644 index 0000000..3c4f69f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java @@ -0,0 +1,89 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Generated; +import ru.mtusi.messenger.dto.HealthDTO; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Health", description = "Проверки живости и готовности процесса. Публичные, без аутентификации.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface HealthApi { + + /** + * GET /health/live : Процесс жив + * + * @return Успех (status code 200) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "liveness", + summary = "Процесс жив", + tags = { "Health" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/health/live", + produces = { "application/json" } + ) + + ResponseEntity liveness( + + ); + + + /** + * GET /health/ready : Готов принимать трафик + * + * @return Успех (status code 200) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "readiness", + summary = "Готов принимать трафик", + tags = { "Health" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/health/ready", + produces = { "application/json" } + ) + + ResponseEntity readiness( + + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthController.java b/src/main/java/ru/mtusi/messenger/controller/HealthController.java new file mode 100644 index 0000000..765d8b1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthController.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.service.HealthService; + +@RestController +@RequiredArgsConstructor +public class HealthController implements HealthApi { + private final HealthService healthService; + + @Override + public ResponseEntity liveness() { + return ResponseEntity.ok(healthService.liveness()); + } + + @Override + public ResponseEntity readiness() { + return ResponseEntity.ok(healthService.readiness()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/MessageController.java b/src/main/java/ru/mtusi/messenger/controller/MessageController.java new file mode 100644 index 0000000..02f462c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessageController.java @@ -0,0 +1,30 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.MessageService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class MessageController implements MessagesApi { + private final MessageService messageService; + + @Override + public ResponseEntity createMessage(UUID chatId, String idempotencyKey, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO, idempotencyKey)); + } + + @Override + public ResponseEntity listMessages(UUID chatId, Integer limit, String cursor, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(messageService.listMessages(principal.userId(), chatId, limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java new file mode 100644 index 0000000..a8ebb18 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java @@ -0,0 +1,138 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import java.util.UUID; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Messages", description = "Отправка и чтение сообщений внутри доступного чата.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface MessagesApi { + + @Operation( + operationId = "createMessage", + summary = "Отправить сообщение", + tags = { "Messages" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = MessageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/chats/{chat_id}/messages", + produces = { "application/json" }, + consumes = { "application/json" } + ) + ResponseEntity createMessage( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Parameter(name = "Idempotency-Key", required = true, in = ParameterIn.HEADER) + @RequestHeader(value = "Idempotency-Key", required = true) String idempotencyKey, + @Parameter(name = "CreateMessageDTO", description = "", required = true) + @Valid @RequestBody CreateMessageDTO createMessageDTO, + @AuthenticationPrincipal SessionPrincipal principal + ); + + @Operation( + operationId = "listMessages", + summary = "Сообщения по (created_at, id) по возрастанию", + tags = { "Messages" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = MessagePageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}/messages", + produces = { "application/json" } + ) + ResponseEntity listMessages( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Min(1) @Max(100) + @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) + @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/UserController.java b/src/main/java/ru/mtusi/messenger/controller/UserController.java new file mode 100644 index 0000000..da1bbad --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UserController.java @@ -0,0 +1,27 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.CreateUserDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.UserService; + +@RestController +@RequiredArgsConstructor +public class UserController implements UsersApi { + private final UserService userService; + + @Override + public ResponseEntity currentUser(@AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(userService.currentUser(principal.userId())); + } + + @Override + public ResponseEntity registerUser(CreateUserDTO createUserDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(createUserDTO)); + } +} diff --git a/src/main/java/ru/mtusi/messenger/controller/UsersApi.java b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java new file mode 100644 index 0000000..87ea33a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java @@ -0,0 +1,137 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.CreateUserDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.UserDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Users", description = "Регистрация пользователей и доступ к профилю текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface UsersApi { + + /** + * GET /api/v1/users/me : Текущий пользователь + * + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "currentUser", + summary = "Текущий пользователь", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/users/me", + produces = { "application/json" } + ) + + ResponseEntity currentUser( + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * POST /api/v1/users : Создать пользователя + * + * @param createUserDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "registerUser", + summary = "Создать пользователя", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/users", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity registerUser( + @Parameter(name = "CreateUserDTO", description = "", required = true) @Valid @RequestBody CreateUserDTO createUserDTO + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java new file mode 100644 index 0000000..02ee70d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java @@ -0,0 +1,156 @@ +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 final RateLimitProperties limitProperties; + private final ApiErrorFactory errors; + + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity invalidRequest(InvalidRequestException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity unauthorized(UnauthorizedException e, HttpServletRequest req) { + boolean isLogin = "/api/v1/auth/sessions".equals(req.getRequestURI()); + String challenge = isLogin + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .header("WWW-Authenticate", challenge) + .body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req)); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity notFound(NotFoundException e, HttpServletRequest req) { + return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity conflict(ConflictException e, HttpServletRequest req) { + return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req); + } + + @ExceptionHandler(PayloadTooLargeException.class) + public ResponseEntity payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) { + return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity unreadable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req); + } + + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity missingParam(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req); + } + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity typeMismatch(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseEntity mediaType(Exception e, HttpServletRequest req) { + return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, + "Unsupported media type", req); + } + + @ExceptionHandler(HandlerMethodValidationException.class) + public ResponseEntity methodValidation(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseEntity methodNotAllowed(Exception e, HttpServletRequest req) { + return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Method not allowed", req); + } + + @ExceptionHandler(RateLimitedException.class) + public ResponseEntity rateLimited(RateLimitedException e, HttpServletRequest req) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())) + .body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req)); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity constraint(ConstraintViolationException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity fallback(Exception e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Internal error", req); + } + + @ExceptionHandler(ServiceUnavailableException.class) + public ResponseEntity serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + e.getMessage(), req); + } + + @ExceptionHandler({ + CannotCreateTransactionException.class, + DataAccessResourceFailureException.class + }) + public ResponseEntity dependencyUnavailable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + "Dependency unavailable", req); + } + + @ExceptionHandler(DataAccessException.class) + public ResponseEntity dataAccess(DataAccessException e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Database error", req); + } + + @ExceptionHandler(MissingRequestHeaderException.class) + public ResponseEntity missingHeader(MissingRequestHeaderException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Missing header: " + e.getHeaderName(), req); + } + + private ResponseEntity respond(HttpStatus status, + ErrorErrorDTO.CodeEnum code, + String message, + HttpServletRequest req) { + return ResponseEntity.status(status).body(errors.error(code, message, req)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java new file mode 100644 index 0000000..f1c436f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -0,0 +1,149 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import java.time.Instant; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.UUID; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; +import jakarta.annotation.Generated; +import org.hibernate.validator.constraints.CodePointLength; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class ChatDTO { + + private UUID id; + + private String title; + + @Valid + private List memberIds = new ArrayList<>(); + + private Instant createdAt; + + public ChatDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ChatDTO(String title, List memberIds) { + this.title = title; + this.memberIds = memberIds; + } + + public ChatDTO id(UUID id) { + this.id = id; + return this; + } + + @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public ChatDTO title(String title) { + this.title = title; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public ChatDTO memberIds(List memberIds) { + this.memberIds = memberIds; + return this; + } + + public ChatDTO addMemberIdsItem(UUID memberIdsItem) { + if (this.memberIds == null) { + this.memberIds = new ArrayList<>(); + } + this.memberIds.add(memberIdsItem); + return this; + } + + @NotNull @Valid @Size(min = 1, max = 100) + @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("member_ids") + public List getMemberIds() { + return memberIds; + } + + public void setMemberIds(List memberIds) { + this.memberIds = memberIds; + } + + public ChatDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChatDTO createChat = (ChatDTO) o; + return Objects.equals(this.id, createChat.id) && + Objects.equals(this.title, createChat.title) && + Objects.equals(this.memberIds, createChat.memberIds) && + Objects.equals(this.createdAt, createChat.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, memberIds, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ChatDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" title: ").append(toIndentedString(title)).append("\n"); + sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java new file mode 100644 index 0000000..240e39f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java @@ -0,0 +1,124 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.ArrayList; +import java.util.List; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ChatPageDTO + */ + +public class ChatPageDTO { + + @Valid + private List<@Valid ChatDTO> items = new ArrayList<>(); + + private String nextCursor = null; + + public ChatPageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ChatPageDTO(List<@Valid ChatDTO> items, String nextCursor) { + this.items = items; + this.nextCursor = nextCursor; + } + + public ChatPageDTO items(List<@Valid ChatDTO> items) { + this.items = items; + return this; + } + + public ChatPageDTO addItemsItem(ChatDTO itemsItem) { + if (this.items == null) { + this.items = new ArrayList<>(); + } + this.items.add(itemsItem); + return this; + } + + /** + * Get items + * @return items + */ + @NotNull @Valid + @Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("items") + public List<@Valid ChatDTO> getItems() { + return items; + } + + public void setItems(List<@Valid ChatDTO> items) { + this.items = items; + } + + public ChatPageDTO nextCursor(String nextCursor) { + this.nextCursor = nextCursor; + return this; + } + + /** + * Get nextCursor + * @return nextCursor + */ + @JsonInclude(JsonInclude.Include.ALWAYS) + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChatPageDTO chatPageDTO = (ChatPageDTO) o; + return Objects.equals(this.items, chatPageDTO.items) && + Objects.equals(this.nextCursor, chatPageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ChatPageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java new file mode 100644 index 0000000..3b55371 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateChatDTO.java @@ -0,0 +1,101 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.annotation.Generated; +import org.hibernate.validator.constraints.CodePointLength; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class CreateChatDTO { + + private String title; + + @Valid + private List memberIds = new ArrayList<>(); + + public CreateChatDTO() { + super(); + } + + public CreateChatDTO(String title, List memberIds) { + this.title = title; + this.memberIds = memberIds; + } + + public CreateChatDTO title(String title) { + this.title = title; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public CreateChatDTO memberIds(List memberIds) { + this.memberIds = memberIds; + return this; + } + + public CreateChatDTO addMemberIdsItem(UUID memberIdsItem) { + if (this.memberIds == null) { + this.memberIds = new ArrayList<>(); + } + this.memberIds.add(memberIdsItem); + return this; + } + + @NotNull + @Valid + @Size(min = 1, max = 100) + @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("member_ids") + public List getMemberIds() { + return memberIds; + } + + public void setMemberIds(List memberIds) { + this.memberIds = memberIds; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CreateChatDTO that = (CreateChatDTO) o; + return Objects.equals(title, that.title) && Objects.equals(memberIds, that.memberIds); + } + + @Override + public int hashCode() { + return Objects.hash(title, memberIds); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateChatDTO {\n"); + sb.append(" title: ").append(toIndentedString(title)).append("\n"); + sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + private String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java new file mode 100644 index 0000000..718cb0f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java @@ -0,0 +1,40 @@ +package ru.mtusi.messenger.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import org.hibernate.validator.constraints.CodePointLength; + +import java.util.Objects; + +@Schema(name = "CreateMessage") +public class CreateMessageDTO { + + private String text; + + public CreateMessageDTO() {} + + public CreateMessageDTO text(String text) { + this.text = text; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { return text; } + + public void setText(String text) { this.text = text; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CreateMessageDTO d)) return false; + return Objects.equals(text, d.text); + } + + @Override + public int hashCode() { return Objects.hash(text); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java new file mode 100644 index 0000000..27876f5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateUserDTO.java @@ -0,0 +1,110 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.annotation.Generated; +import org.hibernate.validator.constraints.CodePointLength; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class CreateUserDTO { + + private String username; + + private String displayName; + + private String password; + + public CreateUserDTO() { + super(); + } + + public CreateUserDTO(String username, String displayName, String password) { + this.username = username; + this.displayName = displayName; + this.password = password; + } + + public CreateUserDTO username(String username) { + this.username = username; + return this; + } + + @NotNull + @Pattern(regexp = "^[a-z0-9_]{3,32}$") + @Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("username") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public CreateUserDTO displayName(String displayName) { + this.displayName = displayName; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("display_name") + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public CreateUserDTO password(String password) { + this.password = password; + return this; + } + + @NotNull + @CodePointLength(min = 12, max = 128) + @Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED, accessMode = Schema.AccessMode.WRITE_ONLY) + @JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CreateUserDTO createUser = (CreateUserDTO) o; + return Objects.equals(this.username, createUser.username) && + Objects.equals(this.displayName, createUser.displayName) && + Objects.equals(this.password, createUser.password); + } + + @Override + public int hashCode() { + return Objects.hash(username, displayName, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateUserDTO {\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); + sb.append(" password: ").append(password != null ? "***" : "null").append("\n"); + sb.append("}"); + return sb.toString(); + } + + private String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java new file mode 100644 index 0000000..65c09ca --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java @@ -0,0 +1,87 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorDTO + */ + +public class ErrorDTO { + + private ErrorErrorDTO error; + + public ErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorDTO(ErrorErrorDTO error) { + this.error = error; + } + + public ErrorDTO error(ErrorErrorDTO error) { + this.error = error; + return this; + } + + /** + * Get error + * @return error + */ + @NotNull @Valid + @Schema(name = "error", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("error") + public ErrorErrorDTO getError() { + return error; + } + + public void setError(ErrorErrorDTO error) { + this.error = error; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorDTO errorDTO = (ErrorDTO) o; + return Objects.equals(this.error, errorDTO.error); + } + + @Override + public int hashCode() { + return Objects.hash(error); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorDTO {\n"); + sb.append(" error: ").append(toIndentedString(error)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java new file mode 100644 index 0000000..6804918 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java @@ -0,0 +1,178 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorErrorDTO + */ + +public class ErrorErrorDTO { + + /** + * Gets or Sets code + */ + public enum CodeEnum { + INVALID_REQUEST("invalid_request"), + UNAUTHORIZED("unauthorized"), + NOT_FOUND("not_found"), + CONFLICT("conflict"), + PAYLOAD_TOO_LARGE("payload_too_large"), + UNSUPPORTED_MEDIA_TYPE("unsupported_media_type"), + RATE_LIMITED("rate_limited"), + UNAVAILABLE("unavailable"), + INTERNAL_ERROR("internal_error"); + + private String value; + + CodeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static CodeEnum fromValue(String value) { + for (CodeEnum b : CodeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private CodeEnum code; + + private String message; + + private String requestId; + + public ErrorErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorErrorDTO(CodeEnum code, String message, String requestId) { + this.code = code; + this.message = message; + this.requestId = requestId; + } + + public ErrorErrorDTO code(CodeEnum code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @NotNull + @Schema(name = "code", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("code") + public CodeEnum getCode() { + return code; + } + + public void setCode(CodeEnum code) { + this.code = code; + } + + public ErrorErrorDTO message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @NotNull @Size(min = 1) + @Schema(name = "message", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("message") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public ErrorErrorDTO requestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Get requestId + * @return requestId + */ + @NotNull @Size(min = 1) + @Schema(name = "request_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("request_id") + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorErrorDTO errorErrorDTO = (ErrorErrorDTO) o; + return Objects.equals(this.code, errorErrorDTO.code) && + Objects.equals(this.message, errorErrorDTO.message) && + Objects.equals(this.requestId, errorErrorDTO.requestId); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, requestId); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorErrorDTO {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" requestId: ").append(toIndentedString(requestId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java new file mode 100644 index 0000000..bd42813 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java @@ -0,0 +1,120 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * HealthDTO + */ + +public class HealthDTO { + + /** + * Gets or Sets status + */ + public enum StatusEnum { + OK("ok"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private StatusEnum status; + + public HealthDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public HealthDTO(StatusEnum status) { + this.status = status; + } + + public HealthDTO status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @NotNull + @Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HealthDTO healthDTO = (HealthDTO) o; + return Objects.equals(this.status, healthDTO.status); + } + + @Override + public int hashCode() { + return Objects.hash(status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthDTO {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java new file mode 100644 index 0000000..703b3ac --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java @@ -0,0 +1,189 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +import org.hibernate.validator.constraints.CodePointLength; + +import java.time.Instant; +import java.util.UUID; + +/** + * MessageDTO + */ + +public class MessageDTO { + + private UUID id; + + private UUID chatId; + + private UUID senderId; + + private String text; + + private Instant createdAt; + + public MessageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public MessageDTO(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) { + this.id = id; + this.chatId = chatId; + this.senderId = senderId; + this.text = text; + this.createdAt = createdAt; + } + + public MessageDTO id(UUID id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @NotNull @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public MessageDTO chatId(UUID chatId) { + this.chatId = chatId; + return this; + } + + /** + * Get chatId + * @return chatId + */ + @NotNull @Valid + @Schema(name = "chat_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("chat_id") + public UUID getChatId() { + return chatId; + } + + public void setChatId(UUID chatId) { + this.chatId = chatId; + } + + public MessageDTO senderId(UUID senderId) { + this.senderId = senderId; + return this; + } + + /** + * Get senderId + * @return senderId + */ + @NotNull @Valid + @Schema(name = "sender_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("sender_id") + public UUID getSenderId() { + return senderId; + } + + public void setSenderId(UUID senderId) { + this.senderId = senderId; + } + + public MessageDTO text(String text) { + this.text = text; + return this; + } + + /** + * Get text + * @return text + */ + @NotNull + @CodePointLength(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public MessageDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @NotNull @Valid + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessageDTO messageDTO = (MessageDTO) o; + return Objects.equals(this.id, messageDTO.id) && + Objects.equals(this.chatId, messageDTO.chatId) && + Objects.equals(this.senderId, messageDTO.senderId) && + Objects.equals(this.text, messageDTO.text) && + Objects.equals(this.createdAt, messageDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, chatId, senderId, text, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessageDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n"); + sb.append(" senderId: ").append(toIndentedString(senderId)).append("\n"); + sb.append(" text: ").append(toIndentedString(text)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java new file mode 100644 index 0000000..2c44c67 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java @@ -0,0 +1,125 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.ArrayList; +import java.util.List; +import ru.mtusi.messenger.dto.MessageDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * MessagePageDTO + */ + +public class MessagePageDTO { + + @Valid + private List<@Valid MessageDTO> items = new ArrayList<>(); + + private String nextCursor = null; + + public MessagePageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public MessagePageDTO(List<@Valid MessageDTO> items, String nextCursor) { + this.items = items; + this.nextCursor = nextCursor; + } + + public MessagePageDTO items(List<@Valid MessageDTO> items) { + this.items = items; + return this; + } + + public MessagePageDTO addItemsItem(MessageDTO itemsItem) { + if (this.items == null) { + this.items = new ArrayList<>(); + } + this.items.add(itemsItem); + return this; + } + + /** + * Get items + * @return items + */ + @NotNull @Valid + @Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("items") + public List<@Valid MessageDTO> getItems() { + return items; + } + + public void setItems(List<@Valid MessageDTO> items) { + this.items = items; + } + + public MessagePageDTO nextCursor(String nextCursor) { + this.nextCursor = nextCursor; + return this; + } + + /** + * Get nextCursor + * @return nextCursor + */ + @JsonInclude(JsonInclude.Include.ALWAYS) + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessagePageDTO messagePageDTO = (MessagePageDTO) o; + return Objects.equals(this.items, messagePageDTO.items) && + Objects.equals(this.nextCursor, messagePageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessagePageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java new file mode 100644 index 0000000..bc1f077 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java @@ -0,0 +1,198 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.Instant; +import ru.mtusi.messenger.dto.UserDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * SessionDTO + */ + +public class SessionDTO { + + private String token; + + /** + * Gets or Sets tokenType + */ + public enum TokenTypeEnum { + BEARER("Bearer"); + + private String value; + + TokenTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TokenTypeEnum fromValue(String value) { + for (TokenTypeEnum b : TokenTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private TokenTypeEnum tokenType; + + private Instant expiresAt; + + private UserDTO user; + + public SessionDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public SessionDTO(String token, TokenTypeEnum tokenType, Instant expiresAt, UserDTO user) { + this.token = token; + this.tokenType = tokenType; + this.expiresAt = expiresAt; + this.user = user; + } + + public SessionDTO token(String token) { + this.token = token; + return this; + } + + /** + * Get token + * @return token + */ + @NotNull @Size(min = 32) + @Schema(name = "token", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token") + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public SessionDTO tokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + return this; + } + + /** + * Get tokenType + * @return tokenType + */ + @NotNull + @Schema(name = "token_type", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token_type") + public TokenTypeEnum getTokenType() { + return tokenType; + } + + public void setTokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + } + + public SessionDTO expiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + /** + * Get expiresAt + * @return expiresAt + */ + @NotNull @Valid + @Schema(name = "expires_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("expires_at") + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public SessionDTO user(UserDTO user) { + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @NotNull @Valid + @Schema(name = "user", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("user") + public UserDTO getUser() { + return user; + } + + public void setUser(UserDTO user) { + this.user = user; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SessionDTO sessionDTO = (SessionDTO) o; + return Objects.equals(this.token, sessionDTO.token) && + Objects.equals(this.tokenType, sessionDTO.tokenType) && + Objects.equals(this.expiresAt, sessionDTO.expiresAt) && + Objects.equals(this.user, sessionDTO.user); + } + + @Override + public int hashCode() { + return Objects.hash(token, tokenType, expiresAt, user); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SessionDTO {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n"); + sb.append(" expiresAt: ").append(toIndentedString(expiresAt)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java new file mode 100644 index 0000000..9e940d7 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -0,0 +1,162 @@ +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, String password) { + 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 + */ + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserDTO userDTO = (UserDTO) o; + return Objects.equals(this.id, userDTO.id) && + Objects.equals(this.username, userDTO.username) && + Objects.equals(this.displayName, userDTO.displayName) && + Objects.equals(this.createdAt, userDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, displayName, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java new file mode 100644 index 0000000..26b98d5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java @@ -0,0 +1,74 @@ +package ru.mtusi.messenger.exception; + +import tools.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.ErrorErrorDTO; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class ApiErrorFactory { + private static final String DEFAULT_MESSAGE = "Error"; + private static final String REQUEST_ID_ATTR = "requestId"; + private static final String REQUEST_ID_MDC = "requestId"; + + private final ObjectMapper objectMapper; + + public ErrorDTO error(ErrorErrorDTO.CodeEnum code, String message, HttpServletRequest request) { + ErrorErrorDTO inner = new ErrorErrorDTO(); + inner.setCode(code); + inner.setMessage(normalizeMessage(message)); + inner.setRequestId(resolveRequestId(request)); + + ErrorDTO outer = new ErrorDTO(); + outer.setError(inner); + return outer; + } + + public void writeError(HttpServletResponse response, + HttpServletRequest request, + HttpStatus status, + String wwwAuthenticate, + ErrorErrorDTO.CodeEnum code, + String message) throws IOException { + String requestId = resolveRequestId(request); + response.setStatus(status.value()); + response.setHeader("X-Request-Id", requestId); + if (wwwAuthenticate != null) { + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); + } + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + objectMapper.writeValue(response.getWriter(), error(code, message, request)); + } + + public String resolveRequestId(HttpServletRequest request) { + Object attr = request.getAttribute(REQUEST_ID_ATTR); + if (attr instanceof String s && !s.isBlank()) { + return s; + } + String mdc = MDC.get(REQUEST_ID_MDC); + if (mdc != null && !mdc.isBlank()) { + request.setAttribute(REQUEST_ID_ATTR, mdc); + return mdc; + } + String generated = UUID.randomUUID().toString(); + request.setAttribute(REQUEST_ID_ATTR, generated); + return generated; + } + + private String normalizeMessage(String message) { + return (message == null || message.isBlank()) ? DEFAULT_MESSAGE : message; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ConflictException.java b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java new file mode 100644 index 0000000..aa0a2bf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class ConflictException extends RuntimeException { + public ConflictException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java new file mode 100644 index 0000000..a4d7792 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class InvalidRequestException extends RuntimeException { + public InvalidRequestException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java new file mode 100644 index 0000000..6055db3 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java new file mode 100644 index 0000000..2493a9e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class PayloadTooLargeException extends RuntimeException { + public PayloadTooLargeException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java new file mode 100644 index 0000000..3c1ab32 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class RateLimitedException extends RuntimeException { + public RateLimitedException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java new file mode 100644 index 0000000..da56529 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class ServiceUnavailableException extends RuntimeException { + public ServiceUnavailableException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java new file mode 100644 index 0000000..a086273 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java b/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java new file mode 100644 index 0000000..36721da --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/InstanceIdFilter.java @@ -0,0 +1,30 @@ +package ru.mtusi.messenger.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import ru.mtusi.messenger.config.properties.InstanceProperties; + +import java.io.IOException; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +@RequiredArgsConstructor +public class InstanceIdFilter extends OncePerRequestFilter { + + private final InstanceProperties props; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + response.setHeader("X-Instance-Id", props.id()); + chain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java new file mode 100644 index 0000000..2476160 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java @@ -0,0 +1,49 @@ +package ru.mtusi.messenger.filter; + +import io.github.bucket4j.Bucket; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import ru.mtusi.messenger.config.properties.RateLimitProperties; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@Order(2) +@RequiredArgsConstructor +public class RateLimitFilter extends OncePerRequestFilter { + private final RateLimitProperties limitProperties; + private final Bucket bucket; + private final ApiErrorFactory errors; + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + if (!req.getRequestURI().startsWith("/api/")) { + chain.doFilter(req, res); + return; + } + + if (bucket.tryConsume(1)) { + chain.doFilter(req, res); + return; + } + + res.setHeader("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())); + errors.writeError( + res, + req, + HttpStatus.TOO_MANY_REQUESTS, + null, + ErrorErrorDTO.CodeEnum.RATE_LIMITED, + "Rate limit exceeded. Try again later."); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java new file mode 100644 index 0000000..b6ad09c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java @@ -0,0 +1,33 @@ +package ru.mtusi.messenger.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class RequestIdFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + String rid = UUID.randomUUID().toString(); + res.setHeader("X-Request-Id", rid); + req.setAttribute("requestId", rid); + MDC.put("requestId", rid); + try { + chain.doFilter(req, res); + } finally { + MDC.clear(); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java new file mode 100644 index 0000000..b3f8859 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java @@ -0,0 +1,35 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Mapper(componentModel = "spring") +public interface ChatMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "members", ignore = true) + @Mapping(target = "messages", ignore = true) + Chat toChat(CreateChatDTO dto); + + @Mapping(target = "memberIds", source = "members", qualifiedByName = "usersToIds") + ChatDTO toChatDto(Chat chat); + + @Named("usersToIds") + default List usersToIds(Set users) { + if (users == null) return new ArrayList<>(); + List ids = new ArrayList<>(users.size()); + for (User u : users) ids.add(u.getId()); + return ids; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java new file mode 100644 index 0000000..393f23e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.model.Message; + +@Mapper(componentModel = "spring") +public interface MessageMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "chat", ignore = true) + @Mapping(target = "sender", ignore = true) + @Mapping(target = "createdAt", ignore = true) + Message toMessage(MessageDTO dto); + + @Mapping(target = "chatId", source = "chat.id") + @Mapping(target = "senderId", source = "sender.id") + MessageDTO toMessageDTO(Message entity); + + Message toMessage(CreateMessageDTO dto); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java new file mode 100644 index 0000000..83478e4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.Session; + +@Mapper(componentModel = "spring") +public interface SessionMapper { + + @Mapping(target = "token", source = "tokenRaw") + @Mapping(target = "tokenType", expression = "java(ru.mtusi.messenger.dto.SessionDTO.TokenTypeEnum.BEARER)") + @Mapping(target = "expiresAt", source = "session.expiresAt") + @Mapping(target = "user", source = "userDTO") + SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java new file mode 100644 index 0000000..0ee46d9 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.CreateUserDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.User; + +@Mapper(componentModel = "spring") +public interface UserMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "passwordHash", ignore = true) + @Mapping(target = "chats", ignore = true) + @Mapping(target = "messages", ignore = true) + User toUser(CreateUserDTO dto); + + UserDTO toUserDto(User user); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Chat.java b/src/main/java/ru/mtusi/messenger/model/Chat.java new file mode 100644 index 0000000..9fbb85f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Chat.java @@ -0,0 +1,53 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Entity +@Table(name = "chats") +@Getter +@Setter +@NoArgsConstructor +public class Chat { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false, length = 100) + private String title; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable( + name = "chat_members", + joinColumns = @JoinColumn(name = "chat_id"), + inverseJoinColumns = @JoinColumn(name = "user_id") + ) + private Set members = new HashSet<>(); + + @OneToMany( + mappedBy = "chat", + fetch = FetchType.LAZY, + cascade = CascadeType.ALL, + orphanRemoval = true + ) + @OrderBy("createdAt ASC, id ASC") + private List messages = new ArrayList<>(); + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java b/src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java new file mode 100644 index 0000000..95e494f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/IdempotencyKey.java @@ -0,0 +1,47 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "idempotency_keys") +@Getter +@Setter +public class IdempotencyKey { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "user_id", nullable = false) + private UUID userId; + + @Column(nullable = false, length = 16) + private String method; + + @Column(name = "chat_id", nullable = false) + private UUID chatId; + + @Column(name = "idempotency_key", nullable = false, length = 128) + private String idempotencyKey; + + @Column(name = "request_hash", nullable = false, length = 64) + private String requestHash; + + @Column(name = "status_code") + private Short statusCode; + + @JdbcTypeCode(SqlTypes.JSON) + @Column(name = "response_body", columnDefinition = "jsonb") + private String responseBody; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Message.java b/src/main/java/ru/mtusi/messenger/model/Message.java new file mode 100644 index 0000000..b4a368d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Message.java @@ -0,0 +1,40 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Entity +@Table(name = "messages") +@Getter +@Setter +@NoArgsConstructor +public class Message { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "chat_id", nullable = false) + private Chat chat; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "sender_id", nullable = false) + private User sender; + + @Column(nullable = false, length = 4000) + private String text; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Session.java b/src/main/java/ru/mtusi/messenger/model/Session.java new file mode 100644 index 0000000..4a2124d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Session.java @@ -0,0 +1,42 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Entity +@Table(name = "sessions") +@Getter +@Setter +@NoArgsConstructor +public class Session { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "user_id", nullable = false) + private UUID userId; + + @Column(name = "token_hash", nullable = false, unique = true) + private byte[] tokenHash; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "expires_at", nullable = false) + private Instant expiresAt; + + @Column(name = "revoked_at") + private Instant revokedAt; + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/User.java b/src/main/java/ru/mtusi/messenger/model/User.java new file mode 100644 index 0000000..2138680 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/User.java @@ -0,0 +1,48 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@Entity +@Table(name = "users") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class User{ + + @Id() + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false, unique = true, length = 32) + private String username; + + @Column(name = "display_name", nullable = false, length = 100) + private String displayName; + + @Column(name = "password_hash", nullable = false, length = 255) + private String passwordHash; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @ManyToMany(mappedBy = "members", fetch = FetchType.LAZY) + private Set chats = new HashSet<>(); + + @OneToMany(mappedBy = "sender", fetch = FetchType.LAZY) + private Set messages = new HashSet<>(); + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java new file mode 100644 index 0000000..0ed5887 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.Chat; + +import org.springframework.data.domain.Pageable; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface ChatRepository extends JpaRepository { + + @EntityGraph(attributePaths = "members") + @Query(""" + select distinct c from Chat c + join c.members m + where m.id = :userId + order by c.createdAt asc, c.id asc + """) + List findPageByMember(@Param("userId") UUID userId, + Pageable pageable); + + @EntityGraph(attributePaths = "members") + @Query(""" + select distinct c from Chat c + join c.members m + where m.id = :userId + and (c.createdAt > :cursorCreated + or (c.createdAt = :cursorCreated and c.id > :cursorId)) + order by c.createdAt asc, c.id asc + """) + List findPageByMemberAfterCursor(@Param("userId") UUID userId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java b/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java new file mode 100644 index 0000000..9cb32e0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/IdempotencyRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; +import ru.mtusi.messenger.model.IdempotencyKey; + +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface IdempotencyRepository extends JpaRepository { + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = """ + INSERT INTO idempotency_keys + (user_id, method, chat_id, idempotency_key, request_hash, created_at) + VALUES (:userId, :method, :chatId, :key, :hash, NOW()) + ON CONFLICT (user_id, method, chat_id, idempotency_key) DO NOTHING + """, nativeQuery = true) + int tryClaim(UUID userId, String method, UUID chatId, String key, String hash); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = """ + UPDATE idempotency_keys + SET status_code = :statusCode, + response_body = CAST(:body AS jsonb) + WHERE user_id = :userId + AND method = :method + AND chat_id = :chatId + AND idempotency_key = :key + """, nativeQuery = true) + int commitResponse(UUID userId, String method, UUID chatId, String key, + int statusCode, String body); + + Optional findByUserIdAndMethodAndChatIdAndIdempotencyKey( + UUID userId, String method, UUID chatId, String idempotencyKey); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java new file mode 100644 index 0000000..35134b4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.Message; + +import org.springframework.data.domain.Pageable; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface MessageRepository extends JpaRepository { + + long countByChatId(UUID chatId); + + @EntityGraph(attributePaths = "sender") + @Query(""" + select m from Message m + where m.chat.id = :chatId + order by m.createdAt asc, m.id asc + """) + List findPageByChat(@Param("chatId") UUID chatId, + Pageable pageable); + + @EntityGraph(attributePaths = "sender") + @Query(""" + select m from Message m + where m.chat.id = :chatId + and (m.createdAt > :cursorCreated + or (m.createdAt = :cursorCreated and m.id > :cursorId)) + order by m.createdAt asc, m.id asc + """) + List findPageByChatAfterCursor(@Param("chatId") UUID chatId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java new file mode 100644 index 0000000..2fc1dce --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java @@ -0,0 +1,12 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.mtusi.messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository extends JpaRepository { + Optional findByTokenHash(byte[] tokenHash); + +} diff --git a/src/main/java/ru/mtusi/messenger/repository/UserRepository.java b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java new file mode 100644 index 0000000..9a9a6d4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.repository; + + +import jakarta.persistence.LockModeType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.User; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public interface UserRepository extends JpaRepository { + + Optional findByUsername(String username); + + @Lock(LockModeType.PESSIMISTIC_READ) + @Query("select u from User u where u.id in :ids") + Set findAllByIdForShare(@Param("ids") Set ids); +} diff --git a/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java new file mode 100644 index 0000000..d069218 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java @@ -0,0 +1,36 @@ +package ru.mtusi.messenger.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ApiErrorFactory errors; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException { + boolean isLogin = "/api/v1/auth/sessions".equals(request.getRequestURI()); + String challenge = isLogin + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + + errors.writeError( + response, + request, + HttpStatus.UNAUTHORIZED, + challenge, + ErrorErrorDTO.CodeEnum.UNAUTHORIZED, + "No valid authentication"); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java new file mode 100644 index 0000000..116ad7c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java @@ -0,0 +1,28 @@ +package ru.mtusi.messenger.security; + +import ru.mtusi.messenger.exception.UnauthorizedException; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public record BasicCredentials(String username, String password) { + + public static BasicCredentials parse(String header) { + if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) { + throw new UnauthorizedException("Basic authentication required"); + } + String decoded; + try { + decoded = new String( + Base64.getDecoder().decode(header.substring(6).trim()), + StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new UnauthorizedException("Invalid Basic encoding"); + } + int i = decoded.indexOf(':'); + if (i < 0) { + throw new UnauthorizedException("Invalid Basic credentials"); + } + return new BasicCredentials(decoded.substring(0, i), decoded.substring(i + 1)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java new file mode 100644 index 0000000..6bfe5d0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java @@ -0,0 +1,45 @@ +package ru.mtusi.messenger.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class SessionAuthenticationFilter extends OncePerRequestFilter { + private final BearerTokenResolver bearerTokenResolver; + private final AuthenticationManager authenticationManager; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + try { + String token = bearerTokenResolver.resolve(request); + if (token != null && !token.isBlank()) { + try { + Authentication auth = authenticationManager.authenticate( + new SessionAuthenticationToken(token)); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(auth); + SecurityContextHolder.setContext(context); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + } + } + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java new file mode 100644 index 0000000..d1d5ee5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java @@ -0,0 +1,33 @@ +package ru.mtusi.messenger.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.service.SessionService; + +@Component +@RequiredArgsConstructor +public class SessionAuthenticationProvider implements AuthenticationProvider { + private final SessionService sessionService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String token = (String) authentication.getCredentials(); + try { + var rec = sessionService.requireActive(token); + return new SessionAuthenticationToken( + new SessionPrincipal(rec.userId(), rec.sessionId())); + } catch (UnauthorizedException e) { + throw new BadCredentialsException(e.getMessage(), e); + } + } + + @Override + public boolean supports(Class authentication) { + return SessionAuthenticationToken.class.isAssignableFrom(authentication); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java new file mode 100644 index 0000000..f5e9977 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java @@ -0,0 +1,34 @@ +package ru.mtusi.messenger.security; + +import org.springframework.security.authentication.AbstractAuthenticationToken; + +import java.util.List; + +public class SessionAuthenticationToken extends AbstractAuthenticationToken { + private final String rawToken; + private final SessionPrincipal principal; + + public SessionAuthenticationToken(String rawToken) { + super(List.of()); + this.rawToken = rawToken; + this.principal = null; + setAuthenticated(false); + } + + public SessionAuthenticationToken(SessionPrincipal principal) { + super(List.of()); + this.rawToken = null; + this.principal = principal; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return rawToken; + } + + @Override + public Object getPrincipal() { + return principal; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java new file mode 100644 index 0000000..8bcae0e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.security; + +import java.util.UUID; + +public record SessionPrincipal(UUID userId, UUID sessionId) { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/AuthService.java b/src/main/java/ru/mtusi/messenger/service/AuthService.java new file mode 100644 index 0000000..8401f57 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AuthService.java @@ -0,0 +1,36 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.security.BasicCredentials; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Service +@RequiredArgsConstructor +public class AuthService { + private final UserService userService; + private final SessionService sessionService; + + public SessionDTO login(String authorizationHeader, long contentLength) { + if (contentLength > 0) { + throw new InvalidRequestException("Request body is not allowed"); + } + var creds = BasicCredentials.parse(authorizationHeader); + UserDTO userDTO = userService.authenticate(creds.username(), creds.password()); + return sessionService.createSession(userDTO); + } + + public void logout() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !(auth.getPrincipal() instanceof SessionPrincipal sp)) { + throw new UnauthorizedException("No active session"); + } + sessionService.revoke(sp.sessionId()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/ChatService.java b/src/main/java/ru/mtusi/messenger/service/ChatService.java new file mode 100644 index 0000000..de7db4f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -0,0 +1,130 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.mapper.ChatMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.ChatRepository; +import ru.mtusi.messenger.validation.ChatValidator; +import ru.mtusi.messenger.util.CursorCodec; + +import java.util.*; + +@Service +@Slf4j +@RequiredArgsConstructor +public class ChatService { + private final ChatMapper chatMapper; + private final ChatValidator chatValidator; + private final ChatRepository chatRepository; + + @Transactional + public ChatDTO createChat(UUID caller, CreateChatDTO createChatDTO) { + Set members = chatValidator.validateCreate(caller, createChatDTO); + Chat chat = buildChat(createChatDTO, members); + chat = persistChat(chat); + return chatMapper.toChatDto(chat); + } + + private Chat buildChat(CreateChatDTO createChatDTO, Set members) { + Chat chat = chatMapper.toChat(createChatDTO); + chat.setMembers(members); + return chat; + } + + private Chat persistChat(Chat chat) { + try { + return chatRepository.saveAndFlush(chat); + } catch (DataIntegrityViolationException e) { + throw new InvalidRequestException("Cannot create chat: invalid data"); + } + } + + @Transactional(readOnly = true) + public ChatDTO getChatDTO(UUID caller, UUID chatId) { + Chat chat = requireChatForMember(caller, chatId); + return chatMapper.toChatDto(chat); + } + + @Transactional(readOnly = true) + public Chat getChat(UUID caller, UUID chatId) { + return requireChatForMember(caller, chatId); + } + + private Chat requireChatForMember(UUID caller, UUID chatId) { + Chat chat = chatRepository.findById(chatId) + .orElseThrow(() -> new NotFoundException("Chat not found")); + if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) { + throw new NotFoundException("Chat not found"); + } + return chat; + } + + @Transactional(readOnly = true) + public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { + int size = resolveSize(limit); + CursorCodec.Cursor decoded = parseChatsCursor(cursor); + List rows = loadChatPage(userId, decoded, size); + return buildPage(rows, size); + } + + private int resolveSize(Integer limit) { + return (limit == null) ? 50 : limit; + } + + private List loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) { + if (cursor == null) { + return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)); + } + return chatRepository.findPageByMemberAfterCursor( + userId, + cursor.boundary().createdAt(), + cursor.boundary().id(), + Pageable.ofSize(size + 1)); + } + + private CursorCodec.Cursor parseChatsCursor(String cursor) { + if (cursor == null) + return null; + if (cursor.isEmpty()) + throw new InvalidRequestException("Cursor must not be empty"); + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() != null) + throw new InvalidRequestException("Invalid cursor"); + return decoded; + } + + private ChatPageDTO buildPage(List rows, int size) { + List items = rows.stream() + .limit(size) + .map(chatMapper::toChatDto) + .toList(); + + ChatPageDTO page = new ChatPageDTO(); + page.setItems(items); + page.setNextCursor(buildNextCursor(rows, size)); + return page; + } + + private String buildNextCursor(List rows, int size) { + if (rows.size() <= size) { + return null; + } + Chat last = rows.get(size - 1); + return CursorCodec.encode(null, boundaryOf(last)); + } + + private CursorCodec.PageBoundary boundaryOf(Chat chat) { + return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/HealthService.java b/src/main/java/ru/mtusi/messenger/service/HealthService.java new file mode 100644 index 0000000..60decf5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/HealthService.java @@ -0,0 +1,51 @@ +package ru.mtusi.messenger.service; + +import com.zaxxer.hikari.HikariDataSource; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.exception.ServiceUnavailableException; + +import javax.sql.DataSource; + +@Service +@RequiredArgsConstructor +public class HealthService { + + private final JdbcTemplate jdbcTemplate; + private final DataSource dataSource; + + public HealthDTO readiness() { + requirePoolAvailable(); + requireDatabaseReachable(); + return ok(); + } + + public HealthDTO liveness() { + return ok(); + } + + private void requirePoolAvailable() { + if (dataSource instanceof HikariDataSource hikari) { + var pool = hikari.getHikariPoolMXBean(); + if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) { + throw new ServiceUnavailableException("Database connection pool exhausted"); + } + } + } + + private void requireDatabaseReachable() { + try { + jdbcTemplate.queryForObject("SELECT 1", Integer.class); + } catch (Exception e) { + throw new ServiceUnavailableException("Database unavailable"); + } + } + + private HealthDTO ok() { + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/IdempotencyService.java b/src/main/java/ru/mtusi/messenger/service/IdempotencyService.java new file mode 100644 index 0000000..043ef68 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/IdempotencyService.java @@ -0,0 +1,63 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.model.IdempotencyKey; +import ru.mtusi.messenger.repository.IdempotencyRepository; +import ru.mtusi.messenger.util.converter.IdempotencyPayloadConverter; +import ru.mtusi.messenger.validation.IdempotencyValidator; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.UUID; +import java.util.function.Supplier; + +@Service +@RequiredArgsConstructor +public class IdempotencyService { + + private final IdempotencyRepository idempotencyRepository; + private final IdempotencyPayloadConverter converter; + private final IdempotencyValidator validator; + + @Transactional + public T execute(UUID userId, String method, UUID chatId, String key, + Object requestBody, Class responseType, Supplier action) { + validator.validateKey(key); + String hash = hashRequest(requestBody); + + int claimed = idempotencyRepository.tryClaim(userId, method, chatId, key, hash); + if (claimed == 0) { + return replay(userId, method, chatId, key, hash, responseType); + } + + T result = action.get(); + idempotencyRepository.commitResponse(userId, method, chatId, key, 201, converter.toJson(result)); + return result; + } + + private T replay(UUID userId, String method, UUID chatId, String key, + String hash, Class responseType) { + IdempotencyKey stored = idempotencyRepository + .findByUserIdAndMethodAndChatIdAndIdempotencyKey(userId, method, chatId, key) + .orElseThrow(() -> new IllegalStateException("Idempotency row not visible after conflict")); + if (!stored.getRequestHash().equals(hash)) + throw new ConflictException("Idempotency-Key reused with a different request body"); + if (stored.getStatusCode() == null || stored.getStatusCode() != 201) + throw new ConflictException("Idempotency-Key has unexpected status"); + return converter.fromJson(stored.getResponseBody(), responseType); + } + + private String hashRequest(Object body) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(converter.toJson(body).getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (Exception e) { + throw new IllegalStateException("Cannot hash request body", e); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/MessageService.java b/src/main/java/ru/mtusi/messenger/service/MessageService.java new file mode 100644 index 0000000..d6d2ea0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/MessageService.java @@ -0,0 +1,116 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.AppProperties; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.PayloadTooLargeException; +import ru.mtusi.messenger.mapper.MessageMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.Message; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.MessageRepository; +import ru.mtusi.messenger.util.CursorCodec; +import ru.mtusi.messenger.service.IdempotencyService; + +import java.util.List; +import java.util.UUID; + +@Service +@Slf4j +@RequiredArgsConstructor +public class MessageService { + private final IdempotencyService idempotencyService; + private final MessageRepository messageRepository; + private final ChatService chatService; + private final UserService userService; + private final MessageMapper messageMapper; + private final AppProperties appProperties; + + @Transactional + public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO dto, String idempotencyKey) { + Chat chat = chatService.getChat(senderId, chatId); + + return idempotencyService.execute(senderId, "POST", chatId, idempotencyKey, dto, MessageDTO.class, + () -> doCreate(senderId, chatId, dto, chat)); + } + + private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) { + validateCreate(chatId, dto); + User sender = userService.getReferenceUserById(senderId); + Message message = buildMessage(dto, sender, chat); + try { + message = messageRepository.saveAndFlush(message); + } catch (DataIntegrityViolationException e) { + throw new NotFoundException("Cannot create message: referenced entity is missing"); + } + log.info("Created message id={} in chat={}", message.getId(), chatId); + return messageMapper.toMessageDTO(message); + } + + private void validateCreate(UUID chatId, CreateMessageDTO dto) { + if (dto.getText() == null || dto.getText().isBlank()) { + throw new InvalidRequestException("Empty text"); + } + if (messageRepository.countByChatId(chatId) >= appProperties.maxMessagesPerChat()) { + throw new PayloadTooLargeException("Chat history limit reached"); + } + } + + private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) { + Message message = messageMapper.toMessage(createMessageDTO); + message.setChat(chat); + message.setSender(sender); + return message; + } + + @Transactional(readOnly = true) + public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) { + int size = (limit == null) ? 50 : limit; + chatService.getChatDTO(userId, chatId); + CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId); + List rows = (decoded == null) ? messageRepository.findPageByChat(chatId, Pageable.ofSize(size + 1)) + : messageRepository.findPageByChatAfterCursor(chatId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1)); + return buildPage(rows, size, chatId); + } + + private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) { + if (cursor == null) + return null; + if (cursor.isEmpty()) + throw new InvalidRequestException("Cursor must not be empty"); + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId)) + throw new InvalidRequestException("Cursor from another chat"); + return decoded; + } + + private MessagePageDTO buildPage(List rows, int size, UUID chatId) { + List items = rows.stream() + .limit(size) + .map(messageMapper::toMessageDTO) + .toList(); + + MessagePageDTO page = new MessagePageDTO(); + page.setItems(items); + page.setNextCursor(buildNextCursor(rows, size, chatId)); + return page; + } + + private String buildNextCursor(List rows, int size, UUID chatId) { + if (rows.size() <= size) { + return null; + } + Message last = rows.get(size - 1); + return CursorCodec.encode(chatId, new CursorCodec.PageBoundary( + last.getCreatedAt(), last.getId())); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java new file mode 100644 index 0000000..8573e42 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java @@ -0,0 +1,65 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.cache.CacheHealthTracker; +import ru.mtusi.messenger.repository.SessionRepository; + +@Slf4j +@Service +@RequiredArgsConstructor +public class SessionCacheService { + + public static final String SESSIONS = "sessions"; + + private final SessionRepository sessionRepository; + private final CacheManager cacheManager; + private final CacheHealthTracker cacheHealthTracker; + + @Cacheable(value = SESSIONS, key = "#hex", unless = "#result == null") + @Transactional(readOnly = true) + public SessionService.SessionRecord lookupByHash(String hex) { + byte[] hash = hexToBytes(hex); + return sessionRepository.findByTokenHash(hash) + .filter(s -> s.getRevokedAt() == null) + .map(s -> new SessionService.SessionRecord( + s.getId(), s.getUserId(), s.getExpiresAt())) + .orElse(null); + } + + @CacheEvict(value = SESSIONS, key = "#hex") + public void evict(String hex) { + } + + public void dropCacheIfStale() { + if (!cacheHealthTracker.consumeStale()) { + return; + } + try { + Cache cache = cacheManager.getCache(SESSIONS); + if (cache != null) { + cache.clear(); + } + log.info("Cache '{}' cleared after stale flag", SESSIONS); + } catch (RuntimeException e) { + log.warn("Cache clear failed: {}", e.getMessage()); + cacheHealthTracker.markStale(); + } + } + + private static byte[] hexToBytes(String hex) { + int len = hex.length(); + byte[] out = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + out[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); + } + return out; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionService.java b/src/main/java/ru/mtusi/messenger/service/SessionService.java new file mode 100644 index 0000000..fe6f555 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionService.java @@ -0,0 +1,81 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.SessionProperties; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.mapper.SessionMapper; +import ru.mtusi.messenger.model.Session; +import ru.mtusi.messenger.repository.SessionRepository; +import ru.mtusi.messenger.util.TokenGenerator; +import ru.mtusi.messenger.util.TokenHasher; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Slf4j +@RequiredArgsConstructor +@Service +public class SessionService { + private final TokenGenerator tokenGenerator; + private final TokenHasher tokenHasher; + private final SessionProperties sessionProperties; + private final SessionRepository sessionRepository; + private final SessionMapper sessionMapper; + private final SessionCacheService sessionCacheService; + + @Transactional + public SessionDTO createSession(UserDTO userDTO) { + String token = tokenGenerator.generate(); + Session session = sessionRepository.save(buildSession(userDTO,token)); + return sessionMapper.toSessionDTO(session, token, userDTO); + } + + public SessionRecord requireActive(String token) { + sessionCacheService.dropCacheIfStale(); + String hex = tokenHasher.hash(token); + SessionRecord record = sessionCacheService.lookupByHash(hex); + requireNotExpired(record, hex); + return record; + } + + private void requireNotExpired(SessionRecord record, String hex) { + if (record == null || isExpired(record)) { + sessionCacheService.evict(hex); + throw new UnauthorizedException("Invalid or expired session"); + } + } + + private boolean isExpired(SessionRecord record) { + return record.expiresAt().isBefore(Instant.now()); + } + + @Transactional + public void revoke(UUID sessionId) { + sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict); + } + + private void markRevokedAndEvict(Session session) { + if (session.getRevokedAt() == null) { + session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)); + } + sessionCacheService.evict(tokenHasher.hash(session.getTokenHash())); + } + + private Session buildSession(UserDTO userDTO, String token) { + Session session = new Session(); + session.setUserId(userDTO.getId()); + session.setTokenHash(tokenHasher.sha256(token)); + session.setExpiresAt(Instant.now() + .plus(sessionProperties.ttl()) + .truncatedTo(ChronoUnit.MILLIS)); + return session; + } + + public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {} +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/UserService.java b/src/main/java/ru/mtusi/messenger/service/UserService.java new file mode 100644 index 0000000..9f5e8aa --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/UserService.java @@ -0,0 +1,84 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.CreateUserDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.mapper.UserMapper; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.UserRepository; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Slf4j +public class UserService { + private final PasswordEncoder passwordEncoder; + private final UserMapper userMapper; + private final UserRepository userRepository; + + @Transactional + public Set requireUsers(Collection ids) { + Set uniqueIds = new HashSet<>(ids); + Set users = userRepository.findAllByIdForShare(uniqueIds); + if (users.size() != uniqueIds.size()) { + throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users)); + } + return users; + } + + private Set findMissing(Set requested, Set found) { + Set foundIds = found.stream() + .map(User::getId) + .collect(Collectors.toSet()); + + Set missing = new HashSet<>(requested); + missing.removeAll(foundIds); + return missing; + } + + @Transactional(readOnly = true) + public UserDTO authenticate(String username, String password) { + User user = userRepository.findByUsername(username).orElseThrow(() -> new UnauthorizedException("Bad credentials")); + + if (!passwordEncoder.matches(password, user.getPasswordHash())) { + throw new UnauthorizedException("Bad credentials"); + } + return userMapper.toUserDto(user); + } + + @Transactional + public UserDTO registerUser(CreateUserDTO createUserDTO) { + User user = userMapper.toUser(createUserDTO); + user.setPasswordHash(passwordEncoder.encode(createUserDTO.getPassword())); + try { + return userMapper.toUserDto(userRepository.saveAndFlush(user)); + } catch (DataIntegrityViolationException exception) { + throw new ConflictException("Username already exists"); + } + } + + @Transactional(readOnly = true) + public UserDTO currentUser(UUID userId) { + return userMapper.toUserDto(userRepository.findById(userId).orElseThrow(() -> + new NotFoundException("User not found") + )); + } + + @Transactional + public User getReferenceUserById(UUID senderId) { + return userRepository.getReferenceById(senderId); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/CursorCodec.java b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java new file mode 100644 index 0000000..860d402 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import ru.mtusi.messenger.exception.InvalidRequestException; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +public final class CursorCodec { + + private CursorCodec() {} + + public record PageBoundary(Instant createdAt, UUID id) {} + + public record Cursor(UUID scopeId, PageBoundary boundary) {} + + public static String encode(UUID scopeId, PageBoundary boundary) { + String raw = (scopeId == null ? "" : scopeId.toString()) + + "|" + boundary.createdAt() + "|" + boundary.id(); + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + public static Cursor decode(String cursor) { + try { + String raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8); + String[] p = raw.split("\\|", -1); + UUID scopeId = p[0].isEmpty() ? null : UUID.fromString(p[0]); + PageBoundary boundary = new PageBoundary( + Instant.parse(p[1]), UUID.fromString(p[2])); + return new Cursor(scopeId, boundary); + } catch (Exception e) { + throw new InvalidRequestException("Invalid cursor"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java new file mode 100644 index 0000000..fa000c4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.security.SecureRandom; +import java.util.Base64; + +@Component +public class TokenGenerator { + private final SecureRandom rng = new SecureRandom(); + + public String generate() { + byte[] raw = new byte[32]; + rng.nextBytes(raw); + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenHasher.java b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java new file mode 100644 index 0000000..c63ea7f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +@Component("tokenHasher") +public class TokenHasher { + + public byte[] sha256(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 not available", e); + } + } + + public String hash(String token) { + return toHex(sha256(token)); + } + + public String hash(byte[] bytes) { + return toHex(bytes); + } + + private String toHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java b/src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java new file mode 100644 index 0000000..4d11cb1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/converter/IdempotencyPayloadConverter.java @@ -0,0 +1,29 @@ +package ru.mtusi.messenger.util.converter; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +@Component +@RequiredArgsConstructor +public class IdempotencyPayloadConverter { + + private final JsonMapper jsonMapper; + + public String toJson(Object payload) { + try { + return jsonMapper.writeValueAsString(payload); + } catch (JacksonException e) { // Исключение теперь непроверяемое + throw new IllegalStateException("Cannot serialize idempotency payload", e); + } + } + + public T fromJson(String json, Class type) { + try { + return jsonMapper.readValue(json, type); + } catch (JacksonException e) { + throw new IllegalStateException("Corrupt idempotency payload", e); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java new file mode 100644 index 0000000..6dea47f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java @@ -0,0 +1,67 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.CreateChatDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.service.UserService; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class ChatValidator { + + private final UserService userService; + + public Set validateCreate(UUID caller, CreateChatDTO createChatDTO) { + List memberIds = createChatDTO.getMemberIds(); + String title = createChatDTO.getTitle(); + + requireNotBlank(title, "Title must not be blank"); + requireNonEmpty(memberIds, "member_ids must not be empty"); + requireNoDuplicates(memberIds, "member_ids contains duplicates"); + requireContains(memberIds, caller, "Вызывающий должен быть участником"); + + return requireAllUsersExist(memberIds); + } + + private void requireNotBlank(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNonEmpty(List ids, String message) { + if (ids == null || ids.isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNoDuplicates(List ids, String message) { + Set unique = new HashSet<>(ids); + if (unique.size() != ids.size()) { + throw new InvalidRequestException(message); + } + } + + private void requireContains(List ids, UUID value, String message) { + if (!ids.contains(value)) { + throw new InvalidRequestException(message); + } + } + + private Set requireAllUsersExist(List ids) { + try { + return userService.requireUsers(ids); + } catch (NotFoundException e) { + throw new InvalidRequestException(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java b/src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java new file mode 100644 index 0000000..e193bd9 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/IdempotencyValidator.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.config.properties.IdempotencyProperties; +import ru.mtusi.messenger.exception.InvalidRequestException; + +import java.util.regex.Pattern; + +@Component +@RequiredArgsConstructor +public class IdempotencyValidator { + + private final IdempotencyProperties properties; + + public void validateKey(String key) { + requireNotBlank(key); + requireMaxLength(key); + requirePattern(key); + } + + private void requireNotBlank(String key) { + if (key == null || key.isEmpty()) { + throw new InvalidRequestException("Idempotency-Key header is required"); + } + } + + private void requireMaxLength(String key) { + if (key.length() > properties.keyMaxLength()) { + throw new InvalidRequestException("Idempotency-Key is too long"); + } + } + + private void requirePattern(String key) { + if (!Pattern.matches(properties.keyPattern(), key)) { + throw new InvalidRequestException("Idempotency-Key contains invalid characters"); + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..2c90e58 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,89 @@ +spring: + application: + name: messenger-lab2 + config: + import: "optional:configtree:/run/secrets/" + lifecycle: + timeout-per-shutdown-phase: 30s + jackson: + default-property-inclusion: non_null + datasource: + driver-class-name: org.postgresql.Driver + url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${SPRING_DATASOURCE_USERNAME:messenger} + password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only} + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 2000 + validation-timeout: 1000 + idle-timeout: 60000 + max-lifetime: 1800000 + jpa: + hibernate: + ddl-auto: validate + open-in-view: false + properties: + hibernate: + jdbc: + time_zone: UTC + dialect: org.hibernate.dialect.PostgreSQLDialect + flyway: + enabled: true + locations: classpath:db/migration + data: + redis: + host: ${SPRING_DATA_REDIS_HOST:localhost} + port: ${SPRING_DATA_REDIS_PORT:6379} + cache: + type: redis + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + +management: + endpoints: + web: + exposure: + include: health,metrics,caches + endpoint: + health: + probes: + enabled: true + show-details: always + caches: + enabled: true + + +app: + idempotency: + key-max-length: ${IDEMPOTENCY_KEY_MAX_LENGTH:128} + key-pattern: '${IDEMPOTENCY_KEY_PATTERN:^[A-Za-z0-9._:-]+$}' + retention-hours: ${IDEMPOTENCY_RETENTION_HOURS:24} + instance: + id: ${INSTANCE_ID:${HOSTNAME:${random.uuid}}} + limits: + max-messages-per-chat: ${MAX_MESSAGES_PER_CHAT:10000} + rate: + rate-per-minute: ${RATE_PER_MINUTE:600} + retry-after-seconds: ${RETRY_AFTER_SECONDS:60} + session: + ttl: ${SESSION_TTL_SECONDS:400}s + redis: + host: ${SPRING_DATA_REDIS_HOST:localhost} + port: ${SPRING_DATA_REDIS_PORT:6379} + command-timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:500ms} + shutdown-timeout: ${REDIS_SHUTDOWN_TIMEOUT:100ms} + keep-alive-idle: ${REDIS_KEEP_ALIVE_IDLE:30s} + keep-alive-interval: ${REDIS_KEEP_ALIVE_INTERVAL:10s} + tcp-user-timeout: ${REDIS_TCP_USER_TIMEOUT:10s} + +logging: + pattern: + console: "%d{ISO8601} %-5level [%X{requestId}] %logger{20} - %msg%n" + level: + org.springframework.cache: TRACE + org.springframework.cache.interceptor: TRACE \ No newline at end of file diff --git a/src/main/resources/db/migration/V1__init.sql b/src/main/resources/db/migration/V1__init.sql new file mode 100644 index 0000000..3069a29 --- /dev/null +++ b/src/main/resources/db/migration/V1__init.sql @@ -0,0 +1,94 @@ +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- ---------- users ---------- +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + username VARCHAR(32) NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_users_username UNIQUE (username), + CONSTRAINT ck_users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT ck_users_display_name_not_blank + CHECK (length(btrim(display_name)) > 0) +); + +-- ---------- chats ---------- +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_chats_title_not_blank CHECK (length(btrim(title)) > 0) +); + +-- ---------- chat_members ---------- +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +-- ---------- messages ---------- +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text VARCHAR(4000) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_messages_text_not_blank CHECK (length(btrim(text)) > 0) +); + +-- ---------- sessions ---------- +CREATE TABLE sessions ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + CONSTRAINT uq_sessions_token_hash UNIQUE (token_hash), + CONSTRAINT ck_sessions_expiry CHECK (expires_at > created_at), + CONSTRAINT ck_sessions_token_len CHECK (octet_length(token_hash) = 32) +); + +-- ---------- idempotency_keys (lab3) ---------- +CREATE TABLE idempotency_keys ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method VARCHAR(16) NOT NULL, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + idempotency_key VARCHAR(128) NOT NULL, + request_hash VARCHAR(64) NOT NULL, + status_code SMALLINT, + response_body JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT uq_idempotency_scope UNIQUE (user_id, method, chat_id, idempotency_key), + CONSTRAINT ck_idem_key_format CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT ck_idem_status_body_paired CHECK ((status_code IS NULL) = (response_body IS NULL)) +); + +-- Keyset pagination: ORDER BY created_at ASC, id ASC (JPQL uses ASC) +CREATE INDEX idx_messages_chat_created_asc_id + ON messages (chat_id, created_at ASC, id ASC); + +-- "My chats" list (listChats) +CREATE INDEX idx_chat_members_user + ON chat_members (user_id); + +-- For chats list pagination: ORDER BY created_at ASC, id ASC +CREATE INDEX idx_chats_created_asc_id + ON chats (created_at ASC, id ASC); + +-- Active sessions per user (logout-all / audit) +CREATE INDEX idx_sessions_user_active + ON sessions (user_id) + WHERE revoked_at IS NULL; + +-- Cleanup of expired sessions +CREATE INDEX idx_sessions_expires_active + ON sessions (expires_at) + WHERE revoked_at IS NULL; + +CREATE INDEX idx_idempotency_created + ON idempotency_keys (created_at); \ No newline at end of file diff --git a/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java new file mode 100644 index 0000000..2da5d51 --- /dev/null +++ b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java @@ -0,0 +1,13 @@ +package ru.mtusi.messenger; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MessengerLab1ApplicationTests { + + @Test + void contextLoads() { + } + +}