From b95197a6fcd009e9b5b12f195019ce17adebb034 Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Tue, 6 Oct 2026 14:32:54 +0300 Subject: [PATCH 1/7] for 3 --- .gitattributes | 4 + .gitignore | 142 ++++++++-- Dockerfile | 20 ++ build.gradle | 63 +++++ docker-compose.yaml | 68 +++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 47505 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++++++++++++++++++ gradlew.bat | 82 ++++++ scripts/restart.sh | 7 + settings.gradle | 1 + .../messenger/MessengerLab1Application.java | 16 ++ .../mtusi/messenger/config/AppProperties.java | 8 + .../mtusi/messenger/config/OpenApiConfig.java | 20 ++ .../messenger/config/RateLimitConfig.java | 24 ++ .../messenger/config/RateLimitProperties.java | 6 + .../messenger/config/SecurityConfig.java | 74 ++++++ .../messenger/config/SessionProperties.java | 10 + .../mtusi/messenger/controller/AuthApi.java | 118 +++++++++ .../messenger/controller/AuthController.java | 28 ++ .../messenger/controller/ChatController.java | 35 +++ .../mtusi/messenger/controller/ChatsApi.java | 215 +++++++++++++++ .../mtusi/messenger/controller/HealthApi.java | 89 +++++++ .../controller/HealthController.java | 26 ++ .../controller/MessageController.java | 29 ++ .../messenger/controller/MessagesApi.java | 135 ++++++++++ .../messenger/controller/UserController.java | 26 ++ .../mtusi/messenger/controller/UsersApi.java | 136 ++++++++++ .../java/ru/mtusi/messenger/dto/ChatDTO.java | 126 +++++++++ .../ru/mtusi/messenger/dto/ChatPageDTO.java | 121 +++++++++ .../mtusi/messenger/dto/CreateMessageDTO.java | 38 +++ .../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 | 187 +++++++++++++ .../mtusi/messenger/dto/MessagePageDTO.java | 122 +++++++++ .../ru/mtusi/messenger/dto/SessionDTO.java | 198 ++++++++++++++ .../java/ru/mtusi/messenger/dto/UserDTO.java | 156 +++++++++++ .../messenger/exception/ApiErrorFactory.java | 71 +++++ .../exception/ConflictException.java | 5 + .../exception/GlobalExceptionHandler.java | 119 +++++++++ .../exception/InvalidRequestException.java | 5 + .../exception/NotFoundException.java | 5 + .../exception/PayloadTooLargeException.java | 5 + .../exception/RateLimitedException.java | 7 + .../exception/UnauthorizedException.java | 5 + .../messenger/filter/RateLimitFilter.java | 50 ++++ .../messenger/filter/RequestIdFilter.java | 35 +++ .../ru/mtusi/messenger/mapper/ChatMapper.java | 34 +++ .../mtusi/messenger/mapper/MessageMapper.java | 20 ++ .../ru/mtusi/messenger/mapper/UserMapper.java | 20 ++ .../java/ru/mtusi/messenger/model/Chat.java | 52 ++++ .../ru/mtusi/messenger/model/Message.java | 39 +++ .../ru/mtusi/messenger/model/Session.java | 41 +++ .../java/ru/mtusi/messenger/model/User.java | 47 ++++ .../messenger/repository/ChatRepository.java | 30 +++ .../repository/MessageRepository.java | 29 ++ .../repository/SessionRepository.java | 12 + .../messenger/repository/UserRepository.java | 23 ++ .../security/ApiAuthenticationEntryPoint.java | 32 +++ .../messenger/security/BasicCredentials.java | 28 ++ .../security/SessionAuthenticationFilter.java | 39 +++ .../SessionAuthenticationProvider.java | 33 +++ .../security/SessionAuthenticationToken.java | 34 +++ .../messenger/security/SessionPrincipal.java | 6 + .../mtusi/messenger/service/AuthService.java | 32 +++ .../mtusi/messenger/service/ChatService.java | 117 +++++++++ .../messenger/service/MessageService.java | 120 +++++++++ .../messenger/service/SessionService.java | 80 ++++++ .../mtusi/messenger/service/UserService.java | 81 ++++++ .../ru/mtusi/messenger/util/CursorCodec.java | 37 +++ .../mtusi/messenger/util/TokenGenerator.java | 17 ++ src/main/resources/application.yaml | 57 ++++ src/main/resources/db/migration/V1__init.sql | 79 ++++++ .../MessengerLab1ApplicationTests.java | 13 + 75 files changed, 4403 insertions(+), 28 deletions(-) create mode 100644 .gitattributes create mode 100644 Dockerfile create mode 100644 build.gradle create mode 100644 docker-compose.yaml 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 100755 scripts/restart.sh 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/config/AppProperties.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/RateLimitProperties.java create mode 100644 src/main/java/ru/mtusi/messenger/config/SecurityConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/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/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/CreateMessageDTO.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/GlobalExceptionHandler.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/UnauthorizedException.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/UserMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/model/Chat.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/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/MessageService.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/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/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dfc97d67 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary +scripts/*.sh text eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore index b5a71896..5cb289f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,118 @@ -# Local/private state +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + + +# Created by https://www.gitignore.io/api/git,java,maven,eclipse,windows + +### Git ### +# Created by git for backups. To disable backups in Git: +# $ git config --global mergetool.keepBackup false +*.orig + +# Created by git when using merge tools for conflicts +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### IntelliJ IDEA ### +SpringTech/.idea +*.iws +*.iml +*.ipr + +### VS Code ### +.vscode/ + +### Some additional ignores (sort later) +*.DS_Store +*.sw? +.#* +*# +*~ +.classpath +.project +.settings +bin +/build/* +target +dependency-reduced-pom.xml +*.sublime-* +/scratch +.gradle +README.html +*.iml +.idea +.exercism +# Environment .env .env.* !.env.example -secrets/ -certs/private/ -*.key -*.p12 -*.pfx -*.jks -*.pem -*.tfstate* -volumes/ -data/ -backups/ -# Runtime/build artifacts -.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 +!gradle/wrapper/gradle-wrapper.jar +secrets/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..e9438fbb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +FROM eclipse-temurin:21-jdk-jammy AS builder +WORKDIR /build +COPY gradle gradle +COPY gradlew settings.gradle build.gradle ./ +RUN ./gradlew dependencies --no-daemon +COPY contracts contracts +COPY src src +RUN ./gradlew bootJar -x test --no-daemon + +FROM eclipse-temurin:21-jre-alpine AS runner +WORKDIR /app +RUN addgroup -S spring && adduser -S spring -G 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 00000000..5424af91 --- /dev/null +++ b/build.gradle @@ -0,0 +1,63 @@ +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 'com.fasterxml.jackson.core:jackson-databind' + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' + + + 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.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 00000000..6f4736f9 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,68 @@ +services: + db: + image: postgres:16-alpine + container_name: messenger-db + restart: unless-stopped + environment: + POSTGRES_DB_FILE: /run/secrets/postgres_db + POSTGRES_USER_FILE: /run/secrets/postgres_user + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + secrets: + - postgres_db + - postgres_user + - postgres_password + networks: + - messenger-net + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $$(cat /run/secrets/postgres_user) -d $$(cat /run/secrets/postgres_db)"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s + + api: + build: + context: . + dockerfile: Dockerfile + container_name: messenger-api + restart: unless-stopped + depends_on: + db: + condition: service_healthy + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user + SPRING_DATASOURCE_PASSWORD_FILE: /run/secrets/postgres_password + SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400} + SESSION_STORE: ${SESSION_STORE:-postgres} + ports: + - "127.0.0.1:8080:8080" + secrets: + - postgres_user + - postgres_password + networks: + - messenger-net + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/health/ready | grep -q '\"status\":\"ok\"'"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 40s + +volumes: + pgdata: + +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..eddabd2eef8d94a5437d6168ff9c87a78ff725b3 GIT binary patch literal 47505 zcma%jV|XRZx@BzJPRF)w+qP|W2RrDP9UC1d9oxo^)3I%LIQh<*=g!Qz_k45q^VI&e z|5VkgwQ8;Rt*tBv4uJsz0|NsB0z&#Z{?7*m1QtX=LS2MGMp2SUUPeqpQB6Wa9TEie zub-^z>bb3QVg*ju^jKS3o#9H#w4Yxz1*n>pYH+2nC3dC@ic(OUh@sI7>n^@O3t+EN zk19TR2&69-M23X8{h9JYx|8)kwwf7ttr>teD4+VN#nkbK$s(IG`^odY38j0~G5LYI zE8yj!-3t3WJpbc*GP8f1Ijv!GZFxNt(Cq4DxZU@%dVh&ur@bEGnl2N^*QNXDgt%%uIzL8-|f9*0a_P$gWq1W= zyYFqsd}OSk24kb~1dN}B%z?^{HGmwKoogz&O?>^nlNT;9zKwXe(^*#}CA6|3JU~$) z84gW6*^!J(I2cJ6Fex`F@*8Z;s#mTo^y2AJ6hSf>Ei3lYhvt>4{wrqH*`8wlt+NqV zs$Y#ZDUzSWF!beISEBi0Dvx#amw4A=5p>tM)l(wMg*GU=hp|-Z=aZM_pw^OegdgFE z#1Jtd_&p~_;Lb@JjM5MZdJErBWf7~hq^IxX89(}?*<2v)uDSTyr#g{7fM4R;@KjPU zef+&aPhcAskT5|z_09<(`3G^SKwJ0e=Q(TjU}<2E7jh(ZoiwT{!}jl%GU(rNo2?a! zx2+TFX}Pt%EZ7ohNMI$bpk|IV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`&NT@+g{&n#qgJY|DYA+&&U3K`@J874c+878h>wm z{Pz}yKkIy7^?cXN@0;nH{+Z4{OxE`W!*|8g-|U6^F9rTvDfQ1s{(UX$k7vQvYMdv{Mz{+ '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..a51ec4f5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..2bb40f48 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +# Restart API and all state stores used in lab2 (Postgres). +# Preserve persistent volumes and data: never `down -v`, never flush or re-seed. +# Exit 0 only after issuing the restart; the test waits for API readiness separately. + +docker compose --env-file .env restart api db \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..650573b3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'messenger-lab1' diff --git a/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java new file mode 100644 index 00000000..54938665 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration; + +@ConfigurationPropertiesScan +@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class) +public class MessengerLab1Application { + + public static void main(String[] args) { + SpringApplication.run(MessengerLab1Application.class, args); + } + +} diff --git a/src/main/java/ru/mtusi/messenger/config/AppProperties.java b/src/main/java/ru/mtusi/messenger/config/AppProperties.java new file mode 100644 index 00000000..e15176cb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/AppProperties.java @@ -0,0 +1,8 @@ +package ru.mtusi.messenger.config; + +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/OpenApiConfig.java b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java new file mode 100644 index 00000000..06edae6a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +public class OpenApiConfig { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java new file mode 100644 index 00000000..874549df --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java @@ -0,0 +1,24 @@ +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 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/RateLimitProperties.java b/src/main/java/ru/mtusi/messenger/config/RateLimitProperties.java new file mode 100644 index 00000000..e8c1b8ee --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RateLimitProperties.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.config; + +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/SecurityConfig.java b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java new file mode 100644 index 00000000..d61091fb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java @@ -0,0 +1,74 @@ +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.bcrypt.BCryptPasswordEncoder; +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 new BCryptPasswordEncoder(); + } + + @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() + .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/SessionProperties.java b/src/main/java/ru/mtusi/messenger/config/SessionProperties.java new file mode 100644 index 00000000..b4ac8cd2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/SessionProperties.java @@ -0,0 +1,10 @@ +package ru.mtusi.messenger.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.session") +public record SessionProperties( + Duration ttl +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthApi.java b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java new file mode 100644 index 00000000..9d0626bf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java @@ -0,0 +1,118 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import ru.mtusi.messenger.dto.SessionDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Auth", description = "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface AuthApi { + + /** + * POST /api/v1/auth/sessions : Вход: Basic username:password; выдаёт сессию + * + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createSession", + summary = "Вход: Basic username:password; выдаёт сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = SessionDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "basicAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/auth/sessions", + produces = { "application/json" } + ) + + ResponseEntity createSession( + + ); + + + /** + * DELETE /api/v1/auth/sessions/current : Отозвать текущую сессию + * + * @return Успех (status code 204) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "revokeSession", + summary = "Отозвать текущую сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "204", description = "Успех"), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/api/v1/auth/sessions/current", + produces = { "application/json" } + ) + + ResponseEntity revokeSession( + + ); + +} diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthController.java b/src/main/java/ru/mtusi/messenger/controller/AuthController.java new file mode 100644 index 00000000..5cb66068 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthController.java @@ -0,0 +1,28 @@ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.service.AuthService; + +@RestController +@RequiredArgsConstructor +public class AuthController implements AuthApi { + private final AuthService authService; + private final HttpServletRequest request; + + @Override + public ResponseEntity createSession() { + return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION))); + } + + @Override + public ResponseEntity revokeSession() { + authService.logout(); + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatController.java b/src/main/java/ru/mtusi/messenger/controller/ChatController.java new file mode 100644 index 00000000..2344b4b1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatController.java @@ -0,0 +1,35 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.ChatService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class ChatController implements ChatsApi { + private final ChatService chatService; + + @Override + public ResponseEntity createChat(ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(chatService.createChat(principal.userId(), chatDTO)); + } + + @Override + public ResponseEntity getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.getChat(principal.userId(), chatId)); + } + + @Override + public ResponseEntity listChats(Integer limit, String cursor , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.listChats(principal.userId(), limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java new file mode 100644 index 00000000..57f81d14 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java @@ -0,0 +1,215 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import java.util.UUID; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Chats", description = "Управление чатами и доступ к чатам текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface ChatsApi { + + /** + * POST /api/v1/chats : Создать чат; вызывающий должен входить в member_ids + * + * @param chatDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createChat", + summary = "Создать чат; вызывающий должен входить в member_ids", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/chats", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity createChat( + @Parameter(name = "CreateChatDTO", description = "", required = true) @Valid @RequestBody ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats/{chat_id} : Получить доступный чат + * + * @param chatId (required) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "getChat", + summary = "Получить доступный чат", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}", + produces = { "application/json" } + ) + + ResponseEntity getChat( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) @PathVariable("chat_id") UUID chatId, + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats : Чаты текущего пользователя + * + * @param limit (optional, default to 50) + * @param cursor (optional) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "listChats", + summary = "Чаты текущего пользователя", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatPageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats", + produces = { "application/json" } + ) + + ResponseEntity listChats( + @Min(1) @Max(100) @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthApi.java b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java new file mode 100644 index 00000000..015bd501 --- /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( + + ); + +} diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthController.java b/src/main/java/ru/mtusi/messenger/controller/HealthController.java new file mode 100644 index 00000000..6652d0bd --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthController.java @@ -0,0 +1,26 @@ +package ru.mtusi.messenger.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.HealthDTO; + +@RestController +public class HealthController implements HealthApi { + private static final HealthDTO OK = createOk(); + + @Override + public ResponseEntity liveness() { + return ResponseEntity.ok(OK); + } + + @Override + public ResponseEntity readiness() { + return ResponseEntity.ok(OK); + } + + private static HealthDTO createOk() { + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } +} diff --git a/src/main/java/ru/mtusi/messenger/controller/MessageController.java b/src/main/java/ru/mtusi/messenger/controller/MessageController.java new file mode 100644 index 00000000..26dc199a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessageController.java @@ -0,0 +1,29 @@ +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.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, MessageDTO messageDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, messageDTO)); + } + + @Override + public ResponseEntity listMessages(UUID chatId, Integer limit, String cursor, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(messageService.listMessages(principal.userId(), chatId, limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java new file mode 100644 index 00000000..618b8bd6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java @@ -0,0 +1,135 @@ +/** + * 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.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 = "MessageDTO", description = "", required = true) + @Valid @RequestBody MessageDTO messageDTO, + @AuthenticationPrincipal SessionPrincipal principal + ); + + @Operation( + operationId = "listMessages", + summary = "Сообщения по (created_at, id) по возрастанию", + tags = { "Messages" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = MessagePageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}/messages", + produces = { "application/json" } + ) + ResponseEntity listMessages( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Min(1) @Max(100) + @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) + @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/UserController.java b/src/main/java/ru/mtusi/messenger/controller/UserController.java new file mode 100644 index 00000000..bf4a5907 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UserController.java @@ -0,0 +1,26 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.UserService; + +@RestController +@RequiredArgsConstructor +public class UserController implements UsersApi { + private final UserService userService; + + @Override + public ResponseEntity currentUser(@AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(userService.currentUser(principal.userId())); + } + + @Override + public ResponseEntity registerUser(UserDTO userDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(userDTO)); + } +} diff --git a/src/main/java/ru/mtusi/messenger/controller/UsersApi.java b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java new file mode 100644 index 00000000..7e97abac --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java @@ -0,0 +1,136 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.UserDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Users", description = "Регистрация пользователей и доступ к профилю текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface UsersApi { + + /** + * GET /api/v1/users/me : Текущий пользователь + * + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "currentUser", + summary = "Текущий пользователь", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/users/me", + produces = { "application/json" } + ) + + ResponseEntity currentUser( + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * POST /api/v1/users : Создать пользователя + * + * @param userDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "registerUser", + summary = "Создать пользователя", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/users", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity registerUser( + @Parameter(name = "UserDTO", description = "", required = true) @Valid @RequestBody UserDTO userDTO + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java new file mode 100644 index 00000000..575dfd06 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -0,0 +1,126 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import org.hibernate.validator.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + + +import java.util.*; +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class ChatDTO { + + private String title; + + @Valid + private Set memberIds = new LinkedHashSet<>(); + + public ChatDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ChatDTO(String title, Set memberIds) { + this.title = title; + this.memberIds = memberIds; + } + + public ChatDTO title(String title) { + this.title = title; + return this; + } + + /** + * Get title + * @return title + */ + @NotNull @Size(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(Set memberIds) { + this.memberIds = memberIds; + return this; + } + + public ChatDTO addMemberIdsItem(UUID memberIdsItem) { + if (this.memberIds == null) { + this.memberIds = new LinkedHashSet<>(); + } + this.memberIds.add(memberIdsItem); + return this; + } + + /** + * Get memberIds + * @return memberIds + */ + @NotNull @Valid @Size(min = 1, max = 100) + @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("member_ids") + public Set getMemberIds() { + return memberIds; + } + + @JsonDeserialize(as = LinkedHashSet.class) + public void setMemberIds(Set memberIds) { + this.memberIds = memberIds; + } + + @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.title, createChat.title) && + Objects.equals(this.memberIds, createChat.memberIds); + } + + @Override + public int hashCode() { + return Objects.hash(title, memberIds); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateChat {\n"); + sb.append(" title: ").append(toIndentedString(title)).append("\n"); + sb.append(" memberIds: ").append(toIndentedString(memberIds)).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 "); + } +} + diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java new file mode 100644 index 00000000..9a67d08d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java @@ -0,0 +1,121 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +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 + */ + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChatPageDTO chatPageDTO = (ChatPageDTO) o; + return Objects.equals(this.items, chatPageDTO.items) && + Objects.equals(this.nextCursor, chatPageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ChatPageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java new file mode 100644 index 00000000..c601455d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java @@ -0,0 +1,38 @@ +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 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 @Size(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { return text; } + + public void setText(String text) { this.text = text; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CreateMessageDTO d)) return false; + return Objects.equals(text, d.text); + } + + @Override + public int hashCode() { return Objects.hash(text); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java new file mode 100644 index 00000000..65c09ca9 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java @@ -0,0 +1,87 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorDTO + */ + +public class ErrorDTO { + + private ErrorErrorDTO error; + + public ErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorDTO(ErrorErrorDTO error) { + this.error = error; + } + + public ErrorDTO error(ErrorErrorDTO error) { + this.error = error; + return this; + } + + /** + * Get error + * @return error + */ + @NotNull @Valid + @Schema(name = "error", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("error") + public ErrorErrorDTO getError() { + return error; + } + + public void setError(ErrorErrorDTO error) { + this.error = error; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorDTO errorDTO = (ErrorDTO) o; + return Objects.equals(this.error, errorDTO.error); + } + + @Override + public int hashCode() { + return Objects.hash(error); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorDTO {\n"); + sb.append(" error: ").append(toIndentedString(error)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java new file mode 100644 index 00000000..6804918b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java @@ -0,0 +1,178 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorErrorDTO + */ + +public class ErrorErrorDTO { + + /** + * Gets or Sets code + */ + public enum CodeEnum { + INVALID_REQUEST("invalid_request"), + UNAUTHORIZED("unauthorized"), + NOT_FOUND("not_found"), + CONFLICT("conflict"), + PAYLOAD_TOO_LARGE("payload_too_large"), + UNSUPPORTED_MEDIA_TYPE("unsupported_media_type"), + RATE_LIMITED("rate_limited"), + UNAVAILABLE("unavailable"), + INTERNAL_ERROR("internal_error"); + + private String value; + + CodeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static CodeEnum fromValue(String value) { + for (CodeEnum b : CodeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private CodeEnum code; + + private String message; + + private String requestId; + + public ErrorErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorErrorDTO(CodeEnum code, String message, String requestId) { + this.code = code; + this.message = message; + this.requestId = requestId; + } + + public ErrorErrorDTO code(CodeEnum code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @NotNull + @Schema(name = "code", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("code") + public CodeEnum getCode() { + return code; + } + + public void setCode(CodeEnum code) { + this.code = code; + } + + public ErrorErrorDTO message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @NotNull @Size(min = 1) + @Schema(name = "message", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("message") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public ErrorErrorDTO requestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Get requestId + * @return requestId + */ + @NotNull @Size(min = 1) + @Schema(name = "request_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("request_id") + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorErrorDTO errorErrorDTO = (ErrorErrorDTO) o; + return Objects.equals(this.code, errorErrorDTO.code) && + Objects.equals(this.message, errorErrorDTO.message) && + Objects.equals(this.requestId, errorErrorDTO.requestId); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, requestId); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorErrorDTO {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" requestId: ").append(toIndentedString(requestId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java new file mode 100644 index 00000000..bd428131 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java @@ -0,0 +1,120 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * HealthDTO + */ + +public class HealthDTO { + + /** + * Gets or Sets status + */ + public enum StatusEnum { + OK("ok"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private StatusEnum status; + + public HealthDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public HealthDTO(StatusEnum status) { + this.status = status; + } + + public HealthDTO status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @NotNull + @Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HealthDTO healthDTO = (HealthDTO) o; + return Objects.equals(this.status, healthDTO.status); + } + + @Override + public int hashCode() { + return Objects.hash(status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthDTO {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java new file mode 100644 index 00000000..10f915e2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java @@ -0,0 +1,187 @@ +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 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 @Size(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public MessageDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @NotNull @Valid + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessageDTO messageDTO = (MessageDTO) o; + return Objects.equals(this.id, messageDTO.id) && + Objects.equals(this.chatId, messageDTO.chatId) && + Objects.equals(this.senderId, messageDTO.senderId) && + Objects.equals(this.text, messageDTO.text) && + Objects.equals(this.createdAt, messageDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, chatId, senderId, text, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessageDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n"); + sb.append(" senderId: ").append(toIndentedString(senderId)).append("\n"); + sb.append(" text: ").append(toIndentedString(text)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java new file mode 100644 index 00000000..6b6cec9c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java @@ -0,0 +1,122 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +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 + */ + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessagePageDTO messagePageDTO = (MessagePageDTO) o; + return Objects.equals(this.items, messagePageDTO.items) && + Objects.equals(this.nextCursor, messagePageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessagePageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java new file mode 100644 index 00000000..bc1f0772 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java @@ -0,0 +1,198 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.Instant; +import ru.mtusi.messenger.dto.UserDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * SessionDTO + */ + +public class SessionDTO { + + private String token; + + /** + * Gets or Sets tokenType + */ + public enum TokenTypeEnum { + BEARER("Bearer"); + + private String value; + + TokenTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TokenTypeEnum fromValue(String value) { + for (TokenTypeEnum b : TokenTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private TokenTypeEnum tokenType; + + private Instant expiresAt; + + private UserDTO user; + + public SessionDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public SessionDTO(String token, TokenTypeEnum tokenType, Instant expiresAt, UserDTO user) { + this.token = token; + this.tokenType = tokenType; + this.expiresAt = expiresAt; + this.user = user; + } + + public SessionDTO token(String token) { + this.token = token; + return this; + } + + /** + * Get token + * @return token + */ + @NotNull @Size(min = 32) + @Schema(name = "token", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token") + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public SessionDTO tokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + return this; + } + + /** + * Get tokenType + * @return tokenType + */ + @NotNull + @Schema(name = "token_type", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token_type") + public TokenTypeEnum getTokenType() { + return tokenType; + } + + public void setTokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + } + + public SessionDTO expiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + /** + * Get expiresAt + * @return expiresAt + */ + @NotNull @Valid + @Schema(name = "expires_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("expires_at") + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public SessionDTO user(UserDTO user) { + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @NotNull @Valid + @Schema(name = "user", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("user") + public UserDTO getUser() { + return user; + } + + public void setUser(UserDTO user) { + this.user = user; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SessionDTO sessionDTO = (SessionDTO) o; + return Objects.equals(this.token, sessionDTO.token) && + Objects.equals(this.tokenType, sessionDTO.tokenType) && + Objects.equals(this.expiresAt, sessionDTO.expiresAt) && + Objects.equals(this.user, sessionDTO.user); + } + + @Override + public int hashCode() { + return Objects.hash(token, tokenType, expiresAt, user); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SessionDTO {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n"); + sb.append(" expiresAt: ").append(toIndentedString(expiresAt)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java new file mode 100644 index 00000000..9a7e7eb5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -0,0 +1,156 @@ +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 java.util.*; + +/** + * UserDTO + */ + +public class UserDTO { + + private UUID id; + + private String username; + + private String displayName; + + private String password; + + public UserDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public UserDTO(String username, String displayName, String password) { + this.username = username; + this.displayName = displayName; + this.password = password; + } + + public UserDTO username(String username) { + this.username = username; + return this; + } + + @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserDTO id(UUID id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + */ + @NotNull @Pattern(regexp = "^[a-z0-9_]{3,32}$") + @Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("username") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public UserDTO displayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get displayName + * @return displayName + */ + @NotNull @Size(min = 1, max = 100) + @Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("display_name") + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public UserDTO password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + @NotNull @Size(min = 12, max = 128) + @Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("password") + 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; + } + UserDTO userDTO = (UserDTO) o; + return Objects.equals(this.id, userDTO.id) && + Objects.equals(this.username, userDTO.username) && + Objects.equals(this.displayName, userDTO.displayName) && + Objects.equals(this.password, userDTO.password); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, displayName, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java new file mode 100644 index 00000000..7a8bb2e8 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java @@ -0,0 +1,71 @@ +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()) { + return mdc; + } + return UUID.randomUUID().toString(); + } + + private String normalizeMessage(String message) { + return (message == null || message.isBlank()) ? DEFAULT_MESSAGE : message; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ConflictException.java b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java new file mode 100644 index 00000000..aa0a2bff --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class ConflictException extends RuntimeException { + public ConflictException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java b/src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java new file mode 100644 index 00000000..53cef055 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java @@ -0,0 +1,119 @@ +package ru.mtusi.messenger.exception; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import ru.mtusi.messenger.config.RateLimitProperties; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.ErrorErrorDTO; + +@RestControllerAdvice +@RequiredArgsConstructor +public class GlobalExceptionHandler { + private final RateLimitProperties limitProperties; + private final ApiErrorFactory errors; + + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity invalidRequest(InvalidRequestException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity unauthorized(UnauthorizedException e, HttpServletRequest req) { + String scheme = req.getRequestURI().equals("/api/v1/auth/sessions") + ? "Basic" : "Bearer"; + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .header("WWW-Authenticate", scheme + " realm=\"messenger\"") + .body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req)); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity notFound(NotFoundException e, HttpServletRequest req) { + return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity conflict(ConflictException e, HttpServletRequest req) { + return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req); + } + + @ExceptionHandler(PayloadTooLargeException.class) + public ResponseEntity payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) { + return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity unreadable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req); + } + + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity missingParam(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req); + } + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity typeMismatch(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseEntity mediaType(Exception e, HttpServletRequest req) { + return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, + "Unsupported media type", req); + } + + @ExceptionHandler(HandlerMethodValidationException.class) + public ResponseEntity methodValidation(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseEntity methodNotAllowed(Exception e, HttpServletRequest req) { + return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Method not allowed", req); + } + + @ExceptionHandler(RateLimitedException.class) + public ResponseEntity rateLimited(RateLimitedException e, HttpServletRequest req) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())) + .body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req)); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity constraint(ConstraintViolationException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity fallback(Exception e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Internal error", req); + } + + 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/exception/InvalidRequestException.java b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java new file mode 100644 index 00000000..a4d7792a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class InvalidRequestException extends RuntimeException { + public InvalidRequestException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java new file mode 100644 index 00000000..6055db37 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java new file mode 100644 index 00000000..2493a9eb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class PayloadTooLargeException extends RuntimeException { + public PayloadTooLargeException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java new file mode 100644 index 00000000..3c1ab32b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class RateLimitedException extends RuntimeException { + public RateLimitedException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java new file mode 100644 index 00000000..a086273a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java new file mode 100644 index 00000000..3eb8d825 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java @@ -0,0 +1,50 @@ +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.AppProperties; +import ru.mtusi.messenger.config.RateLimitProperties; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@Order(2) +@RequiredArgsConstructor +public class RateLimitFilter extends OncePerRequestFilter { + private final RateLimitProperties limitProperties; + private final Bucket bucket; + private final ApiErrorFactory errors; + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + if (!req.getRequestURI().startsWith("/api/")) { + chain.doFilter(req, res); + return; + } + + if (bucket.tryConsume(1)) { + chain.doFilter(req, res); + return; + } + + res.setHeader("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())); + errors.writeError( + res, + req, + HttpStatus.TOO_MANY_REQUESTS, + null, + ErrorErrorDTO.CodeEnum.RATE_LIMITED, + "Rate limit exceeded. Try again later."); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java new file mode 100644 index 00000000..54668db8 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java @@ -0,0 +1,35 @@ +package ru.mtusi.messenger.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(1) +public class RequestIdFilter extends OncePerRequestFilter { + + public static final String INSTANCE_ID = UUID.randomUUID().toString(); + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + String rid = UUID.randomUUID().toString(); + res.setHeader("X-Request-Id", rid); + res.setHeader("X-Instance-Id", INSTANCE_ID); + req.setAttribute("requestId", rid); + MDC.put("requestId", rid); + try { + chain.doFilter(req, res); + } finally { + MDC.clear(); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java new file mode 100644 index 00000000..a36668cf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java @@ -0,0 +1,34 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; + +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +@Mapper(componentModel = "spring") +public interface ChatMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "members", ignore = true) // ← заполнит ChatService + @Mapping(target = "messages", ignore = true) + Chat toChat(ChatDTO dto); + + @Mapping(target = "memberIds", source = "members", qualifiedByName = "usersToIds") + ChatDTO toChatDto(Chat chat); + + @Named("usersToIds") + default Set usersToIds(Set users) { + if (users == null) return new LinkedHashSet<>(); + return users.stream() + .map(User::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java new file mode 100644 index 00000000..b30bf2e1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +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); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java new file mode 100644 index 00000000..74380480 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.User; + +@Mapper(componentModel = "spring") +public interface UserMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "passwordHash", ignore = true) + @Mapping(target = "chats", ignore = true) + @Mapping(target = "messages", ignore = true) + User toUser(UserDTO dto); + + @Mapping(target = "password", ignore = true) + UserDTO toUserDto(User user); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Chat.java b/src/main/java/ru/mtusi/messenger/model/Chat.java new file mode 100644 index 00000000..5d02fbc1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Chat.java @@ -0,0 +1,52 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +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(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Message.java b/src/main/java/ru/mtusi/messenger/model/Message.java new file mode 100644 index 00000000..a22f1c97 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Message.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +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(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Session.java b/src/main/java/ru/mtusi/messenger/model/Session.java new file mode 100644 index 00000000..1cca82dc --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Session.java @@ -0,0 +1,41 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; +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(); + } + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/User.java b/src/main/java/ru/mtusi/messenger/model/User.java new file mode 100644 index 00000000..d42a4c66 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/User.java @@ -0,0 +1,47 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.LocalDateTime; +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(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java new file mode 100644 index 00000000..c3f70c9e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java @@ -0,0 +1,30 @@ +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 + and (:cursorCreated is null + or c.createdAt > :cursorCreated + or (c.createdAt = :cursorCreated and c.id > :cursorId)) + order by c.createdAt asc, c.id asc + """) + List findPageByMember(@Param("userId") UUID userId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} diff --git a/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java new file mode 100644 index 00000000..afa6ce15 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java @@ -0,0 +1,29 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.domain.Pageable; +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 java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface MessageRepository extends JpaRepository { + + @Query(""" + select m from Message m + where m.chat.id = :chatId + and (:cursorCreated is null + or m.createdAt > :cursorCreated + or (m.createdAt = :cursorCreated and m.id > :cursorId)) + order by m.createdAt asc, m.id asc + """) + List findPageByChat(@Param("chatId") UUID chatId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); + + long countByChatId(UUID chatId); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java new file mode 100644 index 00000000..2fc1dce7 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java @@ -0,0 +1,12 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.mtusi.messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository extends JpaRepository { + Optional findByTokenHash(byte[] tokenHash); + +} diff --git a/src/main/java/ru/mtusi/messenger/repository/UserRepository.java b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java new file mode 100644 index 00000000..9a9a6d4a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.repository; + + +import jakarta.persistence.LockModeType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.User; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public interface UserRepository extends JpaRepository { + + Optional findByUsername(String username); + + @Lock(LockModeType.PESSIMISTIC_READ) + @Query("select u from User u where u.id in :ids") + Set findAllByIdForShare(@Param("ids") Set ids); +} diff --git a/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java new file mode 100644 index 00000000..e2f4d10f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java @@ -0,0 +1,32 @@ +package ru.mtusi.messenger.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ApiErrorFactory errors; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { + String scheme = request.getRequestURI().equals("/api/v1/auth/sessions") ? "Basic" : "Bearer"; + + errors.writeError( + response, + request, + HttpStatus.UNAUTHORIZED, + scheme + " realm=\"messenger\"", + ErrorErrorDTO.CodeEnum.UNAUTHORIZED, + "No valid authentication"); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java new file mode 100644 index 00000000..116ad7c0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java @@ -0,0 +1,28 @@ +package ru.mtusi.messenger.security; + +import ru.mtusi.messenger.exception.UnauthorizedException; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public record BasicCredentials(String username, String password) { + + public static BasicCredentials parse(String header) { + if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) { + throw new UnauthorizedException("Basic authentication required"); + } + String decoded; + try { + decoded = new String( + Base64.getDecoder().decode(header.substring(6).trim()), + StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new UnauthorizedException("Invalid Basic encoding"); + } + int i = decoded.indexOf(':'); + if (i < 0) { + throw new UnauthorizedException("Invalid Basic credentials"); + } + return new BasicCredentials(decoded.substring(0, i), decoded.substring(i + 1)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java new file mode 100644 index 00000000..d6202098 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java @@ -0,0 +1,39 @@ +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.http.HttpHeaders; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +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 { + String token = bearerTokenResolver.resolve(request); + if (token != null && !token.isBlank()) { + try { + Authentication auth = authenticationManager.authenticate( + new SessionAuthenticationToken(token)); + SecurityContextHolder.getContext().setAuthentication(auth); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + } + } + chain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java new file mode 100644 index 00000000..d1d5ee56 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java @@ -0,0 +1,33 @@ +package ru.mtusi.messenger.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.service.SessionService; + +@Component +@RequiredArgsConstructor +public class SessionAuthenticationProvider implements AuthenticationProvider { + private final SessionService sessionService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String token = (String) authentication.getCredentials(); + try { + var rec = sessionService.requireActive(token); + return new SessionAuthenticationToken( + new SessionPrincipal(rec.userId(), rec.sessionId())); + } catch (UnauthorizedException e) { + throw new BadCredentialsException(e.getMessage(), e); + } + } + + @Override + public boolean supports(Class authentication) { + return SessionAuthenticationToken.class.isAssignableFrom(authentication); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java new file mode 100644 index 00000000..f5e9977d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java @@ -0,0 +1,34 @@ +package ru.mtusi.messenger.security; + +import org.springframework.security.authentication.AbstractAuthenticationToken; + +import java.util.List; + +public class SessionAuthenticationToken extends AbstractAuthenticationToken { + private final String rawToken; + private final SessionPrincipal principal; + + public SessionAuthenticationToken(String rawToken) { + super(List.of()); + this.rawToken = rawToken; + this.principal = null; + setAuthenticated(false); + } + + public SessionAuthenticationToken(SessionPrincipal principal) { + super(List.of()); + this.rawToken = null; + this.principal = principal; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return rawToken; + } + + @Override + public Object getPrincipal() { + return principal; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java new file mode 100644 index 00000000..8bcae0eb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.security; + +import java.util.UUID; + +public record SessionPrincipal(UUID userId, UUID sessionId) { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/AuthService.java b/src/main/java/ru/mtusi/messenger/service/AuthService.java new file mode 100644 index 00000000..04d5b683 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AuthService.java @@ -0,0 +1,32 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.security.BasicCredentials; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Service +@RequiredArgsConstructor +public class AuthService { + private final UserService userService; + private final SessionService sessionService; + + public SessionDTO login(String authorizationHeader) { + var creds = BasicCredentials.parse(authorizationHeader); + UserDTO userDTO = userService.authenticate(creds.username(), creds.password()); + return sessionService.createSession(userDTO); + } + + public void logout() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !(auth.getPrincipal() instanceof SessionPrincipal sp)) { + throw new UnauthorizedException("No active session"); + } + sessionService.revoke(sp.sessionId()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/ChatService.java b/src/main/java/ru/mtusi/messenger/service/ChatService.java new file mode 100644 index 00000000..92830a04 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -0,0 +1,117 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.mapper.ChatMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.ChatRepository; +import ru.mtusi.messenger.util.CursorCodec; + +import java.time.Instant; +import java.util.*; + +@Service +@Slf4j +@RequiredArgsConstructor +public class ChatService { + private final ChatMapper chatMapper; + private final UserService userService; + private final ChatRepository chatRepository; + + @Transactional + public ChatDTO createChat(UUID caller , ChatDTO chatDTO) { + Set members = validateCreate(caller, chatDTO); + Chat chat = buildChat(chatDTO, members); + try { + chat = chatRepository.saveAndFlush(chat); + } catch (DataIntegrityViolationException e) { + throw new NotFoundException("Cannot create chat: referenced entity is missing"); + } + return chatMapper.toChatDto(chat); + } + + private Set validateCreate(UUID caller, ChatDTO chatDTO) { + Set memberIds = chatDTO.getMemberIds(); + if (!memberIds.contains(caller)) { + throw new InvalidRequestException("Вызывающий должен быть участником"); + } + return userService.requireUsers(memberIds); + } + + private Chat buildChat(ChatDTO chatDTO, Set members) { + Chat chat = chatMapper.toChat(chatDTO); + chat.setMembers(members); + return chat; + } + + @Transactional(readOnly = true) + public ChatDTO getChat(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 chatMapper.toChatDto(chat); + } + + @Transactional(readOnly = true) + public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { + int size = (limit == null) ? 50 : limit; + CursorCodec.Cursor decoded = parseChatsCursor(cursor); + List rows = chatRepository.findPageByMember(userId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); + return buildPage(rows, size); + } + + private CursorCodec.Cursor parseChatsCursor(String cursor) { + if (cursor == null || cursor.isBlank()) { + return null; + } + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() != null) { + throw new InvalidRequestException("Invalid cursor"); + } + return decoded; + } + + private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) { + return cursor == null ? null : cursor.boundary().createdAt(); + } + + private UUID boundaryId(CursorCodec.Cursor cursor) { + return cursor == null ? null : cursor.boundary().id(); + } + + 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()); + } +} diff --git a/src/main/java/ru/mtusi/messenger/service/MessageService.java b/src/main/java/ru/mtusi/messenger/service/MessageService.java new file mode 100644 index 00000000..2559a19c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/MessageService.java @@ -0,0 +1,120 @@ +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.AppProperties; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.PayloadTooLargeException; +import ru.mtusi.messenger.mapper.ChatMapper; +import ru.mtusi.messenger.mapper.MessageMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.Message; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.MessageRepository; +import ru.mtusi.messenger.repository.UserRepository; +import ru.mtusi.messenger.util.CursorCodec; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +@Service +@Slf4j +@RequiredArgsConstructor +public class MessageService { + private final ChatMapper chatMapper; + private final MessageRepository messageRepository; + private final ChatService chatService; + private final UserService userService; + private final MessageMapper messageMapper; + private final AppProperties appProperties; + + @Transactional + public MessageDTO createMessage(UUID senderId, UUID chatId, MessageDTO messageDTO) { + ChatDTO chatDTO = chatService.getChat(senderId, chatId); + validateCreate(chatId, messageDTO); + User sender = userService.getReferenceUserById(senderId); + Message message = buildMessage(messageDTO, sender, chatDTO); + 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, MessageDTO 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(MessageDTO messageDTO, User sender, ChatDTO chatDTO) { + Message message = messageMapper.toMessage(messageDTO); + message.setChat(chatMapper.toChat(chatDTO)); + 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.getChat(userId, chatId); + CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId); + List rows = messageRepository.findPageByChat(chatId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); + return buildPage(rows, size, chatId); + } + + private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) { + if (cursor == null || cursor.isBlank()) { + return null; + } + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId)) { + throw new InvalidRequestException("Cursor from another chat"); + } + return decoded; + } + + private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) { + return cursor == null ? null : cursor.boundary().createdAt(); + } + + private UUID boundaryId(CursorCodec.Cursor cursor) { + return cursor == null ? null : cursor.boundary().id(); + } + + 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/SessionService.java b/src/main/java/ru/mtusi/messenger/service/SessionService.java new file mode 100644 index 00000000..652a65cc --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionService.java @@ -0,0 +1,80 @@ +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.SessionProperties; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.model.Session; +import ru.mtusi.messenger.repository.SessionRepository; +import ru.mtusi.messenger.util.TokenGenerator; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.UUID; + +@Slf4j +@RequiredArgsConstructor +@Service +public class SessionService { + private final TokenGenerator tokenGenerator; + private final SessionProperties sessionProperties; + private final SessionRepository sessionRepository; + + @Transactional + public SessionDTO createSession(UserDTO userDTO) { + String token = tokenGenerator.generate(); + Session session = sessionRepository.save(buildSession(userDTO,token)); + return toSessionDTO(session, token, userDTO); + } + + @Transactional(readOnly = true) + public SessionRecord requireActive(String token) { + Session s = sessionRepository.findByTokenHash(sha256(token)) + .filter(x -> x.getRevokedAt() == null) + .filter(x -> x.getExpiresAt().isAfter(Instant.now())) + .orElseThrow(() -> new UnauthorizedException("Invalid or expired session")); + return new SessionRecord(s.getId(), s.getUserId()); + } + + @Transactional + public void revoke(UUID sessionId) { + sessionRepository.findById(sessionId).ifPresent(s -> { + if (s.getRevokedAt() == null) { + s.setRevokedAt(Instant.now()); + } + }); + } + + private static 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); + } + } + + private Session buildSession(UserDTO userDTO, String token) { + Session session = new Session(); + session.setUserId(userDTO.getId()); + session.setTokenHash(sha256(token)); + session.setExpiresAt(Instant.now().plus(sessionProperties.ttl())); + return session; + } + + private SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO) { + return new SessionDTO() + .token(tokenRaw) + .tokenType(SessionDTO.TokenTypeEnum.BEARER) + .expiresAt(session.getExpiresAt()) + .user(userDTO); + } + + public record SessionRecord(UUID sessionId, UUID userId) {} +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/UserService.java b/src/main/java/ru/mtusi/messenger/service/UserService.java new file mode 100644 index 00000000..5f2bfba0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/UserService.java @@ -0,0 +1,81 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.mapper.UserMapper; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.UserRepository; + +import java.util.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(Set ids) { + Set users = userRepository.findAllByIdForShare(ids); + if (users.size() != ids.size()) { + throw new NotFoundException("Users not found: " + findMissing(ids, users)); + } + return users; + } + + private Set findMissing(Set requested, Set found) { + Set foundIds = found.stream() + .map(User::getId) + .collect(Collectors.toSet()); + + Set missing = new HashSet<>(requested); + missing.removeAll(foundIds); + return missing; + } + + @Transactional(readOnly = true) + public UserDTO authenticate(String username, String password) { + User user = userRepository.findByUsername(username).orElseThrow(() -> new UnauthorizedException("Bad credentials")); + + if (!passwordEncoder.matches(password, user.getPasswordHash())) { + throw new UnauthorizedException("Bad credentials"); + } + return userMapper.toUserDto(user); + } + + @Transactional + public UserDTO registerUser(UserDTO userDTO) { + User user = userMapper.toUser(userDTO); + user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword())); + try { + return userMapper.toUserDto(userRepository.saveAndFlush(user)); + } catch (DataIntegrityViolationException exception) { + throw new ConflictException("Username already exists"); + } + } + + @Transactional(readOnly = true) + public UserDTO currentUser(UUID userId) { + return userMapper.toUserDto(userRepository.findById(userId).orElseThrow(() -> + new NotFoundException("User not found") + )); + } + + @Transactional + public User getReferenceUserById(UUID senderId) { + return userRepository.getReferenceById(senderId); + } +} diff --git a/src/main/java/ru/mtusi/messenger/util/CursorCodec.java b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java new file mode 100644 index 00000000..860d4029 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import ru.mtusi.messenger.exception.InvalidRequestException; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +public final class CursorCodec { + + private CursorCodec() {} + + public record PageBoundary(Instant createdAt, UUID id) {} + + public record Cursor(UUID scopeId, PageBoundary boundary) {} + + public static String encode(UUID scopeId, PageBoundary boundary) { + String raw = (scopeId == null ? "" : scopeId.toString()) + + "|" + boundary.createdAt() + "|" + boundary.id(); + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + public static Cursor decode(String cursor) { + try { + String raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8); + String[] p = raw.split("\\|", -1); + UUID scopeId = p[0].isEmpty() ? null : UUID.fromString(p[0]); + PageBoundary boundary = new PageBoundary( + Instant.parse(p[1]), UUID.fromString(p[2])); + return new Cursor(scopeId, boundary); + } catch (Exception e) { + throw new InvalidRequestException("Invalid cursor"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java new file mode 100644 index 00000000..fa000c45 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.security.SecureRandom; +import java.util.Base64; + +@Component +public class TokenGenerator { + private final SecureRandom rng = new SecureRandom(); + + public String generate() { + byte[] raw = new byte[32]; + rng.nextBytes(raw); + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw); + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 00000000..06c40e97 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,57 @@ +spring: + application: + name: messenger-lab2 + config: + import: "optional:configtree:/run/secrets/" + lifecycle: + timeout-per-shutdown-phase: 10s + jackson: + default-property-inclusion: non_null + deserialization: + fail-on-unknown-properties: true + datasource: + driver-class-name: org.postgresql.Driver + url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${SPRING_DATASOURCE_USERNAME:messenger} + password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only} + 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 + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + +management: + endpoints: + web: + exposure: + include: health,metrics + endpoint: + health: + probes: + enabled: true + show-details: always + +app: + limits: + max-messages-per-chat: ${MAX_MESSAGES_PER_CHAT:10000} + rate: + rate-per-minute: ${RATE_PER_MINUTE:600} + retry-after-seconds: ${RETRY_AFTER_SECONDS:60} + session: + ttl: ${SESSION_TTL_SECONDS:400}s + +logging: + pattern: + console: "%d{ISO8601} %-5level [%X{requestId}] %logger{20} - %msg%n" \ No newline at end of file diff --git a/src/main/resources/db/migration/V1__init.sql b/src/main/resources/db/migration/V1__init.sql new file mode 100644 index 00000000..dc3eb522 --- /dev/null +++ b/src/main/resources/db/migration/V1__init.sql @@ -0,0 +1,79 @@ +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- ---------- users ---------- +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + username VARCHAR(32) NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_users_username UNIQUE (username), + CONSTRAINT ck_users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT ck_users_display_name_not_blank + CHECK (length(btrim(display_name)) > 0) +); + +-- ---------- chats ---------- +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_chats_title_not_blank CHECK (length(btrim(title)) > 0) +); + +-- ---------- chat_members ---------- +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +-- ---------- messages ---------- +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text VARCHAR(4000) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_messages_text_not_blank CHECK (length(btrim(text)) > 0) +); + +-- ---------- sessions ---------- +CREATE TABLE sessions ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + CONSTRAINT uq_sessions_token_hash UNIQUE (token_hash), + CONSTRAINT ck_sessions_expiry CHECK (expires_at > created_at), + CONSTRAINT ck_sessions_token_len CHECK (octet_length(token_hash) = 32) +); + +-- ========================================================= +-- Indexes (critical for keyset pagination & EXPLAIN on lab5) +-- ========================================================= + +-- Keyset pagination: ORDER BY created_at ASC, id ASC (JPQL uses ASC) +CREATE INDEX idx_messages_chat_created_asc_id + ON messages (chat_id, created_at ASC, id ASC); + +-- "My chats" list (listChats) +CREATE INDEX idx_chat_members_user + ON chat_members (user_id); + +-- For chats list pagination: ORDER BY created_at ASC, id ASC +CREATE INDEX idx_chats_created_asc_id + ON chats (created_at ASC, id ASC); + +-- Active sessions per user (logout-all / audit) +CREATE INDEX idx_sessions_user_active + ON sessions (user_id) + WHERE revoked_at IS NULL; + +-- Cleanup of expired sessions +CREATE INDEX idx_sessions_expires_active + ON sessions (expires_at) + WHERE revoked_at IS NULL; \ No newline at end of file diff --git a/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java new file mode 100644 index 00000000..2da5d512 --- /dev/null +++ b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java @@ -0,0 +1,13 @@ +package ru.mtusi.messenger; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MessengerLab1ApplicationTests { + + @Test + void contextLoads() { + } + +} -- 2.54.0 From 65bd58c4091819c82f626511223e555a7c30677f Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 8 Oct 2026 13:08:31 +0300 Subject: [PATCH 2/7] concurrency --- .gitignore | 115 ++++++++---------- build.gradle | 7 +- contracts/openapi.json | 35 +++++- docker-compose.yaml | 25 ++++ scripts/restart.bat | 2 + scripts/seed_messages.sql | 24 ++++ scripts/seed_track2.sql | 75 ++++++++++++ .../messenger/config/ExecutorConfig.java | 24 ++++ .../messenger/config/RateLimitConfig.java | 1 + .../mtusi/messenger/config/RedisConfig.java | 102 ++++++++++++++++ .../{ => properties}/AppProperties.java | 2 +- .../{ => properties}/RateLimitProperties.java | 2 +- .../config/properties/RedisProperties.java | 16 +++ .../{ => properties}/SessionProperties.java | 2 +- .../messenger/controller/ChatController.java | 2 +- .../mtusi/messenger/controller/ChatsApi.java | 2 +- .../mtusi/messenger/controller/HealthApi.java | 72 +++++------ .../controller/HealthController.java | 18 ++- .../controller/MessageController.java | 5 +- .../messenger/controller/MessagesApi.java | 5 +- .../GlobalExceptionHandler.java | 32 ++++- .../java/ru/mtusi/messenger/dto/ChatDTO.java | 65 +++++++--- .../ru/mtusi/messenger/dto/ChatPageDTO.java | 3 + .../mtusi/messenger/dto/MessagePageDTO.java | 3 + .../java/ru/mtusi/messenger/dto/UserDTO.java | 28 ++++- .../messenger/exception/ApiErrorFactory.java | 5 +- .../ServiceUnavailableException.java | 7 ++ .../messenger/filter/RateLimitFilter.java | 3 +- .../mtusi/messenger/mapper/MessageMapper.java | 3 + .../mtusi/messenger/mapper/SessionMapper.java | 17 +++ .../java/ru/mtusi/messenger/model/Chat.java | 3 +- .../ru/mtusi/messenger/model/Message.java | 3 +- .../ru/mtusi/messenger/model/Session.java | 3 +- .../java/ru/mtusi/messenger/model/User.java | 3 +- .../messenger/repository/ChatRepository.java | 21 +++- .../repository/MessageRepository.java | 24 ++-- .../mtusi/messenger/service/ChatService.java | 25 ++-- .../messenger/service/HealthService.java | 31 +++++ .../messenger/service/MessageService.java | 35 ++---- .../messenger/service/SessionService.java | 58 +++++---- .../ru/mtusi/messenger/util/TokenHasher.java | 37 ++++++ src/main/resources/application.yaml | 22 ++++ 42 files changed, 743 insertions(+), 224 deletions(-) create mode 100644 scripts/restart.bat create mode 100644 scripts/seed_messages.sql create mode 100644 scripts/seed_track2.sql create mode 100644 src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/config/RedisConfig.java rename src/main/java/ru/mtusi/messenger/config/{ => properties}/AppProperties.java (80%) rename src/main/java/ru/mtusi/messenger/config/{ => properties}/RateLimitProperties.java (81%) create mode 100644 src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java rename src/main/java/ru/mtusi/messenger/config/{ => properties}/SessionProperties.java (82%) rename src/main/java/ru/mtusi/messenger/{exception => controller/controllerAdvice}/GlobalExceptionHandler.java (81%) create mode 100644 src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java create mode 100644 src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java create mode 100644 src/main/java/ru/mtusi/messenger/service/HealthService.java create mode 100644 src/main/java/ru/mtusi/messenger/util/TokenHasher.java diff --git a/.gitignore b/.gitignore index 5cb289f7..ccdf7fea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,5 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - - -# Created by https://www.gitignore.io/api/git,java,maven,eclipse,windows - ### Git ### -# Created by git for backups. To disable backups in Git: -# $ git config --global mergetool.keepBackup false *.orig - -# Created by git when using merge tools for conflicts *.BACKUP.* *.BASE.* *.LOCAL.* @@ -29,7 +10,6 @@ *_REMOTE_*.txt ### Java ### -# Compiled class file *.class # Log file @@ -37,11 +17,9 @@ # BlueJ files *.ctxt - -# Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +# Package files *.jar *.war *.nar @@ -50,69 +28,82 @@ *.tar.gz *.rar -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +# 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 ### -# Windows thumbnail cache files Thumbs.db ehthumbs.db ehthumbs_vista.db - -# Dump file -*.stackdump - -# Folder config file [Dd]esktop.ini - -# Recycle Bin used on file shares $RECYCLE.BIN/ - -# Windows Installer files *.cab *.msi *.msix *.msm *.msp - -# Windows shortcuts *.lnk -### IntelliJ IDEA ### -SpringTech/.idea -*.iws -*.iml -*.ipr +### macOS ### +.DS_Store +.AppleDouble +.LSOverride -### VS Code ### -.vscode/ - -### Some additional ignores (sort later) -*.DS_Store +### Miscellaneous ### *.sw? .#* *# *~ -.classpath -.project -.settings -bin -/build/* -target -dependency-reduced-pom.xml -*.sublime-* +bin/ /scratch -.gradle -README.html -*.iml -.idea -.exercism -# Environment +*.sublime-* + +### Environment / Secrets ### .env .env.* !.env.example +secrets/ +secrets/*.txt +!secrets/.gitkeep +### Python / venv ### __pycache__/ *.pyc -!gradle/wrapper/gradle-wrapper.jar -secrets/ \ No newline at end of file +.venv/ +.venv +venv/ + +### Lab evidence ### +evidence/**/*.dump +evidence/**/*.sql.gz +evidence/**/raw/ +evidence/**/*.raw \ No newline at end of file diff --git a/build.gradle b/build.gradle index 5424af91..8952432a 100644 --- a/build.gradle +++ b/build.gradle @@ -36,9 +36,6 @@ dependencies { 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 'com.fasterxml.jackson.core:jackson-databind' - implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' - testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1' @@ -58,6 +55,10 @@ dependencies { testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } +tasks.withType(JavaCompile).configureEach { + options.compilerArgs << '-parameters' +} + tasks.named('test') { useJUnitPlatform() } \ No newline at end of file diff --git a/contracts/openapi.json b/contracts/openapi.json index 921d32db..7881abba 100644 --- a/contracts/openapi.json +++ b/contracts/openapi.json @@ -16,9 +16,32 @@ "bearerAuth": [] } ], + "tags": [ + { + "name": "Health", + "description": "Проверки живости и готовности процесса. Публичные, без аутентификации." + }, + { + "name": "Users", + "description": "Регистрация пользователей и доступ к профилю текущего пользователя." + }, + { + "name": "Auth", + "description": "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена." + }, + { + "name": "Chats", + "description": "Управление чатами и доступ к чатам текущего пользователя." + }, + { + "name": "Messages", + "description": "Отправка и чтение сообщений внутри доступного чата." + } + ], "paths": { "/health/live": { "get": { + "tags": ["Health"], "operationId": "liveness", "summary": "Процесс жив", "responses": { @@ -66,6 +89,7 @@ }, "/health/ready": { "get": { + "tags": ["Health"], "operationId": "readiness", "summary": "Готов принимать трафик", "responses": { @@ -132,6 +156,7 @@ }, "/api/v1/users": { "post": { + "tags": ["Users"], "operationId": "registerUser", "summary": "Создать пользователя", "responses": { @@ -272,6 +297,7 @@ }, "/api/v1/users/me": { "get": { + "tags": ["Users"], "operationId": "currentUser", "summary": "Текущий пользователь", "responses": { @@ -445,6 +471,7 @@ }, "/api/v1/chats": { "post": { + "tags": ["Chats"], "operationId": "createChat", "summary": "Создать чат; вызывающий должен входить в member_ids", "responses": { @@ -626,6 +653,7 @@ } }, "get": { + "tags": ["Chats"], "operationId": "listChats", "summary": "Чаты текущего пользователя", "responses": { @@ -819,6 +847,7 @@ }, "/api/v1/chats/{chat_id}": { "get": { + "tags": ["Chats"], "operationId": "getChat", "summary": "Получить доступный чат", "responses": { @@ -1003,6 +1032,7 @@ }, "/api/v1/chats/{chat_id}/messages": { "post": { + "tags": ["Messages"], "operationId": "createMessage", "summary": "Отправить сообщение", "responses": { @@ -1195,6 +1225,7 @@ } }, "get": { + "tags": ["Messages"], "operationId": "listMessages", "summary": "Сообщения по (created_at, id) по возрастанию", "responses": { @@ -1397,6 +1428,7 @@ }, "/api/v1/auth/sessions": { "post": { + "tags": ["Auth"], "operationId": "createSession", "summary": "Вход: Basic username:password; выдаёт сессию", "responses": { @@ -1537,6 +1569,7 @@ }, "/api/v1/auth/sessions/current": { "delete": { + "tags": ["Auth"], "operationId": "revokeSession", "summary": "Отозвать текущую сессию", "responses": { @@ -2023,4 +2056,4 @@ } } } -} +} \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index 6f4736f9..9c25cc21 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -22,6 +22,26 @@ services: retries: 10 start_period: 10s + redis: + image: redis:7.4-alpine + container_name: messenger-redis + restart: unless-stopped + command: > + redis-server + --appendonly yes + --appendfsync everysec + --save "" + volumes: + - redisdata:/data + networks: + - messenger-net + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + api: build: context: . @@ -31,6 +51,8 @@ services: depends_on: db: condition: service_healthy + redis: + condition: service_healthy environment: SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user @@ -38,6 +60,8 @@ services: SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400} SESSION_STORE: ${SESSION_STORE:-postgres} + SPRING_DATA_REDIS_HOST: redis + SPRING_DATA_REDIS_PORT: 6379 ports: - "127.0.0.1:8080:8080" secrets: @@ -54,6 +78,7 @@ services: volumes: pgdata: + redisdata: networks: messenger-net: diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 00000000..caba6d52 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,2 @@ +@echo off +docker compose --env-file .env restart api db \ No newline at end of file diff --git a/scripts/seed_messages.sql b/scripts/seed_messages.sql new file mode 100644 index 00000000..c188dd4a --- /dev/null +++ b/scripts/seed_messages.sql @@ -0,0 +1,24 @@ +-- создаём тестового юзера и чат +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed', + '$2a$10$abcdefghijklmnopqrstuv', now()) + ON CONFLICT (username) DO NOTHING; + +INSERT INTO chats (id, title, created_at) +VALUES ('22222222-2222-4222-8222-222222222222', 'seed_chat', now()) + ON CONFLICT (id) DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id, role, joined_at) +VALUES ('22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', 'owner', now()) + ON CONFLICT DO NOTHING; + +-- 10000 сообщений с разбросом created_at за последние 30 дней +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), + '22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', + 'msg #' || g || ' ' || repeat('x', 1 + (random()*200)::int), + now() - (random() * interval '30 days') +FROM generate_series(1, 10000) g; \ No newline at end of file diff --git a/scripts/seed_track2.sql b/scripts/seed_track2.sql new file mode 100644 index 00000000..6a8edd03 --- /dev/null +++ b/scripts/seed_track2.sql @@ -0,0 +1,75 @@ +-- Пользователи +INSERT INTO users (id, username, display_name, password_hash, created_at) +SELECT + gen_random_uuid(), + 'u_' || lpad(g::text, 4, '0'), + 'User ' || g, + '$2a$10$abcdefghijklmnopqrstuv', -- фиктивный bcrypt-хеш, не для логина + now() - (random() * interval '60 days') +FROM generate_series(1, 20) g; + +-- Один чат-гигант +INSERT INTO chats (id, title, created_at) +VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Huge chat', now() - interval '60 days'); + +INSERT INTO chat_members (chat_id, user_id) +SELECT 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', id FROM users LIMIT 5; + +-- 50 000 сообщений в гиганта +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + (SELECT id FROM users ORDER BY random() LIMIT 1), + 'msg #' || g || ' ' || repeat('x', 1 + (random()*100)::int), + now() - (random() * interval '60 days') +FROM generate_series(1, 50000) g; + +-- 5 чатов по 5000 +DO $$ +DECLARE +cid uuid; + i int; +BEGIN +FOR i IN 1..5 LOOP + cid := gen_random_uuid(); +INSERT INTO chats (id, title, created_at) +VALUES (cid, 'Medium chat ' || i, now() - (random() * interval '60 days')); +INSERT INTO chat_members (chat_id, user_id) +SELECT cid, id FROM users LIMIT 3; +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), cid, + (SELECT id FROM users ORDER BY random() LIMIT 1), + 'm-' || i || '-' || g || ' ' || repeat('x', 1 + (random()*100)::int), + now() - (random() * interval '60 days') +FROM generate_series(1, 5000) g; +END LOOP; +END $$; + +-- 250 чатов по 100 +DO $$ +DECLARE +cid uuid; + i int; +BEGIN +FOR i IN 1..250 LOOP + cid := gen_random_uuid(); +INSERT INTO chats (id, title, created_at) +VALUES (cid, 'Small chat ' || i, now() - (random() * interval '60 days')); +INSERT INTO chat_members (chat_id, user_id) +SELECT cid, id FROM users LIMIT 2; +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), cid, + (SELECT id FROM users ORDER BY random() LIMIT 1), + 's-' || i || '-' || g, + now() - (random() * interval '60 days') +FROM generate_series(1, 100) g; +END LOOP; +END $$; + +ANALYZE users; +ANALYZE chats; +ANALYZE chat_members; +ANALYZE messages; \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java b/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java new file mode 100644 index 00000000..a34b9c1a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java @@ -0,0 +1,24 @@ +package ru.mtusi.messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +@Configuration +public class ExecutorConfig { + + @Bean(destroyMethod = "shutdown") + public ExecutorService cacheEvictExecutor() { + AtomicInteger counter = new AtomicInteger(); + ThreadFactory factory = r -> { + Thread t = new Thread(r, "cache-evict-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; + }; + return Executors.newSingleThreadExecutor(factory); + } +} \ 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 index 874549df..3a609576 100644 --- a/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java +++ b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java @@ -5,6 +5,7 @@ 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; diff --git a/src/main/java/ru/mtusi/messenger/config/RedisConfig.java b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java new file mode 100644 index 00000000..854f4dfe --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java @@ -0,0 +1,102 @@ +package ru.mtusi.messenger.config; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.SocketOptions; +import io.lettuce.core.resource.ClientResources; +import io.lettuce.core.resource.DefaultClientResources; +import io.lettuce.core.resource.DirContextDnsResolver; +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.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; + + @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) { + log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { + log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { + log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheClearError(RuntimeException e, Cache cache) { + 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/AppProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java similarity index 80% rename from src/main/java/ru/mtusi/messenger/config/AppProperties.java rename to src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java index e15176cb..127495e6 100644 --- a/src/main/java/ru/mtusi/messenger/config/AppProperties.java +++ b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java @@ -1,4 +1,4 @@ -package ru.mtusi.messenger.config; +package ru.mtusi.messenger.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/ru/mtusi/messenger/config/RateLimitProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java similarity index 81% rename from src/main/java/ru/mtusi/messenger/config/RateLimitProperties.java rename to src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java index e8c1b8ee..39d4646d 100644 --- a/src/main/java/ru/mtusi/messenger/config/RateLimitProperties.java +++ b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java @@ -1,4 +1,4 @@ -package ru.mtusi.messenger.config; +package ru.mtusi.messenger.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java new file mode 100644 index 00000000..994ae257 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.redis") +public record RedisProperties( + String host, + int port, + Duration commandTimeout, + Duration connectTimeout, + Duration shutdownTimeout, + Duration keepAliveIdle, + Duration keepAliveInterval, + Duration tcpUserTimeout +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/SessionProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java similarity index 82% rename from src/main/java/ru/mtusi/messenger/config/SessionProperties.java rename to src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java index b4ac8cd2..6ff06f2f 100644 --- a/src/main/java/ru/mtusi/messenger/config/SessionProperties.java +++ b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java @@ -1,4 +1,4 @@ -package ru.mtusi.messenger.config; +package ru.mtusi.messenger.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatController.java b/src/main/java/ru/mtusi/messenger/controller/ChatController.java index 2344b4b1..5eb47727 100644 --- a/src/main/java/ru/mtusi/messenger/controller/ChatController.java +++ b/src/main/java/ru/mtusi/messenger/controller/ChatController.java @@ -25,7 +25,7 @@ public class ChatController implements ChatsApi { @Override public ResponseEntity getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) { - return ResponseEntity.ok(chatService.getChat(principal.userId(), chatId)); + return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId)); } @Override diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java index 57f81d14..c5b11eaf 100644 --- a/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java +++ b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java @@ -107,7 +107,7 @@ public interface ChatsApi { * or Неожиданная ошибка без внутренних деталей (status code 500) */ @Operation( - operationId = "getChat", + operationId = "getChatDTO", summary = "Получить доступный чат", tags = { "Chats" }, responses = { diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthApi.java b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java index 015bd501..3c4f69f5 100644 --- a/src/main/java/ru/mtusi/messenger/controller/HealthApi.java +++ b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java @@ -30,26 +30,26 @@ public interface HealthApi { * 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)) - }) - } + 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" } + method = RequestMethod.GET, + value = "/health/live", + produces = { "application/json" } ) - + ResponseEntity liveness( - + ); @@ -61,29 +61,29 @@ public interface HealthApi { * 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)) - }) - } + 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" } + 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 index 6652d0bd..d5b8bb7c 100644 --- a/src/main/java/ru/mtusi/messenger/controller/HealthController.java +++ b/src/main/java/ru/mtusi/messenger/controller/HealthController.java @@ -1,26 +1,24 @@ package ru.mtusi.messenger.controller; +import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.service.HealthService; @RestController +@RequiredArgsConstructor public class HealthController implements HealthApi { - private static final HealthDTO OK = createOk(); + + private final HealthService healthService; @Override public ResponseEntity liveness() { - return ResponseEntity.ok(OK); + return ResponseEntity.ok(healthService.liveness()); } @Override public ResponseEntity readiness() { - return ResponseEntity.ok(OK); + return ResponseEntity.ok(healthService.readiness()); } - - private static HealthDTO createOk() { - 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/controller/MessageController.java b/src/main/java/ru/mtusi/messenger/controller/MessageController.java index 26dc199a..11fc588d 100644 --- a/src/main/java/ru/mtusi/messenger/controller/MessageController.java +++ b/src/main/java/ru/mtusi/messenger/controller/MessageController.java @@ -5,6 +5,7 @@ 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; @@ -18,8 +19,8 @@ public class MessageController implements MessagesApi { private final MessageService messageService; @Override - public ResponseEntity createMessage(UUID chatId, MessageDTO messageDTO, @AuthenticationPrincipal SessionPrincipal principal) { - return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, messageDTO)); + public ResponseEntity createMessage(UUID chatId, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO)); } @Override diff --git a/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java index 618b8bd6..2d59677c 100644 --- a/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java +++ b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java @@ -6,6 +6,7 @@ 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; @@ -77,8 +78,8 @@ public interface MessagesApi { ResponseEntity createMessage( @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) @PathVariable("chat_id") UUID chatId, - @Parameter(name = "MessageDTO", description = "", required = true) - @Valid @RequestBody MessageDTO messageDTO, + @Parameter(name = "CreateMessageDTO", description = "", required = true) + @Valid @RequestBody CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal ); diff --git a/src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java similarity index 81% rename from src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java rename to src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java index 53cef055..46a10d19 100644 --- a/src/main/java/ru/mtusi/messenger/exception/GlobalExceptionHandler.java +++ b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java @@ -1,11 +1,14 @@ -package ru.mtusi.messenger.exception; +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; @@ -14,9 +17,10 @@ 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.RateLimitProperties; +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 @@ -110,6 +114,30 @@ public class GlobalExceptionHandler { "Internal error", req); } + @ExceptionHandler(ServiceUnavailableException.class) + public ResponseEntity serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + e.getMessage(), req); + } + + @ExceptionHandler({ + CannotCreateTransactionException.class, + DataAccessResourceFailureException.class + }) + public ResponseEntity dependencyUnavailable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + "Dependency unavailable", req); + } + + @ExceptionHandler(DataAccessException.class) + public ResponseEntity dataAccess(DataAccessException e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Database error", req); + } + private ResponseEntity respond(HttpStatus status, ErrorErrorDTO.CodeEnum code, String message, diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java index 575dfd06..eaae7ffe 100644 --- a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -1,6 +1,7 @@ package ru.mtusi.messenger.dto; import java.util.Objects; +import java.time.Instant; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.LinkedHashSet; @@ -8,21 +9,23 @@ import java.util.Set; import java.util.UUID; import jakarta.validation.Valid; import jakarta.validation.constraints.*; -import org.hibernate.validator.constraints.*; import io.swagger.v3.oas.annotations.media.Schema; - import java.util.*; import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") public class ChatDTO { + private UUID id; + private String title; @Valid private Set memberIds = new LinkedHashSet<>(); + private Instant createdAt; + public ChatDTO() { super(); } @@ -35,15 +38,27 @@ public class ChatDTO { 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; } - /** - * Get title - * @return title - */ @NotNull @Size(min = 1, max = 100) @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("title") @@ -68,10 +83,6 @@ public class ChatDTO { return this; } - /** - * Get memberIds - * @return memberIds - */ @NotNull @Valid @Size(min = 1, max = 100) @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("member_ids") @@ -84,6 +95,21 @@ public class ChatDTO { 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) { @@ -93,34 +119,33 @@ public class ChatDTO { return false; } ChatDTO createChat = (ChatDTO) o; - return Objects.equals(this.title, createChat.title) && - Objects.equals(this.memberIds, createChat.memberIds); + 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(title, memberIds); + return Objects.hash(id, title, memberIds, createdAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class CreateChat {\n"); + 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(); } - /** - * 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/ChatPageDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java index 9a67d08d..240e39f3 100644 --- a/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java @@ -1,6 +1,8 @@ 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; @@ -70,6 +72,7 @@ public class ChatPageDTO { * Get nextCursor * @return nextCursor */ + @JsonInclude(JsonInclude.Include.ALWAYS) @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("next_cursor") public String getNextCursor() { diff --git a/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java index 6b6cec9c..2c44c67e 100644 --- a/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java @@ -1,6 +1,8 @@ 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; @@ -71,6 +73,7 @@ public class MessagePageDTO { * Get nextCursor * @return nextCursor */ + @JsonInclude(JsonInclude.Include.ALWAYS) @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("next_cursor") public String getNextCursor() { diff --git a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java index 9a7e7eb5..269fa6dd 100644 --- a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -1,5 +1,6 @@ package ru.mtusi.messenger.dto; +import java.time.Instant; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.Valid; @@ -22,6 +23,8 @@ public class UserDTO { private String password; + private Instant createdAt; + public UserDTO() { super(); } @@ -111,6 +114,25 @@ public class UserDTO { this.password = password; } + public UserDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -123,12 +145,13 @@ public class UserDTO { return Objects.equals(this.id, userDTO.id) && Objects.equals(this.username, userDTO.username) && Objects.equals(this.displayName, userDTO.displayName) && - Objects.equals(this.password, userDTO.password); + Objects.equals(this.password, userDTO.password) && + Objects.equals(this.createdAt, userDTO.createdAt); } @Override public int hashCode() { - return Objects.hash(id, username, displayName, password); + return Objects.hash(id, username, displayName, password, createdAt); } @Override @@ -139,6 +162,7 @@ public class UserDTO { sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java index 7a8bb2e8..26b98d56 100644 --- a/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java +++ b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java @@ -60,9 +60,12 @@ public class ApiErrorFactory { } String mdc = MDC.get(REQUEST_ID_MDC); if (mdc != null && !mdc.isBlank()) { + request.setAttribute(REQUEST_ID_ATTR, mdc); return mdc; } - return UUID.randomUUID().toString(); + String generated = UUID.randomUUID().toString(); + request.setAttribute(REQUEST_ID_ATTR, generated); + return generated; } private String normalizeMessage(String message) { diff --git a/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java new file mode 100644 index 00000000..da565290 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class ServiceUnavailableException extends RuntimeException { + public ServiceUnavailableException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java index 3eb8d825..2476160b 100644 --- a/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java +++ b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java @@ -10,8 +10,7 @@ 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.AppProperties; -import ru.mtusi.messenger.config.RateLimitProperties; +import ru.mtusi.messenger.config.properties.RateLimitProperties; import ru.mtusi.messenger.dto.ErrorErrorDTO; import ru.mtusi.messenger.exception.ApiErrorFactory; diff --git a/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java index b30bf2e1..393f23e4 100644 --- a/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java +++ b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java @@ -2,6 +2,7 @@ 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; @@ -17,4 +18,6 @@ public interface MessageMapper { @Mapping(target = "chatId", source = "chat.id") @Mapping(target = "senderId", source = "sender.id") MessageDTO toMessageDTO(Message entity); + + Message toMessage(CreateMessageDTO dto); } \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java new file mode 100644 index 00000000..83478e43 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.Session; + +@Mapper(componentModel = "spring") +public interface SessionMapper { + + @Mapping(target = "token", source = "tokenRaw") + @Mapping(target = "tokenType", expression = "java(ru.mtusi.messenger.dto.SessionDTO.TokenTypeEnum.BEARER)") + @Mapping(target = "expiresAt", source = "session.expiresAt") + @Mapping(target = "user", source = "userDTO") + SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Chat.java b/src/main/java/ru/mtusi/messenger/model/Chat.java index 5d02fbc1..9fbb85f2 100644 --- a/src/main/java/ru/mtusi/messenger/model/Chat.java +++ b/src/main/java/ru/mtusi/messenger/model/Chat.java @@ -4,6 +4,7 @@ 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; @@ -47,6 +48,6 @@ public class Chat { @PrePersist private void onCreate() { - this.createdAt = Instant.now(); + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); } } \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Message.java b/src/main/java/ru/mtusi/messenger/model/Message.java index a22f1c97..b4a368d1 100644 --- a/src/main/java/ru/mtusi/messenger/model/Message.java +++ b/src/main/java/ru/mtusi/messenger/model/Message.java @@ -4,6 +4,7 @@ import jakarta.persistence.*; import lombok.*; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.UUID; @Entity @@ -34,6 +35,6 @@ public class Message { @PrePersist private void onCreate() { - this.createdAt = Instant.now(); + 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 index 1cca82dc..4a2124dd 100644 --- a/src/main/java/ru/mtusi/messenger/model/Session.java +++ b/src/main/java/ru/mtusi/messenger/model/Session.java @@ -6,6 +6,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.UUID; @Entity @@ -35,7 +36,7 @@ public class Session { @PrePersist private void onCreate() { - this.createdAt = Instant.now(); + 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 index d42a4c66..21386805 100644 --- a/src/main/java/ru/mtusi/messenger/model/User.java +++ b/src/main/java/ru/mtusi/messenger/model/User.java @@ -5,6 +5,7 @@ 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; @@ -42,6 +43,6 @@ public class User{ @PrePersist private void onCreate() { - this.createdAt = Instant.now(); + 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 index c3f70c9e..0ed58876 100644 --- a/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java +++ b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java @@ -18,13 +18,22 @@ public interface ChatRepository extends JpaRepository { select distinct c from Chat c join c.members m where m.id = :userId - and (:cursorCreated is null - or c.createdAt > :cursorCreated - or (c.createdAt = :cursorCreated and c.id > :cursorId)) order by c.createdAt asc, c.id asc """) List findPageByMember(@Param("userId") UUID userId, - @Param("cursorCreated") Instant cursorCreated, - @Param("cursorId") UUID cursorId, Pageable pageable); -} + + @EntityGraph(attributePaths = "members") + @Query(""" + select distinct c from Chat c + join c.members m + where m.id = :userId + and (c.createdAt > :cursorCreated + or (c.createdAt = :cursorCreated and c.id > :cursorId)) + order by c.createdAt asc, c.id asc + """) + List findPageByMemberAfterCursor(@Param("userId") UUID userId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java index afa6ce15..35134b4a 100644 --- a/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java +++ b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java @@ -1,29 +1,39 @@ package ru.mtusi.messenger.repository; -import org.springframework.data.domain.Pageable; +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 - and (:cursorCreated is null - or m.createdAt > :cursorCreated - or (m.createdAt = :cursorCreated and m.id > :cursorId)) order by m.createdAt asc, m.id asc """) List findPageByChat(@Param("chatId") UUID chatId, - @Param("cursorCreated") Instant cursorCreated, - @Param("cursorId") UUID cursorId, Pageable pageable); - long countByChatId(UUID chatId); + @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/service/ChatService.java b/src/main/java/ru/mtusi/messenger/service/ChatService.java index 92830a04..5bb6ff8b 100644 --- a/src/main/java/ru/mtusi/messenger/service/ChatService.java +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -16,7 +16,6 @@ import ru.mtusi.messenger.model.User; import ru.mtusi.messenger.repository.ChatRepository; import ru.mtusi.messenger.util.CursorCodec; -import java.time.Instant; import java.util.*; @Service @@ -54,7 +53,7 @@ public class ChatService { } @Transactional(readOnly = true) - public ChatDTO getChat(UUID caller, UUID chatId) { + public ChatDTO getChatDTO(UUID caller, UUID chatId) { Chat chat = chatRepository.findById(chatId) .orElseThrow(() -> new NotFoundException("Chat not found")); @@ -68,7 +67,8 @@ public class ChatService { public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { int size = (limit == null) ? 50 : limit; CursorCodec.Cursor decoded = parseChatsCursor(cursor); - List rows = chatRepository.findPageByMember(userId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); + List rows = (decoded == null) ? chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)) + : chatRepository.findPageByMemberAfterCursor(userId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1)); return buildPage(rows, size); } @@ -83,14 +83,6 @@ public class ChatService { return decoded; } - private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) { - return cursor == null ? null : cursor.boundary().createdAt(); - } - - private UUID boundaryId(CursorCodec.Cursor cursor) { - return cursor == null ? null : cursor.boundary().id(); - } - private ChatPageDTO buildPage(List rows, int size) { List items = rows.stream() .limit(size) @@ -114,4 +106,15 @@ public class ChatService { private CursorCodec.PageBoundary boundaryOf(Chat chat) { return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); } + + @Transactional(readOnly = true) + public Chat getChat(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; + } } diff --git a/src/main/java/ru/mtusi/messenger/service/HealthService.java b/src/main/java/ru/mtusi/messenger/service/HealthService.java new file mode 100644 index 00000000..3269338c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/HealthService.java @@ -0,0 +1,31 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.exception.ServiceUnavailableException; + +@Service +@RequiredArgsConstructor +public class HealthService { + + private final JdbcTemplate jdbcTemplate; + + public HealthDTO readiness() { + try { + jdbcTemplate.queryForObject("SELECT 1", Integer.class); + } catch (Exception e) { + throw new ServiceUnavailableException("Database unavailable"); + } + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } + + public HealthDTO liveness() { + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/MessageService.java b/src/main/java/ru/mtusi/messenger/service/MessageService.java index 2559a19c..637862e7 100644 --- a/src/main/java/ru/mtusi/messenger/service/MessageService.java +++ b/src/main/java/ru/mtusi/messenger/service/MessageService.java @@ -6,8 +6,8 @@ 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.AppProperties; -import ru.mtusi.messenger.dto.ChatDTO; +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; @@ -19,10 +19,8 @@ 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.repository.UserRepository; import ru.mtusi.messenger.util.CursorCodec; -import java.time.Instant; import java.util.List; import java.util.UUID; @@ -38,11 +36,11 @@ public class MessageService { private final AppProperties appProperties; @Transactional - public MessageDTO createMessage(UUID senderId, UUID chatId, MessageDTO messageDTO) { - ChatDTO chatDTO = chatService.getChat(senderId, chatId); - validateCreate(chatId, messageDTO); + public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO createMessageDTO) { + Chat chat = chatService.getChat(senderId, chatId);; + validateCreate(chatId, createMessageDTO); User sender = userService.getReferenceUserById(senderId); - Message message = buildMessage(messageDTO, sender, chatDTO); + Message message = buildMessage(createMessageDTO, sender, chat); try { message = messageRepository.saveAndFlush(message); } catch (DataIntegrityViolationException e) { @@ -53,7 +51,7 @@ public class MessageService { return messageMapper.toMessageDTO(message); } - private void validateCreate(UUID chatId, MessageDTO dto) { + private void validateCreate(UUID chatId, CreateMessageDTO dto) { if (dto.getText() == null || dto.getText().isBlank()) { throw new InvalidRequestException("Empty text"); } @@ -62,9 +60,9 @@ public class MessageService { } } - private Message buildMessage(MessageDTO messageDTO, User sender, ChatDTO chatDTO) { - Message message = messageMapper.toMessage(messageDTO); - message.setChat(chatMapper.toChat(chatDTO)); + private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) { + Message message = messageMapper.toMessage(createMessageDTO); + message.setChat(chat); message.setSender(sender); return message; } @@ -72,9 +70,10 @@ public class MessageService { @Transactional(readOnly = true) public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) { int size = (limit == null) ? 50 : limit; - chatService.getChat(userId, chatId); + chatService.getChatDTO(userId, chatId); CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId); - List rows = messageRepository.findPageByChat(chatId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); + 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); } @@ -89,14 +88,6 @@ public class MessageService { return decoded; } - private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) { - return cursor == null ? null : cursor.boundary().createdAt(); - } - - private UUID boundaryId(CursorCodec.Cursor cursor) { - return cursor == null ? null : cursor.boundary().id(); - } - private MessagePageDTO buildPage(List rows, int size, UUID chatId) { List items = rows.stream() .limit(size) diff --git a/src/main/java/ru/mtusi/messenger/service/SessionService.java b/src/main/java/ru/mtusi/messenger/service/SessionService.java index 652a65cc..54be3c4a 100644 --- a/src/main/java/ru/mtusi/messenger/service/SessionService.java +++ b/src/main/java/ru/mtusi/messenger/service/SessionService.java @@ -2,40 +2,52 @@ 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.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.mtusi.messenger.config.SessionProperties; +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.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.UUID; +import java.util.concurrent.ExecutorService; @Slf4j @RequiredArgsConstructor @Service public class SessionService { + private static final String SESSIONS = "sessions"; + private final TokenGenerator tokenGenerator; + private final TokenHasher tokenHasher; private final SessionProperties sessionProperties; private final SessionRepository sessionRepository; + private final SessionMapper sessionMapper; + private final CacheManager cacheManager; + private final ExecutorService cacheEvictExecutor; + @Transactional public SessionDTO createSession(UserDTO userDTO) { String token = tokenGenerator.generate(); Session session = sessionRepository.save(buildSession(userDTO,token)); - return toSessionDTO(session, token, userDTO); + return sessionMapper.toSessionDTO(session, token, userDTO); } + @Cacheable(value = SESSIONS, key = "@tokenHasher.hash(#token)") @Transactional(readOnly = true) public SessionRecord requireActive(String token) { - Session s = sessionRepository.findByTokenHash(sha256(token)) + Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token)) .filter(x -> x.getRevokedAt() == null) .filter(x -> x.getExpiresAt().isAfter(Instant.now())) .orElseThrow(() -> new UnauthorizedException("Invalid or expired session")); @@ -46,35 +58,29 @@ public class SessionService { public void revoke(UUID sessionId) { sessionRepository.findById(sessionId).ifPresent(s -> { if (s.getRevokedAt() == null) { - s.setRevokedAt(Instant.now()); + s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)); } + String key = tokenHasher.hash(s.getTokenHash()); + cacheEvictExecutor.submit(() -> { + try { + Cache cache = cacheManager.getCache(SESSIONS); + if (cache != null) { + cache.evict(key); + } + } catch (RuntimeException e) { + log.warn("Cache EVICT failed (sessions): {}", e.getMessage()); + } + }); }); } - private static 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); - } - } - private Session buildSession(UserDTO userDTO, String token) { Session session = new Session(); session.setUserId(userDTO.getId()); - session.setTokenHash(sha256(token)); - session.setExpiresAt(Instant.now().plus(sessionProperties.ttl())); + session.setTokenHash(tokenHasher.sha256(token)); + session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS)); return session; } - private SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO) { - return new SessionDTO() - .token(tokenRaw) - .tokenType(SessionDTO.TokenTypeEnum.BEARER) - .expiresAt(session.getExpiresAt()) - .user(userDTO); - } - public record SessionRecord(UUID sessionId, UUID userId) {} } \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenHasher.java b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java new file mode 100644 index 00000000..c63ea7f6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +@Component("tokenHasher") +public class TokenHasher { + + public byte[] sha256(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 not available", e); + } + } + + public String hash(String token) { + return toHex(sha256(token)); + } + + public String hash(byte[] bytes) { + return toHex(bytes); + } + + private String toHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 06c40e97..29c9d928 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -14,6 +14,13 @@ spring: url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger} username: ${SPRING_DATASOURCE_USERNAME:messenger} password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only} + hikari: + connection-timeout: 2000 + validation-timeout: 1000 + maximum-pool-size: 10 + minimum-idle: 2 + idle-timeout: 60000 + max-lifetime: 1800000 jpa: hibernate: ddl-auto: validate @@ -26,6 +33,12 @@ spring: 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} @@ -51,6 +64,15 @@ app: 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: -- 2.54.0 From e64b104796ebfc571b243ba69a310733fdd3e7ac Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 8 Oct 2026 15:39:19 +0300 Subject: [PATCH 3/7] fix RedisConfig --- .dockerignore | 1 + Dockerfile | 13 +++-- REPORT.md | 52 +++++++++++++++--- build.gradle | 4 ++ .../04-compose-ps-before.txt | Bin 0 -> 1044 bytes .../06-compose-ps-after.txt | Bin 0 -> 1202 bytes .../07-gitignore.txt | Bin 0 -> 478 bytes .../01-redis-keys.txt | Bin 0 -> 6 bytes .../02-redis-ttl.txt | Bin 0 -> 104 bytes .../mtusi/messenger/config/RedisConfig.java | 8 +-- .../messenger/config/SecurityConfig.java | 1 + src/main/resources/application.yaml | 10 +++- 12 files changed, 72 insertions(+), 17 deletions(-) create mode 100644 evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt create mode 100644 evidence/lab2/level3-2026-10-08_65bd58c/06-compose-ps-after.txt create mode 100644 evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt create mode 100644 evidence/lab2/level4-2026-10-08_65bd58c/01-redis-keys.txt create mode 100644 evidence/lab2/level4-2026-10-08_65bd58c/02-redis-ttl.txt diff --git a/.dockerignore b/.dockerignore index bc16e556..796eb7ed 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +!gradle-9.7.1-bin.zip \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index e9438fbb..20085dbd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,20 @@ 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 ./ -RUN ./gradlew dependencies --no-daemon +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 ./gradlew bootJar -x test --no-daemon +RUN gradle bootJar -x test --no-daemon -FROM eclipse-temurin:21-jre-alpine AS runner +FROM eclipse-temurin:21-jre-jammy AS runner WORKDIR /app -RUN addgroup -S spring && adduser -S spring -G spring +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 diff --git a/REPORT.md b/REPORT.md index e42f2b05..6f5fd99a 100644 --- a/REPORT.md +++ b/REPORT.md @@ -11,16 +11,54 @@ TODO: версии runtime/образов, prerequisites, команды соз ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Схема процессов/хранилищ: +Клиент → API (Spring Boot 4, Java 21) → PostgreSQL 16. На уровне 4 добавлен Redis 7.4 как кэш активных сессий. +Все три сервиса в одном compose.yaml, объединены сетью messenger-net, volumes — pgdata и redisdata. +Источник истины: +PostgreSQL. Пользователи, чаты, участники, сообщения и сессии хранятся в нём. Redis (уровень 4) — производное хранилище, кэш. +При расхождении верим Postgres. При недоступности Redis приложение продолжает работать через Postgres. + +Транзакционные границы: +ChatService.createChat — @Transactional: вставка в chats + N вставок в chat_members. При ошибке любого INSERT — откат целиком (проверено rollback-сценарием). +MessageService.createMessage — @Transactional: ACL-проверка, COUNT лимита, INSERT messages. +SessionService.createSession — @Transactional: INSERT sessions + запись в Redis-кэш. +requireActive, listChats, listMessages — @Transactional(readOnly = true). + +Ограничения: +Кэш сессий в Redis не инвалидируется по TTL-истечении Postgres-записи — только по expiresAt при чтении. +При жёстком рассинхроне максимум до SESSION_TTL_SECONDS может висеть «протухшая» копия. +Keyset-пагинация в JPQL транслируется в OR-условие — индекс используется как диапазон только в native-варианте. +Один узел Postgres, без репликации; RPO = время с последнего pg_dump. + +Перенесено из lab1: +модель чатов и сообщений, CRUD-эндпоинты, структура DTO. + +Изменено в этой работе: +состояние переехало в Postgres (вместо in-memory), добавлены Flyway-миграции, аутентификация переведена с X-User-Id на Basic → Bearer с opaque-токеном, пароли хешируются BCrypt, на уровне 4 добавлен Redis для кэша сессий, на уровне 5 — исследование плана запроса и восстановления. + +Соответствие .env → конфигурации: +.env Куда попадает Роль +APP_ENV SPRING_PROFILES_ACTIVE профиль Spring +SESSION_TTL_SECONDS app.session.ttl TTL сессии и кэша +SESSION_STORE флаг выбора хранилища сессий postgres / redis +REDIS_COMMAND_TIMEOUT app.redis.command-timeout таймаут команды Lettuce +REDIS_CONNECT_TIMEOUT app.redis.connect-timeout таймаут TCP-connect +POSTGRES_* (secrets) SPRING_DATASOURCE_*_FILE креды БД через Docker secrets +SPRING_DATA_REDIS_HOST/PORT spring.data.redis.* адрес Redis + +Секреты БД передаются через Docker secrets (/run/secrets/postgres_*), не через .env; .env содержит только неконфиденциальные параметры. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +|-----------------------------------|---------------------------------------------------|-----------------------|------------------------------------------------------------| +| Публичный smoke | py tests/smoke.py | PASS | evidence/lab2/level3-/03-smoke.log | +| Persistence | py tests/resilience.py --mode persistence | PASS | 05-persistence.log + 04/06-compose-ps | +| Структура и контракт | py scripts/check_contract.py; validate_openapi.py | PASS | 01-check.log, 02-validate.log | +| Секреты не в Git | git check-ignore | 4 пути игнорируются | 07-gitignore.txt | +| Составная операция атомарна | @Transactional в ChatService | код в репо | src/main/java/ru/mtusi/messenger/service/ChatService.java | +| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | +| Выбранный трек 5, если заявлен | TODO | TODO | TODO | TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. diff --git a/build.gradle b/build.gradle index 8952432a..e28f457d 100644 --- a/build.gradle +++ b/build.gradle @@ -36,6 +36,10 @@ dependencies { implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' + implementation 'org.springframework.boot:spring-boot-starter-cache' + implementation 'org.springframework.boot:spring-boot-starter-aspectj' + + runtimeOnly 'io.netty:netty-transport-native-epoll::linux-x86_64' testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1' diff --git a/evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt b/evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt new file mode 100644 index 0000000000000000000000000000000000000000..518a09fb793561cb913eb215e62c34f61cbb3e1d GIT binary patch literal 1044 zcmcJMOHaa35QWd$#Q)HA;bT!1MNk$d1c+fF8Y=D;nu3-`EExIo$~UbFHav7eCUcqI zd*;lU!{Wly$uUWegSFf;DtQ)isRsX+Eq?J*ZCaw~7ikH8}1$m$Uf1 z*?UX=pQhNnJG3?F@wKZR^%W>40u2;$zRJ_1M(Qo_^)=Q6Oi!meAq$GYJW*w_E~qY@ zp4y!I@V%2(KhyC>+FMn7j!R{con?1rb$&@^GTDKuoLA-@(a6t2P@pdbJp(b?5h zhhIH8Sc^JhgEVt0>4GmyPgg(nF@0_LSGm(+^HfE8j!+fT6XKmIEh&dX=1i3MIN&x# zy6S*!>xCQh**qUpO~DP5ZO3Sf7u?CtGM??Ya}Mtr4sF`rcI=?l{t=7$cPVi9#p4%%xv(w!1I=6*3l%rV4Nhdm@}q&Vvo^PRdrzOmC1=+WI9 zc8HRB=lY-p?#Eax&`S{dd( z`2zBqYU@EAeFIh-wK)w3-7tZMc0Dv_SWWY-^?id^VEk%~E~h!;;GBgp*lJ zXJ7k6;u`SV+pX$OlgcB;XpY`8MBT_K&5_C8!4y~@1H2K^U-%2ryN5*0zzrNSMBDgV zcb0P*&;N8M1Md+X`mK7av58jew2k>W=enC-S-BzqUj3Xq%4PGW)vw0=^f!*(Upif= F{vE&ksI~wA literal 0 HcmV?d00001 diff --git a/evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt b/evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt new file mode 100644 index 0000000000000000000000000000000000000000..a341c0f12732d6b387b11f030d9ec7128a4911d0 GIT binary patch literal 478 zcmb7=y9&ZU5JgWd_zxl2DuRVyU~MB-0nsGH2gHz#kHT+P@6Mv65tC*aX6~K6XI{^O z0}T-=dvd)e#_AN5oT=4`nCLCJs&c0A-9~jnC5=;En9{M~Vwzf>hP& eh.authenticationEntryPoint(entryPoint)); diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 29c9d928..3f85cde9 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -49,12 +49,15 @@ management: endpoints: web: exposure: - include: health,metrics + include: health,metrics,caches endpoint: health: probes: enabled: true show-details: always + caches: + enabled: true + app: limits: @@ -76,4 +79,7 @@ app: logging: pattern: - console: "%d{ISO8601} %-5level [%X{requestId}] %logger{20} - %msg%n" \ No newline at end of file + 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 -- 2.54.0 From c744ee561316c947465342fd9f7cb8b195f15392 Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 8 Oct 2026 21:21:07 +0300 Subject: [PATCH 4/7] fix RedisConfig --- REPORT.md | 27 ++++++++++++------ .../01-redis-keys.txt | Bin 6 -> 0 bytes .../02-redis-ttl.txt | Bin 104 -> 0 bytes .../01-redis-keys.txt | Bin 0 -> 370 bytes .../02-redis-ttl.txt | Bin 0 -> 210 bytes .../05-db-down-live.txt | Bin 0 -> 402 bytes .../06-db-down-ready.txt | Bin 0 -> 496 bytes .../07-db-down-login.txt | Bin 0 -> 1066 bytes .../08-db-up-ready.txt | Bin 0 -> 402 bytes .../level4-2026-10-08_e64b104/09-race.txt | Bin 0 -> 1634 bytes .../level4-2026-10-08_e64b104/10-rollback.txt | Bin 0 -> 2896 bytes .../11-explain-first.txt | Bin 0 -> 2536 bytes .../12-explain-keyset-or.txt | Bin 0 -> 3094 bytes .../13-explain-keyset-tuple.txt | Bin 0 -> 2750 bytes .../14-explain-no-index.txt | Bin 0 -> 2828 bytes scripts/seed_10k.sql | 21 ++++++++++++++ 16 files changed, 39 insertions(+), 9 deletions(-) delete mode 100644 evidence/lab2/level4-2026-10-08_65bd58c/01-redis-keys.txt delete mode 100644 evidence/lab2/level4-2026-10-08_65bd58c/02-redis-ttl.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/01-redis-keys.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/02-redis-ttl.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/08-db-up-ready.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/09-race.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/10-rollback.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/11-explain-first.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/12-explain-keyset-or.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt create mode 100644 evidence/lab2/level4-2026-10-08_e64b104/14-explain-no-index.txt create mode 100644 scripts/seed_10k.sql diff --git a/REPORT.md b/REPORT.md index 6f5fd99a..fc122780 100644 --- a/REPORT.md +++ b/REPORT.md @@ -50,15 +50,24 @@ SPRING_DATA_REDIS_HOST/PORT spring.data.redis.* адрес Redi Секреты БД передаются через Docker secrets (/run/secrets/postgres_*), не через .env; .env содержит только неконфиденциальные параметры. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -|-----------------------------------|---------------------------------------------------|-----------------------|------------------------------------------------------------| -| Публичный smoke | py tests/smoke.py | PASS | evidence/lab2/level3-/03-smoke.log | -| Persistence | py tests/resilience.py --mode persistence | PASS | 05-persistence.log + 04/06-compose-ps | -| Структура и контракт | py scripts/check_contract.py; validate_openapi.py | PASS | 01-check.log, 02-validate.log | -| Секреты не в Git | git check-ignore | 4 пути игнорируются | 07-gitignore.txt | -| Составная операция атомарна | @Transactional в ChatService | код в репо | src/main/java/ru/mtusi/messenger/service/ChatService.java | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +|-----------------------------------|---------------------------------------------------|--------------------------------|-----------------------------------------------------------| +| Публичный smoke | py tests/smoke.py | PASS | evidence/lab2/level3-/03-smoke.log | +| Persistence | py tests/resilience.py --mode persistence | PASS | 05-persistence.log + 04/06-compose-ps | +| Структура и контракт | py scripts/check_contract.py; validate_openapi.py | PASS | 01-check.log, 02-validate.log | +| Секреты не в Git | git check-ignore | 4 пути игнорируются | 07-gitignore.txt | +| Составная операция атомарна | @Transactional в ChatService | код в репо | src/main/java/ru/mtusi/messenger/service/ChatService.java | +| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | +| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Redis с TTL, источник истины | keys + ttl | ключи sessions::*, TTL>0 | 01-redis-keys.txt, 02-redis-ttl.txt | +| Graceful degradation Redis | stop redis + smoke | PASS, Cache GET failed в логах | 03-redis-down-smoke.log | +| Expiry TTL=5 | SESSION_TTL_SECONDS=5 | 200 → 401 | 04-expiry.log | +| Readiness 503 при мёртвой БД | stop db + curl | live=200, ready=503 | 05-06-db-down-*.txt | +| Логин 503 при мёртвой БД | stop db + login | 503 unavailable | 07-db-down-login.txt | +| Гонка регистрации | 2× POST /users | 201 + 409 | 09-race.txt | +| Rollback | чат с фиктивным member | 404 + count=0 | 10-rollback.txt | +| EXPLAIN 10k+ | EXPLAIN (ANALYZE, BUFFERS) | Index Scan | 11-14-explain-*.txt | +|-----------------------------------|---------------------------------------------------|--------------------------------|-----------------------------------------------------------| TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. diff --git a/evidence/lab2/level4-2026-10-08_65bd58c/01-redis-keys.txt b/evidence/lab2/level4-2026-10-08_65bd58c/01-redis-keys.txt deleted file mode 100644 index 49cc8ef0e116cef009fe0bd72473a964bbd07f9b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6 NcmezWkC%aq0RRg=0u=xN diff --git a/evidence/lab2/level4-2026-10-08_65bd58c/02-redis-ttl.txt b/evidence/lab2/level4-2026-10-08_65bd58c/02-redis-ttl.txt deleted file mode 100644 index f71aab7d440993a13ee2140852b6ffe8709fcfb9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 104 zcmW-X$qj%o3 zW7#n7!~&HXuel0sjdI7-)<`og6>6o4JoaBV=cDYZ?duvop+}Kl^zX)Z|kCy+WNHy-kl6IFDx!3%OPa+8f*m}viW>aNlabWSBt;$KhIOKiO=?cQ+U h9Gg1b#MGJ{3-(NzyZ^PPLsKUAB4Nyk87r1ieF1CIBj5l4 literal 0 HcmV?d00001 diff --git a/evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt b/evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt new file mode 100644 index 0000000000000000000000000000000000000000..68f2fd876d5503b297e894db284d5e0c00414d7e GIT binary patch literal 402 zcmYL_TWbPA4292gq5okS?4uWoLh-%Ow-%H>33c5aS?ko5cD;c5*VQkbrPz759%ZKk*GIMfNp#R$&s*5F8lXF(C zq0vxJ>bZBRMRrSYRgPVt%TylmF-vgK|BBe literal 0 HcmV?d00001 diff --git a/evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt b/evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b7c198c6c7474656928f009ce0652fab65fc590 GIT binary patch literal 496 zcmaKpPfx-?5XIlw#P47>dZQGmRp?n0Z+ak}Ok`=RU@B-^1%rHb^|xdEb0U+sJ2P)) zc4qeTBiD;+RqCqL8XPE6W9N#~X`+QLG)AtlkF?QDE%KyW$jYF?LBWmzwGUEhjtlbEtD&>sU9`Ie{~B|vFy%85p-#&N=XC!4ZVz9oKJN{{h)FzCrbxs+WoLJ2BPGn;N6T%C1NcOz VcoL$9!0{VfoA&S5QgRaWeF2_qPb>fc literal 0 HcmV?d00001 diff --git a/evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt b/evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt new file mode 100644 index 0000000000000000000000000000000000000000..94b5cace0ddeffbc4b51094655aba795d3fdcd09 GIT binary patch literal 1066 zcmaizTTc^V5Qg7t6aT|zL);SSw#9;4QWA(J-a)YO%7kpUAF!r$m$IBh{<`|iEKo}f zWb>Wo@Xow5vwwb9x>2OIa`sq-PF1PYTs7|t&M9A^u~P0qXUKxi(XJuOxCL#h&uiH> zU_E!7*LnrE`A#%k@=1A_Z_o^j5`9n$S)ywV$STn)QBAtguFCM5OomTlF6Wo(0MA9f zE$~jryN2ID9lj|sb2v5nc(w%z`t7V~|=<9o*g!qYekr+x&ofEy~Y-)4|-YIw%&1y14yRSWc)recezsB|k zl!)`CDl~m5VPkb}d6YA7w(zca6-aBBr;l}BbL6Ju#;f(;PBgg$x|M@nf%0@>7E_Sw z3;B;=@|l>;WJF$p2w!9JZ!UqpKlI#kvA0#{xm;rG*0rrS^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{o1hC43Kw-vd(+JVuqI8Ho;Fc zpc9R5p;0$EVE3qhU94rhMPv60#BDZ<`mq~bjk48g$q_Fjw(1~5_ru*tLeoh%?Jl5i=J1OWjr7!y+3gQD~zEmDoYU47o&ZaHme zBaI)7F`KiO+1c6Ixx90J{-|5aYWB$zyEMnFWesc7cc3`S(h_Uh7sfL?w+m0r^=Xc= z$5(^1Zm0BZ&V7bUCtuPx*zI^(O?%H=cVyumwZ#%YT+qMfO!)%vt$BykS zyN{u*BY%rlu>(7_IVgwBclb8!h*iUK=v()^n%C@uRjq3$LsY%8370e*-swW?!LPf* z`AaC0kidW9XO8<1Y|oy1p77GDe`m*2oV~VZUc<^jN?HqNW$3e39BJ9XI&1U&dDfN& zvr+!Io<*80waJ*7p!I71);tnR_#?lb)eXo<*)W&JrDp59z<@y`ktihBDr-Yedt=!1szHSynVhjBVrbZ69R|X!Mkb zby#xM9%4gh-}#P+k_4OXkrf}A)rcEK_5<#Jg-_qXS!7=^)+S%7L}in;^6;zAmoBRo zQJLeU;&8_9+dcm|B>fxh1v#wzl`lfR@A?-Cb^f=%-vWwA<-<9dbnYWu_@ElnVO1tK zazyzueGc@>u`a@Y$^JDQW$-4?`r0FM7kn<06(u;8tr>DcS#!mxdeZf`B%Vi-mf)3K z^}?^kTO?m_Q_I&RNuEn(&pL9?Xu|ytc<1Pa%))r(`Un4>GWr(C)+ecxS&vSR{10`b z2lpYGR#`iwb~ve8=lrXBREk&wV`VsjJ63_3zcF1^I_!o@{P&V)7xAgy|MZHko4fq@itFmR@!xc6I literal 0 HcmV?d00001 diff --git a/evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt b/evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt new file mode 100644 index 0000000000000000000000000000000000000000..0e49cdf266b506bd1dcaba837b405aa59c224a83 GIT binary patch literal 2750 zcmeH}ZBG+H5Xa}WiQi#Ej4jbNEe}O7CE=k)5(ESkF(#z8hoDd@*Ge^hcJ=q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|4CS(DvtDu4y9$+&TCok*CfLo}YkO`vxSx!DvQ!64 z+u-g3u0{@pooD#;foQ%WSzuq;y#kSkRH?w5kt?5RB&87T_2lZ8U9 z2aitgK&0}noX62u|44D&tDvaK5bo4F)H@?)C0hW;1&}od%|OY#VDm_J zko%5g$?+b*>qKgZSluhh@WXJ8$|!Zvys(>)uC0XG#lAkHqoMLwvkn4yIzBk zn?-q5Z`UoE=1=lXpU1Wf;N_Cumu=_1l^gaotzwJ$OpKE}umZ=KI0aH_w8(Fk(nCmS`xTJMe^Au-ms<2Psvbm$g6 zC63h2UG*){39_~6HdimLdmU8qg7+Q$Q$+o5D%{e#<*%vOc^{|4U&Vc}=p8osYHAFT Nan9w#_#cMW{s7XVY+nEX literal 0 HcmV?d00001 diff --git a/scripts/seed_10k.sql b/scripts/seed_10k.sql new file mode 100644 index 00000000..df3cf394 --- /dev/null +++ b/scripts/seed_10k.sql @@ -0,0 +1,21 @@ +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed', + '$2a$10$abcdefghijklmnopqrstuv', now()) + ON CONFLICT (username) DO NOTHING; + +INSERT INTO chats (id, title, created_at) +VALUES ('22222222-2222-4222-8222-222222222222', 'seed_chat', now()) + ON CONFLICT (id) DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id) +VALUES ('22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111') + ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), + '22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', + 'msg #' || g || ' ' || repeat('x', 1 + (random()*200)::int), + now() - (random() * interval '30 days') +FROM generate_series(1, 10000) g; \ No newline at end of file -- 2.54.0 From a7635cd486c8ab202443a0310c28496492234614 Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 8 Oct 2026 22:19:50 +0300 Subject: [PATCH 5/7] =?UTF-8?q?lab2:=20Postgres,=20Redis-=D0=BA=D1=8D?= =?UTF-8?q?=D1=88=20=D1=81=D0=B5=D1=81=D1=81=D0=B8=D0=B9,=20=D0=BC=D0=B8?= =?UTF-8?q?=D0=B3=D1=80=D0=B0=D1=86=D0=B8=D0=B8,=20=D0=BE=D1=82=D1=87?= =?UTF-8?q?=D1=91=D1=82,=20=D1=82=D1=80=D0=B5=D0=BA=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 215 +++++++++++++----- evidence/lab2/track2-2026-10-08_c744ee5/01.1 | 2 + .../02-explain-huge-first.txt | Bin 0 -> 2102 bytes .../03-explain-huge-or.txt | Bin 0 -> 3050 bytes .../04-explain-huge-tuple.txt | Bin 0 -> 2688 bytes .../05-explain-medium-first.txt | Bin 0 -> 2080 bytes .../06-explain-medium-or.txt | Bin 0 -> 3040 bytes .../07-explain-medium-tuple.txt | Bin 0 -> 2696 bytes .../08-explain-small-first.txt | Bin 0 -> 2062 bytes .../09-explain-small-or.txt | Bin 0 -> 5844 bytes .../10-explain-small-tuple.txt | Bin 0 -> 4040 bytes .../11-index-sizes.txt | Bin 0 -> 1804 bytes .../12-explain-index-a.txt | Bin 0 -> 2696 bytes .../13-explain-index-b.txt | Bin 0 -> 2680 bytes .../14-explain-index-c.txt | Bin 0 -> 2560 bytes evidence/lab2/track2-2026-10-08_c744ee5/15.1 | 3 + evidence/lab2/track2-2026-10-08_c744ee5/15.2 | 3 + evidence/lab2/track2-2026-10-08_c744ee5/16.1 | 1 + .../17-counts-before.txt | Bin 0 -> 1754 bytes .../18-dump-size.txt | Bin 0 -> 1780 bytes .../19-restore-time.txt | Bin 0 -> 1008 bytes evidence/lab2/track2-2026-10-08_c744ee5/19.1 | 1 + .../20-counts-after.txt | Bin 0 -> 1810 bytes .../21-sample-original.txt | Bin 0 -> 1550 bytes .../22-sample-restored.txt | Bin 0 -> 1566 bytes evidence/lab2/track2-2026-10-08_c744ee5/23.1 | 1 + .../lab2/track2-2026-10-08_c744ee5/README.md | 143 ++++++++++++ 27 files changed, 314 insertions(+), 55 deletions(-) create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/01.1 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/08-explain-small-first.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/10-explain-small-tuple.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/11-index-sizes.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/14-explain-index-c.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/15.1 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/15.2 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/16.1 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/17-counts-before.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/19.1 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/22-sample-restored.txt create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/23.1 create mode 100644 evidence/lab2/track2-2026-10-08_c744ee5/README.md diff --git a/REPORT.md b/REPORT.md index fc122780..b24951ec 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,84 +1,189 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Иванов Данил, БВТ2301 +- Целевая оценка: 5, выбранный трек: Трек 2 «План запроса и восстановление» +- Commit/PR: c744ee5 (дополнить ссылкой на PR после публикации) +- Использованные источники: документация Spring Boot 4, Spring Data Redis, Lettuce, PostgreSQL (EXPLAIN, pg_dump/pg_restore), Redis persistence. Помощь ИИ: Deep seek — консультации по миграции на Boot 4 (Jackson 3, flyway-starter, starter-aspectj), настройке Lettuce (нативный epoll), keyset-пагинации. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Prerequisites: Docker Desktop с запущенным engine (WSL2-бэкенд), Git, локальный `gradle-9.7.1-bin.zip` в корне проекта (для offline-сборки), Python 3.9+ для тестов. + +Запуск из чистого clone + +git clone url + +Secrets (Linux / macOS / Git Bash): +mkdir -p secrets +printf 'messenger' > secrets/postgres_db.txt +printf 'messenger' > secrets/postgres_user.txt +printf 'change-me-local-only' > secrets/postgres_password.txt + +Secrets (Windows PowerShell): +New-Item -ItemType Directory -Force secrets | Out-Null +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_db.txt", "messenger") +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_user.txt", "messenger") +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_password.txt", "change-me-local-only") + +.env: +cp .env.example .env +Отредактировать .env: APP_ENV=lab, SESSION_TTL_SECONDS=400, SESSION_STORE=postgres + +Gradle offline: +curl -L --retry 5 --retry-delay 10 -o gradle-9.7.1-bin.zip https://services.gradle.org/distributions/gradle-9.7.1-bin.zip + +Python venv (Linux): +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt + +Python venv (Windows): +py -m venv .venv +.venv\Scripts\python.exe -m pip install -r requirements-dev.txt + +Сборка и запуск: +docker compose --env-file .env up -d --build +docker compose --env-file .env ps +curl.exe -s http://localhost:8080/health/ready + +Публичные проверки: +py scripts/check_contract.py +.venv\Scripts\python.exe scripts\validate_openapi.py +py tests/smoke.py --base-url http://localhost:8080 + +Persistence (Linux): +py tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://localhost:8080 + +Persistence (Windows): +py tests/resilience.py --mode persistence --action-script scripts\restart.bat --base-url http://localhost:8080 + +Остановка: +docker compose --env-file .env stop +docker compose --env-file .env down -v + +Трек 2 (опционально): +Get-Content scripts\seed_track2.sql | docker compose --env-file .env exec -T db psql -U messenger -d messenger +docker compose --env-file .env exec db psql -U messenger -d messenger -c "ANALYZE messages;" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "SELECT count(*) FROM messages;" ## Архитектура и решения Схема процессов/хранилищ: -Клиент → API (Spring Boot 4, Java 21) → PostgreSQL 16. На уровне 4 добавлен Redis 7.4 как кэш активных сессий. -Все три сервиса в одном compose.yaml, объединены сетью messenger-net, volumes — pgdata и redisdata. +Клиент → API (Spring Boot 4, Java 21) → PostgreSQL 16. На уровне 4 добавлен Redis 7.4 как кэш активных сессий. Все три сервиса в одном `compose.yaml`, объединены сетью `messenger-net`, volumes — `pgdata` и `redisdata`. Источник истины: -PostgreSQL. Пользователи, чаты, участники, сообщения и сессии хранятся в нём. Redis (уровень 4) — производное хранилище, кэш. -При расхождении верим Postgres. При недоступности Redis приложение продолжает работать через Postgres. +PostgreSQL. Пользователи, чаты, участники, сообщения и сессии хранятся в нём. Redis — производное хранилище, кэш. При расхождении верим Postgres. При недоступности Redis приложение продолжает работать через Postgres. Транзакционные границы: -ChatService.createChat — @Transactional: вставка в chats + N вставок в chat_members. При ошибке любого INSERT — откат целиком (проверено rollback-сценарием). -MessageService.createMessage — @Transactional: ACL-проверка, COUNT лимита, INSERT messages. -SessionService.createSession — @Transactional: INSERT sessions + запись в Redis-кэш. -requireActive, listChats, listMessages — @Transactional(readOnly = true). +- `ChatService.createChat` — `@Transactional`: вставка в `chats` + N вставок в `chat_members`. При ошибке любого INSERT — откат целиком (проверено rollback-сценарием). +- `MessageService.createMessage` — `@Transactional`: ACL-проверка, COUNT лимита, INSERT messages. +- `SessionService.createSession` — `@Transactional`: INSERT sessions + запись в Redis-кэш. +- `requireActive`, `listChats`, `listMessages` — `@Transactional(readOnly = true)`. Ограничения: -Кэш сессий в Redis не инвалидируется по TTL-истечении Postgres-записи — только по expiresAt при чтении. -При жёстком рассинхроне максимум до SESSION_TTL_SECONDS может висеть «протухшая» копия. -Keyset-пагинация в JPQL транслируется в OR-условие — индекс используется как диапазон только в native-варианте. -Один узел Postgres, без репликации; RPO = время с последнего pg_dump. +- Кэш сессий в Redis не инвалидируется по TTL-истечении Postgres-записи — только по `expiresAt` при чтении. При жёстком рассинхроне максимум до `SESSION_TTL_SECONDS` может висеть «протухшая» копия. +- Keyset-пагинация в JPQL транслируется в OR-условие — индекс используется как диапазон только в native-варианте. +- Один узел Postgres, без репликации; RPO = время с последнего `pg_dump`. -Перенесено из lab1: -модель чатов и сообщений, CRUD-эндпоинты, структура DTO. +Перенесено из lab1: модель чатов и сообщений, CRUD-эндпоинты, структура DTO. -Изменено в этой работе: -состояние переехало в Postgres (вместо in-memory), добавлены Flyway-миграции, аутентификация переведена с X-User-Id на Basic → Bearer с opaque-токеном, пароли хешируются BCrypt, на уровне 4 добавлен Redis для кэша сессий, на уровне 5 — исследование плана запроса и восстановления. +Изменено в этой работе: состояние переехало в Postgres (вместо in-memory), добавлены Flyway-миграции, аутентификация переведена с `X-User-Id` на `Basic → Bearer` с opaque-токеном, пароли хешируются BCrypt, на уровне 4 добавлен Redis для кэша сессий, на уровне 5 — исследование плана запроса и восстановления. -Соответствие .env → конфигурации: -.env Куда попадает Роль -APP_ENV SPRING_PROFILES_ACTIVE профиль Spring -SESSION_TTL_SECONDS app.session.ttl TTL сессии и кэша -SESSION_STORE флаг выбора хранилища сессий postgres / redis -REDIS_COMMAND_TIMEOUT app.redis.command-timeout таймаут команды Lettuce -REDIS_CONNECT_TIMEOUT app.redis.connect-timeout таймаут TCP-connect -POSTGRES_* (secrets) SPRING_DATASOURCE_*_FILE креды БД через Docker secrets -SPRING_DATA_REDIS_HOST/PORT spring.data.redis.* адрес Redis +Соответствие `.env` → конфигурации: + +| `.env` | Куда попадает | Роль | +|-------------------------------|------------------------------|-------------------------------| +| `APP_ENV` | `SPRING_PROFILES_ACTIVE` | профиль Spring | +| `SESSION_TTL_SECONDS` | `app.session.ttl` | TTL сессии и кэша | +| `SESSION_STORE` | флаг выбора хранилища сессий | postgres / redis | +| `REDIS_COMMAND_TIMEOUT` | `app.redis.command-timeout` | таймаут команды Lettuce | +| `REDIS_CONNECT_TIMEOUT` | `app.redis.connect-timeout` | таймаут TCP-connect | +| `POSTGRES_*` (secrets) | `SPRING_DATASOURCE_*_FILE` | креды БД через Docker secrets | +| `SPRING_DATA_REDIS_HOST/PORT` | `spring.data.redis.*` | адрес Redis | + +Секреты БД передаются через Docker secrets (`/run/secrets/postgres_*`), не через `.env`; `.env` содержит только неконфиденциальные параметры. -Секреты БД передаются через Docker secrets (/run/secrets/postgres_*), не через .env; .env содержит только неконфиденциальные параметры. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -|-----------------------------------|---------------------------------------------------|--------------------------------|-----------------------------------------------------------| -| Публичный smoke | py tests/smoke.py | PASS | evidence/lab2/level3-/03-smoke.log | -| Persistence | py tests/resilience.py --mode persistence | PASS | 05-persistence.log + 04/06-compose-ps | -| Структура и контракт | py scripts/check_contract.py; validate_openapi.py | PASS | 01-check.log, 02-validate.log | -| Секреты не в Git | git check-ignore | 4 пути игнорируются | 07-gitignore.txt | -| Составная операция атомарна | @Transactional в ChatService | код в репо | src/main/java/ru/mtusi/messenger/service/ChatService.java | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | -| Redis с TTL, источник истины | keys + ttl | ключи sessions::*, TTL>0 | 01-redis-keys.txt, 02-redis-ttl.txt | -| Graceful degradation Redis | stop redis + smoke | PASS, Cache GET failed в логах | 03-redis-down-smoke.log | -| Expiry TTL=5 | SESSION_TTL_SECONDS=5 | 200 → 401 | 04-expiry.log | -| Readiness 503 при мёртвой БД | stop db + curl | live=200, ready=503 | 05-06-db-down-*.txt | -| Логин 503 при мёртвой БД | stop db + login | 503 unavailable | 07-db-down-login.txt | -| Гонка регистрации | 2× POST /users | 201 + 409 | 09-race.txt | -| Rollback | чат с фиктивным member | 404 + count=0 | 10-rollback.txt | -| EXPLAIN 10k+ | EXPLAIN (ANALYZE, BUFFERS) | Index Scan | 11-14-explain-*.txt | -|-----------------------------------|---------------------------------------------------|--------------------------------|-----------------------------------------------------------| +### Уровень 3 -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Критерий | Команда | Результат | Файл | +|-----------------------------|---------------------------------------------|---------------------|-------------------------------------------------------------| +| Публичный smoke | `py tests/smoke.py` | PASS | `evidence/lab2/level3-/03-smoke.log` | +| Persistence | `py tests/resilience.py --mode persistence` | PASS | `05-persistence.log` + `04/06-compose-ps` | +| Структура и контракт | `check_contract.py`, `validate_openapi.py` | PASS | `01-check.log`, `02-validate.log` | +| Секреты не в Git | `git check-ignore` | 4 пути игнорируются | `07-gitignore.txt` | +| Составная операция атомарна | `@Transactional` в `ChatService` | код в репо | `src/main/java/ru/mtusi/messenger/service/ChatService.java` | + +### Уровень 4 + +| Критерий | Команда | Результат | Файл | +|---------------------------------|------------------------------|-----------------------------------------------------------------|---------------------------------------------------------------| +| Redis с TTL, источник истины | `keys` + `ttl` | ключи `sessions::*`, TTL>0, value JSON `SessionRecord` | `01-redis-keys.txt`, `02-redis-ttl.txt`, `03-redis-value.txt` | +| Graceful degradation Redis | `stop redis` + smoke | PASS, `Cache GET failed` в логах, приложение читает из Postgres | `03-redis-down-smoke.log` | +| Expiry TTL=5 | `SESSION_TTL_SECONDS=5` | 200 → 401 через 6 сек | `04-expiry.log` | +| Readiness 503 при мёртвой БД | `stop db` + curl | live=200, ready=503 `unavailable` | `05-db-down-live.txt`, `06-db-down-ready.txt` | +| Логин 503 при мёртвой БД | `stop db` + login | 503 `unavailable` (не 500) | `07-db-down-login.txt` | +| Восстановление после `start db` | curl `/health/ready` | 200 | `08-db-up-ready.txt` | +| Гонка регистрации | 2× `POST /users` параллельно | 201 + 409 | `09-race.txt` | +| Rollback составной операции | чат с фиктивным `member_id` | 404 + count=0 | `10-rollback.txt` | +| EXPLAIN на 10k+ | `EXPLAIN (ANALYZE, BUFFERS)` | Index Scan, keyset не делает Seq Scan | `11-14-explain-*.txt` | + +### Уровень 5 — Трек 2 + +| Критерий | Команда | Результат | Файл | +|------------------------------|--------------------------------------|------------------------------------------------------------------------------|------------------------------------| +| 100k+ сообщений неравномерно | seed + count + GROUP BY | 116 011 / Huge 50k / Medium 5×5k / Small 250×100 | `track2-/01-seed.log` | +| EXPLAIN на 3 размерах | `EXPLAIN (ANALYZE, BUFFERS)` ×9 | OR деградирует линейно (30 514 буферов на 50k), tuple константен (54 буфера) | `track2-/02-10-explain-*.txt` | +| Сравнение индексов | A / B / C | A (8568 kB) — единственный корректный для tuple-keyset | `track2-/11-14-*.txt` | +| Стоимость записи | 3× INSERT 1000 строк, 4 vs 2 индекса | 4idx ~51 ms, 2idx ~23 ms (медиана) | `track2-/15-16-insert-*.log` | +| Backup → restore | `pg_dump -Fc` → `pg_restore` | RTO 1.98 сек, count и md5 совпали | `track2-/17-22-*.txt` | +| Сводка трека | markdown | гипотеза/методика/результаты/RTO/RPO | `track2-/README.md` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Hardware: Docker Desktop, Windows 11, 4 CPU, 16 GB RAM. Версии: PostgreSQL 16.15, Redis 7.4.11, Java 21, Spring Boot 4.1.1. Объём данных для трека 2: 116 011 сообщений, 263 чата, 49 пользователей. Прогрев: не делался (все измерения на горячем кэше `shared_buffers`). Повторы: 3 прогона для INSERT, взята медиана. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Воздействие | Что ожидали | Что наблюдали | Время восстановления / потеря | +|----------------------------------------|-----------------------------------------------------|---------------------------------------------------|------------------------------------------------| +| `stop redis` + smoke | приложение переживёт, `@Cacheable` уйдёт в Postgres | PASS, `Cache GET failed`, время ответа +0.5 сек | 0 (кэш восстанавливается при следующем чтении) | +| `SESSION_TTL_SECONDS=5`, sleep 6 | сессия истечёт | 200 → 401 | 6 сек — время TTL | +| `stop db` + `/health/live` | 200 (процесс жив) | 200 `{"status":"ok"}` | — | +| `stop db` + `/health/ready` | 503 `unavailable` | 503 `{"error":{"code":"unavailable"}}` | — | +| `stop db` + login | 503 `unavailable`, не 500 | 503 через ~4.2 сек (Hikari timeout 2s + overhead) | — | +| 2× `POST /users` с одинаковым username | 201 + 409 | 201 + 409 | — | +| Чат с несуществующим `member_id` | 404 + откат | 404 + `count(*)=0` | — | +| EXPLAIN keyset-OR на Huge (50k) | линейная деградация по позиции курсора | 30 514 буферов, 30 208 Rows Removed, 15.9 ms | — | +| EXPLAIN keyset-tuple на Huge | константа ~52 буфера | 54 буфера, 0.27 ms | — | +| 4 vs 2 индекса, INSERT 1000 строк | +10-30 ms с лишними индексами | 51 ms vs 23 ms (медиана) | — | +| `pg_dump` 35 МБ → `pg_restore` | RTO в секундах, полная сверка | RTO 1.98 сек, count и md5 совпали | потери = с момента последнего дампа | + +Гипотеза трека: keyset через JPQL-OR деградирует линейно; tuple-синтаксис константен; индекс `(chat_id, created_at, id)` оправдан; `pg_dump` даёт полное восстановление. + +Методика: см. `evidence/lab2/track2-/README.md`. + +Ограничения измерения: медиана по 3 прогонам (грубо); горячий кэш `shared_buffers`; один узел без конкурентной нагрузки; JPQL не генерирует tuple-синтаксис, в текущем коде — OR-вариант. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Что выдерживает приложение: +- Отказ Redis: чтение уходит в Postgres, запись сессий идёт напрямую в БД. Медленнее, но не падает. +- Отказ Postgres: `/health/ready` отдаёт 503, `/health/live` — 200, бизнес-запросы возвращают 503 `unavailable` вместо 500. Hikari `connection-timeout=2000ms` не даёт висеть клиенту 30 секунд. +- Рестарт API и БД без потери volumes: сессии и данные переживают (persistence-тест). +- Гонка регистрации и rollback составной операции: корректная обработка через unique constraint и `@Transactional`. + +Что не реализовано или учебное упрощение: +- Один узел Postgres, без репликации и failover БД. +- Кэш Redis не инвалидируется автоматически при TTL-истечении Postgres-записи — полагается на проверку `expiresAt` в `requireActive`. При жёстком рассинхроне возможно окно до `SESSION_TTL_SECONDS`. +- Keyset-пагинация в коде использует JPQL-трансляцию с OR — деградирует линейно на глубоких страницах. Обходной путь (native SQL с tuple) описан в отчёте трека 2, но в код не внесён: сохраняет совместимость с `@EntityGraph` для `Chat.members` и `@Cacheable` на `SessionService`. +- Backup — логический (`pg_dump`), не физический. Для production: `pg_basebackup` + WAL-архив + PITR. + +Подтверждено (гипотеза → результат): +- Graceful degradation Redis: PASS. +- Keyset OR деградирует линейно, tuple константен: доказано на 50k и 5k. +- Индекс `(chat_id, created_at, id)` оправдан: tuple-keyset за 54 буфера. +- Восстановление из `pg_dump`: count и md5 совпали, RTO 1.98 сек. + +Гипотеза (не проверено в этой лабе): +- На 500k+ сообщениях разница между OR и tuple станет критичной (секунды vs миллисекунды). Требует отдельного эксперимента. +- Параллельный restore (`pg_restore -j 4`) ускорит RTO пропорционально числу воркеров. Требует замера. +- WAL-архивирование даст RPO в секунды. Требует настройки `archive_mode` и хранилища. \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/01.1 b/evidence/lab2/track2-2026-10-08_c744ee5/01.1 new file mode 100644 index 00000000..47a0851f --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/01.1 @@ -0,0 +1,2 @@ +узнать актуальные ID чатов +docker compose --env-file .env exec db psql -U messenger -d messenger -c "SELECT id, title FROM chats WHERE title IN ('Huge chat', 'Medium chat 1', 'Small chat 1') ORDER BY title;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt b/evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ce327ed51249789dbc822ead816b112601e7411 GIT binary patch literal 2102 zcmeH|TW?Z96ouEbiT`2JG`3BI6k4=kFlj3)3DR0xwZ?=XP>U@WIbeD4x2xaYheHmv zHQFa1%w!HTd-iqBn$3^z9Szmig}NFmuo|kb5#I<&P=?XfKwtSiQ%{#J&CX?k-x;%w zW=9|Sj~o`pS}T$8~Mp*11}msJSGyDhFs;X3HlNWHaa|f20Gwa-F!+me(1%B{W&#cL56Gv=C_jS)_z}LSvUW2r8#&C@}R`*Ho*w z5U~3;zV&!1J!g=;S?eXni!vO_Y8xJ989CqW=rI;!G_KGo!?aEISN=99u&a!oY1+G9 zhjqrwDZkcPCLX6d_q&N_^Plx^4!@6X@O(+6p?4?qypdw(9)8al)&U}wu#LP^*lV-b zbnX>dhFdAC46n$TU7dH28S4gFw%7+eMp#+L3trKTevx#-q(3y#PI^I`*vq{o;xz6@ zfxOMqFiwxmVwa)X_#{Ks$ttazUat|Q#7#~8hSH2kXZQE)IP@+#;Lc(Olv1qu zQ*Svc*#glHKE}>><6?Qi!0R!rkK5bpI&$_Jiq2Q#NHmXMng3Hy-CxY9>sEQ*Xpy*y O)w=Hz-ozN$TmK2n*c>td literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt new file mode 100644 index 0000000000000000000000000000000000000000..7801096503c6fa8c56c826aac5fb44c8057012c6 GIT binary patch literal 3050 zcmeH}Yfn=_5QgWoiT`0kh%M1JrOMTmgiBEp1mvP(Oh_pQL7`wTQjNb|ecoA4IYrxO z;|F8R=A5%TJ3BKw^Uloq_VvgvtZwfuv8DxP7j|x!yjxI$6&Q&%>?7Y}JGC>X7O!c6 zZVZP3@Y`d(^t%$ux&Z~LdPON5aJLse8mJPUMS^rKOS{Hul zisze9Bq4$Sz-Iyd+qP-XoG0G2=J#wlCD==Q>K0aeQnFSAt3c1$I9z-71kN05-F1a; zeu&-$KUcPrm2Dc2mTZpqq)kCDG3GPx`#zWCO{^U*H`?>Na#M>_p9hQf$&&1lopB7G zrCjMZM|>4w*}vlcRQ&g$435kqcv$X5Pe_nwMGK&0jhL-DPNuNvF_;T@a>4H5!(d-{ zc8PO>PdCB!J7#qvFKmvZ{{?=2!?}m-3niBzz6P!utWT`t2q=(4O>ozC6ph(kyW>wl z%D*w5gIQ&t;t;cS!*8gX@qhgN9uOjx3#Vk!siRx9K^>sQssg@?_K2(~GRh#nNN&t= zq6xmFp+aSLJ$0Ri6YMzWx&UE;yAGBRh;yjWyOZH5UNzs?*B$6TejjJtZ_uB0b(%*;nui6{rER`gfu2U~i3e zKyHh(>R7?=)}`L3oh+^I2XLpgyzV-)y`jZ!>?Z;1CG+-qQDn&=kIRp9Uft#W88~nJ zUWTGO$zP*-UosWh)caGnbi~*W_I|d8WxcrU_dW7>=x(WxVg-)XqhKk9gk8L8(HgC**yb)!ii9lcc1^Pn~%~}WkHH<kv`%K=!!L@|CFlc99s0xm!8WbNq;bDt%#nM#P8=+i4Fh& literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt b/evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt new file mode 100644 index 0000000000000000000000000000000000000000..503b7af10c44b60efbf60fef95d87f68ac449351 GIT binary patch literal 2688 zcmeH}Yfn=_5QgWoiT`0kh%M1JEw=y$62Ph?2*^dmn2_2Y1ckP8T4{{GU47m;J#>rK zi1C9lW^?v3J2Sg;d-r_((zLcU?7by+X@ObWF04bJLJ3x)CDyW!j3;(x=T0pTXo0cM z*MPHWZ|FP7eSk}n2lN;0rmm}HZ<*_i61?Mfq-nxx_R@B2(^hT6wxAT5ZSif|k-cK~ z0kk#rKc>}e*Y<1*${zDgzIEGYbzx=h+jL&d8+K}S>)P=MRaUm((#=M9y3qRY>#R)v z5{fh=@E`juaQ?1s+cW3MEUmkpsZ)X-+Ec$_?OIEGi(t#p3pNSYfjxnjAIBww84Ugm;_jyQG1Z-Qedsr3hGv7XuNU(C7%zMYI zL2Q&glbrto%U>fm%f8~+At&oZzQy{~dLE+^{5{`E$d9f^d&2J89sdHl{)P6O%u3Bfb~Bt0+*>+t%8R19ALr)i$}<5s#}m9Qw=DPea$i+SUDfpeCKRL>)%JR81e zdMgk82H(G>deh?fEa$!LtESWQOjecDiDzdJ5mmr2&x3t(&m@2RB^>p@)JR>#QM!GN z?D#v@B6G7kSc+=rSG85i+xdaqO?`S*g*J(2OVz7ic%iCD2Qsz6KVQ%NoK;aQrR>#T R$YLZ_^i`hA8BPe@z5#9lTLb_A literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt b/evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt new file mode 100644 index 0000000000000000000000000000000000000000..9220bbaab7fe57c440a6420746852bd0e8491e10 GIT binary patch literal 2080 zcmeH|TTfF_5QW#XiT`1T5DSTIN-wlvFyT^TlL|;d#h8%Ni=eb%Pb+=!x2xaGZsC+b zB0l+Gc23Wn*)y|e)~r4K^|PZ(we?k94Hb|s)z=lj37ViRtE+*&^X}w_YEuaJmR;{ZsM^9`iyL6WU+l{$09ALrVrXzLz}8=7tIpVE>AXisn4CRW<=Iuq9fz1M5cuyzwAokh?F`ivHdP}2_89wBAW?Gbm!J+0E? z8}Iva*rf99n>?-N09K|8;87=H-4Q7(uNR;jRM1O3(+biLo|r_yws=jn;)l z&VQ$}KH*np-|)Diw=EDH@NK>AAditEJBD<61lA)*Zb47=#GgRCe`~!3X=9Ed8=1E2 znHt~!ug4=`oi?_e!-aF_kKJ0ECdP;j7?e{9-sMHL@=H_5WacOYVdm(9H36-}5JvspNs5GPpAra_yt z=ch};Zk$Mgye;Nkf74h758+$^VS5buGIqCEm(Ug+|G&k%GKY6*E_&?b!+57BK^nbn zue0MFu$pGr#EBLsWr4ga>=nqqtyS*o8a>LR%Ti^J-BYAfv^}(0EY|ocI`^vRj2)}6 zCBrG}bZP9}NwXoH-Q$_D@AGj$zhd{-Q;hl3Xe(Z0yis@K*|fGh)^(JO?^SBIo70DJ f(Wf^3PagX{iQKvCWhmG!nRzXN(=9_H9v1C4e()9O literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt new file mode 100644 index 0000000000000000000000000000000000000000..40ef58da972bf9c4fb0c20c0c46724c2f47ba3e4 GIT binary patch literal 3040 zcmeH}YflqV5QgWoiT~k*5L=>cdg0PyAVDaR1Od6I7!%SPf`Sy$2^)hSju|edc*=r*`Jt?2s3D z4!G(_Hmt_IgWe~kqgVh^C)jIy?jBaItR%e%wgf+A(^#n38mB#gO2N~4 z*LbEU?7i%|1;MH7WpSnl1qL@ zYcdr}#m^KuR+i=en#WWaID|7kJ1byf^(uoxgCZ+l04W>9dc(0YheuDrT_BRn_J|k; z`^L3TuA9Vk8*G1os*`=;bDI5M5$AX4De^)}2h>-=R*QF`z5(5b%1}#P@OR;8nzD!X zz^{O%e`CD_wW>npBC6UgKcRZZ|MmArK!{X5oPyRp_eqQ$-lk=g+*J!2$e3#8peR0$S#znh?&v`nG;$KGY zIw}R{|4z*FiI^9NOVWCj&G9i$_N`>}R{fj}&w|br$0q8$@mwjA^E!Acb658)lcyZK z45vIMPc^6-++(;IB+9%M9f2iy!qq(frr2eXEcHD*Nkk;QTj%Q;h!Z-5jkL%5wn=`U zX(|t5G^#rssmNQHP(ZD_1HA8X4oWO;z-?PvftO2cy6aXj(>h?-^`L`c+_u_ zSrWZVeAG)sHHl-Jf6l0aYxV{1XeL$9s*c;O-LEU`_zZ7Rt5M}ICanLe#XLw|80wAM x(;tPpY}2u*3M_iZQy=IJbt=O@>b@f@>Kmh4WzIcIOk%CHSH*P&M=@4pegcF_g)aaA literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt b/evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt new file mode 100644 index 0000000000000000000000000000000000000000..4337339074ebf4cd19b73ad7658f98f992932078 GIT binary patch literal 2696 zcmeH}YflqV5QgWoiT~k*5L=>cwk;IFK*FU)5(MNTVoXSB7eQ&Mw3WvA+tuft?b0n; zBhe4Wn3JsWgLlmjPw*LmkB z>Q3(^8)f~nQ|GK~5xa_)BU|8EvN=v7)?()Q(BYh0mvdMY=@M_Ueh#Hn={x5)*~Ta9 zZndIxg!ak)TOn#|H$IjvvR$}9EI07RhDURb`#d2t0=6yN1FQ=6nY~XmVyxUI``!UH zh>tR88vQS^{0)5boGX?c^0H3!+k7i8o4|db0z7>`jmeXqM}5lf+dba_dH=$CL2jv5 z6py5~w%k5d`2Y2HdqBCUdN?Or&ppG{8Pu!0d@YgVMVqBEimZ}V*hO+*b$_m13f|EI^`G?T0hD{(vd(uvVizvWl;9Q(=*a1;NjvZ{ z)M>YExVCKf?sA%R{J^~>^ESUQs{Bcwp2I6uZY`fwp&R+S?3my2x1<(5u8PsZnDiu) zll`6TR$1?@xt&dqK;ErNy_59aWEPc)!aTkyqqTuu1>Q~Wpe{N~6f1Pv0(${C0;&R? zfK~oI2B-X}0_D)NNSyi}A5EyyOw-If^c#FXQ#IGJGcBdP>tvJmG>=s!b)wlpwkkmR zKg#l8pWHL?AD@Qf9+(-cifokbULiX^%i82^QU!~d%K24ks^jXA@3uTmR&|@$vqg13 nPnFfS{rcO_X9vf*)1;VbjDM0V}N_T_3csrZ&~kE}BK8U1n3q`pE8c zbX)k}X4G|{LoJ~>L~b%`I%3sRo_O1S*5sDXm1v}s8Leg6=afY@yE8&J=Dgh%?T2X0 zLx=MxE(PvC(4KbuOw2U#JX6;Mz1M4xuzuqu8%0nR{etF+eaG`_vI=-S&?~pIJdbZ| z?~7m)+uBW(mT|z7=>ljp@Y`@aR#eanunk()OFdH&=?C+Od^*%*kNSNGuND|!ma}AYwX+DoTDi+ z3jUfGVV807%2^hW?557db3rAB`L=rsc(2^!`GT7+y(gLHr3@dp@O#Fvcb{ql+tmAm zy)b)0=blrQ_$wK!952VX+?e!?G4df%CaeP?7d1PCE_)t*R{&2TcjgCe~Wai;uPu9jOSRxhmp>{{VZ-Z&#>*- zTQ*ZvVh4+Tu}qCu$mEo7k(pyIQy=SBWin0B=EyZcK0{h#w}V{9rh;XQ^(w0cZrPwd zS6-Ja5384wKvm)Yw-ovC;z}# Z{z4*a?phVWz^XR2TEx#SJ0c$D?Kht06W9O% literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt new file mode 100644 index 0000000000000000000000000000000000000000..c92dd0a76c8a816615b765d21e70f94bdfa48655 GIT binary patch literal 5844 zcmeI0eNP)l5XR^4O8pM2C~6#~Mt;GLp(0WsR6*q>fuwD!O2{!zL%}w|(2%H~z3uO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6%#T2)!kpJzrf3p+u6p~?z!;`3!b21~tnz2`=p#yvT%jw%&U!Ruw86Xdkl cTUWcyFrUjrV--2?V>5v_r&L(MN66xT4(5Rq5C8xG literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt b/evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt new file mode 100644 index 0000000000000000000000000000000000000000..8743978946b2765afb139224e12e31bacb525724 GIT binary patch literal 2696 zcmeH}YimD+NN!z$suj?Y}v8B zVfGQaHT*wilx@%UZ3@jk@)pm!9q_AR1Bw~BS_WJs$hn^@^&!!sRpJ?ynt zSbvR19_rYixRkK}p6%ERw+WF}JkGXj5<9Zze!}vtm+UDLTSlMSBvyy^49k??igkl; zZtTACOo~sDuefz;B`fmGk>R2(@}9O?W{QlZ%=@9ssYjN&EQ>g_HjJN3(JFpZKgkaH z*zkx|p<{L*pSx8mwtkym#iH1yOQ_=}S>5zX&T^h7bVWjJEB1h>68pk)Kqcx#xkKl@ zN2*dAbEYRI!bf&z0lI-E3WSNKJ~s|amcKD)-K`@vB;?BOLn?)zL)2z406`+d&&@} zwqc%xw^&d7DU6?cL^|P2W>wxzb_T;zPJSLsmpR7&zW7k#SG3j_g|X z-Lh=mW;QTgNZ`~uUc@1(NSIkdf+i?3-$Z>Xv6~o9=p(rifN^y4do3hUmmFjwhbT18VGTo9# zeu5uwQQc-bPrS*Z?OpFP?H)T>D5+4-R=*-bz@X0)`|O#i|M5F;I0I8dxX4!N?ikti z8>~s^1{^G9u=A_lgyqm#`X^HZ@1?$%QSZ84#XWWJoxm@1&I1jQ7}%){3U%vtJ?jBe Z*;QhXl0Bw}gsiYC=NO5d9aux&z609tTigHu literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt b/evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt new file mode 100644 index 0000000000000000000000000000000000000000..377bd90a8ba870acb41208b46f74170b23f75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? z>Z-1)?*4nK=J~0qz5?B-rBH@hUtJC05f&p4YN@AtWLsCdb=KU}W{_h>fM-(;_<*=O zylmtNyvu6ja`n_nWq_n67&itEk8o4(J z;a?%-X`5FZaQ~irr@x9=piB9@{y$>zTI}*oRH(xUWJ3CZt?CPK>OdLvrZ%A=UyrSv z6)G+bPa~_;>>jmOW4@y^xb@D?Smc`6%N@=)1XO5C#u*(}MZy#S?Q04e|g literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt b/evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt new file mode 100644 index 0000000000000000000000000000000000000000..90ae2d1368630a2f0cd3c430cce948c54e413fa9 GIT binary patch literal 1780 zcmd^<$xZ@65QhH)CljB*%Y=BHVG#s5qsEAOLA{U|90nbcB`_K^KD+vL51ScKj5kcD zyDGK(wRBg1ytmYsuZ{u@<-qmT)qrz^#F5Ji)YCJxtx%6v>P=)0bj(J} zSBJV%QH^i2OUvYUOyv91t46|>jyX=q^~GBmC;Z8@6z*7uUL9m zj@fZ0CL3q6s#pvsSbew`RnSy98`?=_Q@PY>s=@6yiJ7-`M%=E!%`3~^U(f}-mXPS? z-T0h~ei7JBq#bdHu2xGUW_EtW=P^rH&=Gs r%!6lV!<)^@yz)Gn3KO!IxTONp116|sy_WsF^FMQrx5?b}2Ql;$&MLz7 literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt b/evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt new file mode 100644 index 0000000000000000000000000000000000000000..31b3c5278a3be7736476fa9158775bae864d6bc0 GIT binary patch literal 1008 zcmaKqOHaZ;6ot>)#Q)F`S5N9G)m&3{zRoq)h|yD`zC3;EPzS8p=yMzE4dj%Q*kLEkDJLG;K5L?P z)@Kbgbf=Z&na8>yVuy^F`+8)a=tU2%da4;*ro*^ynMdqX$DV-7s`^gX_RTg&6}}Pt z)g3$)Smy55-uF$dy3Ta08oMtdqMG?}jmB4YF-IqnT(t_j z1yOSTS&a)k{Q$f2a@TswZQwGlaKd`B51*sER87FooSI$Co^te!d(YT)xQO4-HK)Y5 zhm3*igZ12g#(JKiLv@zgBe3>M)-mg)&Y8B_B1-4bEa$jWd8VaHC0P0Cz(t8w|xx=L{!g1t@C3viYiF?=wfrOCNW8QrwFy OJM*(l)!b2YbrpX(=Z5b9 literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/19.1 b/evidence/lab2/track2-2026-10-08_c744ee5/19.1 new file mode 100644 index 00000000..674d4943 --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/19.1 @@ -0,0 +1 @@ +docker compose --env-file .env exec db psql -U messenger -d postgres -c "CREATE DATABASE messenger_restore;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt b/evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b4eb6f50c30d385daf98c3073d3fe43e8710e33 GIT binary patch literal 1810 zcmeH|TT22_5Xb+|LEmAKK#f+sc75vlR0w845Qwg3H!rzs`Os&tesfeb*b1_zkm1an znKNf*XU@#*`&&~z1$t0R19|Lv>ZlJ6k$Ccfmb!X|-snz`PMVp>Jm`oOpxIOd+~?jC zT6XgS+~G8Iwz_JwHy=K_aVIrSO*_K7?M%}wCv>i3ow5#9g|}}U@=cLaT2~s$i7G1V zjNQ~<-FXYO$8ArqtSS~;SS<6M_v`}ho9#91UaF*P<&||Fr`AKbI#EYx50rt9SP89a zg$Vvr)`sqd2H>CaYQYq0gf7HcSUE85vN_4FC_kc-a^Poo7 z+CU1vsa?Q&&AMy@J4tX7TBf^?=+X-N16_elJH24%|5YX1G?<@B#@p1Khp|phIc+jy zjG80`^~gm}FT`S!vEFRHc}_BK$)D(W-1Jn`j^h`#l;^t&-&z{`i^t=ajX#@7Ew;~* r{EnOEsID!lCreEQ&~29soACA@vXkP3Hjre2qLUPeGY^=R_^f>ZWt9vX literal 0 HcmV?d00001 diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt b/evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt new file mode 100644 index 0000000000000000000000000000000000000000..1105f116fbce21657df0382a6dbb980c18f33fcb GIT binary patch literal 1550 zcmb`H?N1Xy5XPU+CjJi_Bte7MwD$s6j9+|(1k(gTV`4&%yK6;h3zTR-@VBeKnO3W& z?R}7JW_NaWX7+h@=I+P$N@JD!qFUDqXk!g^$vnXl6ftUz^p&-*b6vQ#HMa%UDN^ED z>5Tc3xGTIY@`QQF>BMu5G(fjIB79e!Sf&lV)k_^B&vnfH9RJ6xH-6iV>m`|L6>h6^ z>RQk%9jT``e`GKG)(MvP+9%@?Vk|#-#Hr^FdWvmJn|Pe)H6B~+d-%Tah@fZs;8Dx& zJk$X<9yroOPe31ZiyVWmhHH;^`HWVA)wpev^PMt%RICo?6Oh=8+sj70`!$#b$O!v| zT0~8e4c*s0mq3=LVK3I?W9NpmY5aQiCcoABmetDGSa03c*uJw&GerNJ&-mFl5o?FK zw)u8aB%&7*EM2se`ev@>tQq|gVQFiZn1o%aO3K7sC7HP%(k zDj##3;fq*vpSxH)=zETGHn-S!K-C6gs%_Txybq0w;V3ybH1?T#syLKPc$@(+9lkRBJmP->ngT5Yhssj{~luOa)xzL29`zb S9~7km;)_~sp%SRAA_!r-o7AdlswtX>es=YDCaJ-Y zWFIWUow;-W%$zg#?*9H&X{=ITG|+cNXk(3Z#XP|hDP|0GsUNIEUFd7DHs`j8b&8Zk zRyt$8BJUef&OBuv;hluDE_IIXJ7Qv2dHQ%Aea-FG9O;uAdaHdMAun{o{(}4`tk=X$ znXQ*0qX@Q2eOZh2O2_Ky4caY^BA}RHd9MRbJVu=TDP;7+*^!=M+tNcKPW76IE%rTP zUxtiG&-Ec>8RhbwM>^!j!+z&&AsFV@IzX%oZ zOUFwuQmILnIX84)_ku*6T{rwhnU0F?98zZvnIE6z_iP*`wzPUjAmEh9}*F> zrbPKG&Eafu#Rjl (?, ?) использует B-tree как диапазон и даёт константную стоимость. +2. Индекс (chat_id, created_at, id) оправдан для keyset, но не бесплатен — каждый дополнительный индекс увеличивает стоимость записи. +3. Логический дамп (pg_dump -Fc) позволяет полностью восстановить БД в новое хранилище с проверяемым RTO. + +Профиль данных + +- Сообщений: 116 011 +- Чатов: 263 +- Пользователей: 49 +- Распределение: Huge chat 50 000, seed_chat 10 000, 5 Medium по 5 000, 250 Small по 100 +- Размер таблицы messages: 15 МБ +- Размер индекса idx_messages_chat_created_asc_id: 8 568 kB +- Размер индекса messages_pkey: 4 376 kB +- Размер БД messenger: 35 МБ + +Методика + +EXPLAIN + +Для трёх чатов разного размера (Huge 50k, Medium 5k, Small 100) сняты три варианта плана: + +1. first page — ORDER BY created_at, id LIMIT 50 без курсора. +2. OR-keyset — как генерирует Hibernate из JPQL: (created_at > X OR (created_at = X AND id > Y)). +3. tuple-keyset — как должно быть: (created_at, id) > (X, Y). + +Команда: EXPLAIN (ANALYZE, BUFFERS) SELECT ... + +Метрика: Buffers: shared hit — сколько страниц (индексных + heap) реально прочитано. Это устойчивее, чем Execution Time, который зависит от кэша. + +Сравнение индексов + +Созданы два альтернативных индекса: + +- A (текущий): (chat_id, created_at ASC, id ASC) — 8 568 kB. +- B: (chat_id, created_at ASC) — 4 384 kB. +- C: (chat_id, id) — 5 368 kB. + +Для каждого — EXPLAIN с tuple-запросом (или эквивалентным для его колонок). После замера индексы удалены. + +Стоимость записи + +3 прогона INSERT 1000 сообщений с 4 индексами, 3 прогона с 2 индексами. Взята медиана. Разница — цена двух лишних индексов. + +Backup и restore + +1. Контрольные точки: count(*) по messages, users, chats; md5(string_agg(id, ',')) по messages. +2. pg_dump -Fc в файл. +3. CREATE DATABASE messenger_restore. +4. pg_restore с таймером (Measure-Command). +5. Сверка count и md5. +6. Выборочная сверка: 3 сообщения по конкретному чату. +7. DROP DATABASE. + +Результаты + +EXPLAIN (ANALYZE, BUFFERS) + +| Чат | Размер | Запрос | План | Buffers | Rows Removed | Time | +|--------|----------|---------|-------------------------|-----------|---------------|---------| +| Huge | 50k | first | Index Scan | 53 | 0 | 0.23 ms | +| Huge | 50k | OR | Index Scan + Filter | 30 514 | 30 208 | 15.9 ms | +| Huge | 50k | tuple | Index Scan + Index Cond | 54 | 0 | 0.27 ms | +| Medium | 5k | first | Index Scan | 52 | 0 | 0.17 ms | +| Medium | 5k | OR | Index Scan + Filter | 3 048 | 3 001 | 1.9 ms | +| Medium | 5k | tuple | Index Scan + Index Cond | 53 | 0 | 0.18 ms | +| Small | 100 | first | Index Scan | 28 | 0 | 0.14 ms | +| Small | 100 | OR | Bitmap Heap + Sort | 27 | 0 | 0.48 ms | +| Small | 100 | tuple | Bitmap Heap + Sort | 24 | 0 | 0.24 ms | + +Вывод 1. OR-keyset деградирует линейно: 50k → 30 514 буферов, 5k → 3 048 буферов. Отношение 10×. Tuple-keyset константен: 54 и 53 буфера. Разница ×565 и ×57 соответственно. + +Вывод 2. На мелких чатах (100 строк) Postgres выбирает Bitmap Heap Scan + Sort вместо Index Scan — планировщик сам решает, что индекс на маленькой выборке не окупается. + +Сравнение индексов + +| Индекс | Определение | Размер | Buffers (Huge, tuple) | +|----------|---------------------------|----------|------------------------| +| A | (chat_id, created_at, id) | 8 568 kB | 54 | +| B | (chat_id, created_at) | 4 384 kB | 53 (по created_at) | +| C | (chat_id, id) | 5 368 kB | 50 (по id) | + +Вывод. Все три индекса дают keyset за ~53 буфера. Но B не может разорвать ties по created_at (два сообщения с одной миллисекундой могут дублироваться или пропускаться при пагинации), C сортирует по UUID вместо времени. Только A даёт стабильный tuple-keyset (created_at, id). Дополнительные 4 МБ оправданы корректностью. + +Стоимость записи + +| Конфигурация | Прогоны (ms) | Медиана | +|----------------|--------------------|----------| +| 4 индекса | 89.4 / 51.5 / 38.8 | ~51 ms | +| 2 индекса | 23.6 / 22.9 / 23.2 | ~23 ms | + +Вывод. Дельта ~28 ms на 1000 строк = ~28 µs/строка за два лишних индекса = ~14 µs за индекс. На учебном объёме это незаметно, но при высоком RPS и больших таблицах каждый индекс должен быть обоснован конкретным запросом. + +Backup и restore + +| Метрика | Значение | +|-----------------------------------------|----------------------------------| +| Count before (messages / users / chats) | 116 011 / 49 / 263 | +| md5 id сообщений before | ca7a05ca849eedb7a4b7abd0044b3322 | +| Размер дампа (-Fc) | 4.6 МБ (сжатие ~8×) | +| RTO (restore) | 1.98 сек | +| Count after | 116 011 / 49 / 263 | +| md5 after | ca7a05ca849eedb7a4b7abd0044b3322 | +| Выборочная сверка (3 сообщения) | id/text/created_at совпали 1-в-1 | + +RTO и RPO + +RTO (Recovery Time Objective) + +Восстановление 35 МБ БД заняло 1.98 сек. Масштабируется ~линейно: 350 МБ → ~20 сек, 3.5 ГБ → ~3.5 мин. Для ускорения: pg_restore -j N (параллельный restore из custom format), больше CPU. На production обычно измеряется не в секундах, а в бизнес-требованиях (например, «восстановиться за 4 часа»), и достигается через реплику + PITR, а не только pg_dump. + +RPO (Recovery Point Objective) + +RPO = время с момента последнего pg_dump. Стратегии: + +| Стратегия | RPO | +|--------------------------|-------------| +| pg_dump раз в сутки | до 24 часов | +| pg_dump раз в час | до 1 часа | +| WAL-архивирование (PITR) | секунды | +| Синхронная репликация | ~0 | + +На учебном стенде RPO не определён (нет расписания дампов). Границы потери данных: + +- Всё, что появилось после последнего дампа — теряется. +- Незакоммиченные транзакции при краше — откатываются автоматически (WAL). +- synchronous_commit = off ускоряет запись, но может потерять последние ~200 мс закоммиченных транзакций при краше ОС или питания. + +Ограничения + +1. JPQL не генерирует tuple-синтаксис. Hibernate транслирует keyset в OR, что даёт линейную деградацию. Обходной путь — native SQL с (created_at, id) > (?, ?). В текущей реализации используется OR-вариант. +2. Тест на одном узле. Нет конкурентной нагрузки, нет параллельных writers, нет replication lag. +3. pg_dump — логический бэкап. На больших БД (десятки ГБ) полный restore занимает часы. Для production: pg_basebackup (физический) + WAL-архив + PITR. +4. Замеры INSERT проведены на горячем кэше с shared_buffers по умолчанию (~128 МБ). На больших объёмах пропорции индексов могут отличаться. +5. Медиана по 3 прогонам — грубая. Для production-замеров нужно ≥10 прогонов и p95. \ No newline at end of file -- 2.54.0 From 30cf79907b7351c515ddcc878fecb5f7509deda0 Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Thu, 8 Oct 2026 22:32:26 +0300 Subject: [PATCH 6/7] =?UTF-8?q?lab2:=20Postgres,=20Redis-=D0=BA=D1=8D?= =?UTF-8?q?=D1=88=20=D1=81=D0=B5=D1=81=D1=81=D0=B8=D0=B9,=20=D0=BC=D0=B8?= =?UTF-8?q?=D0=B3=D1=80=D0=B0=D1=86=D0=B8=D0=B8,=20=D0=BE=D1=82=D1=87?= =?UTF-8?q?=D1=91=D1=82,=20=D1=82=D1=80=D0=B5=D0=BA=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REPORT.md b/REPORT.md index b24951ec..b8a2e4b1 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор, группа: Иванов Данил, БВТ2301 - Целевая оценка: 5, выбранный трек: Трек 2 «План запроса и восстановление» -- Commit/PR: c744ee5 (дополнить ссылкой на PR после публикации) +- Commit/PR: c744ee5 https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/23 - Использованные источники: документация Spring Boot 4, Spring Data Redis, Lettuce, PostgreSQL (EXPLAIN, pg_dump/pg_restore), Redis persistence. Помощь ИИ: Deep seek — консультации по миграции на Boot 4 (Jackson 3, flyway-starter, starter-aspectj), настройке Lettuce (нативный epoll), keyset-пагинации. ## Запуск из чистого clone -- 2.54.0 From d4961906469b2cd34739fb5c15a0d474f0a827bf Mon Sep 17 00:00:00 2001 From: Danil01042005 Date: Sat, 10 Oct 2026 08:33:01 +0300 Subject: [PATCH 7/7] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20=D0=B8=20=D0=BE=D0=B1=D0=B5=D1=81=D0=BF?= =?UTF-8?q?=D0=B5=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=81?= =?UTF-8?q?=D0=B8=D0=BD=D1=81=D1=82=D0=B5=D0=BD=D1=82=D0=BD=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20=D0=BA=D1=8D=D1=88=D0=B0=20=D0=BF=D0=BE=D1=81?= =?UTF-8?q?=D0=BB=D0=B5=20=D0=BF=D0=B0=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B8=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Исправление security context утечки --- .../messenger/cache/CacheHealthTracker.java | 19 +++++ .../messenger/config/ExecutorConfig.java | 24 ------ .../mtusi/messenger/config/RedisConfig.java | 17 ++-- .../messenger/config/SecurityConfig.java | 4 +- .../java/ru/mtusi/messenger/dto/ChatDTO.java | 20 ++--- .../mtusi/messenger/dto/CreateMessageDTO.java | 4 +- .../ru/mtusi/messenger/dto/MessageDTO.java | 4 +- .../java/ru/mtusi/messenger/dto/UserDTO.java | 7 +- .../ru/mtusi/messenger/mapper/ChatMapper.java | 16 ++-- .../security/SessionAuthenticationFilter.java | 14 +++- .../mtusi/messenger/service/ChatService.java | 83 ++++++++++--------- .../service/SessionCacheService.java | 65 +++++++++++++++ .../messenger/service/SessionService.java | 65 +++++++-------- .../mtusi/messenger/service/UserService.java | 12 +-- .../messenger/validation/ChatValidator.java | 66 +++++++++++++++ 15 files changed, 283 insertions(+), 137 deletions(-) create mode 100644 src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java delete mode 100644 src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java create mode 100644 src/main/java/ru/mtusi/messenger/service/SessionCacheService.java create mode 100644 src/main/java/ru/mtusi/messenger/validation/ChatValidator.java diff --git a/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java new file mode 100644 index 00000000..c3c1d66a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java @@ -0,0 +1,19 @@ +package ru.mtusi.messenger.cache; + +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Component +public class CacheHealthTracker { + + private final AtomicBoolean stale = new AtomicBoolean(false); + + public void markStale() { + stale.set(true); + } + + public boolean consumeStale() { + return stale.getAndSet(false); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java b/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java deleted file mode 100644 index a34b9c1a..00000000 --- a/src/main/java/ru/mtusi/messenger/config/ExecutorConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -package ru.mtusi.messenger.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -@Configuration -public class ExecutorConfig { - - @Bean(destroyMethod = "shutdown") - public ExecutorService cacheEvictExecutor() { - AtomicInteger counter = new AtomicInteger(); - ThreadFactory factory = r -> { - Thread t = new Thread(r, "cache-evict-" + counter.incrementAndGet()); - t.setDaemon(true); - return t; - }; - return Executors.newSingleThreadExecutor(factory); - } -} \ 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 index 190bfa37..badf523a 100644 --- a/src/main/java/ru/mtusi/messenger/config/RedisConfig.java +++ b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java @@ -2,9 +2,6 @@ package ru.mtusi.messenger.config; import io.lettuce.core.ClientOptions; import io.lettuce.core.SocketOptions; -import io.lettuce.core.resource.ClientResources; -import io.lettuce.core.resource.DefaultClientResources; -import io.lettuce.core.resource.DirContextDnsResolver; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -22,6 +19,7 @@ import org.springframework.data.redis.connection.lettuce.LettuceClientConfigurat 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; @@ -34,6 +32,7 @@ import ru.mtusi.messenger.service.SessionService; public class RedisConfig implements CachingConfigurer { private final SessionProperties sessionProperties; private final RedisProperties redisProperties; + private final CacheHealthTracker cacheHealthTracker; @Bean public RedisConnectionFactory redisConnectionFactory() { @@ -83,19 +82,23 @@ public class RedisConfig implements CachingConfigurer { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { - log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage(), e); + cacheHealthTracker.markStale(); + log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage()); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { - log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage(), e); + cacheHealthTracker.markStale(); + log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage()); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { - log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage(), e); + cacheHealthTracker.markStale(); + log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage()); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { - log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage(), e); + cacheHealthTracker.markStale(); + log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage()); } }; } diff --git a/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java index a29ab546..a2233e0c 100644 --- a/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java +++ b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java @@ -10,7 +10,7 @@ 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.bcrypt.BCryptPasswordEncoder; +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; @@ -29,7 +29,7 @@ public class SecurityConfig { @Bean public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); + return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); } @Bean diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java index eaae7ffe..f1c436fe 100644 --- a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -3,9 +3,6 @@ package ru.mtusi.messenger.dto; import java.util.Objects; import java.time.Instant; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import java.util.LinkedHashSet; -import java.util.Set; import java.util.UUID; import jakarta.validation.Valid; import jakarta.validation.constraints.*; @@ -13,6 +10,7 @@ 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 { @@ -22,7 +20,7 @@ public class ChatDTO { private String title; @Valid - private Set memberIds = new LinkedHashSet<>(); + private List memberIds = new ArrayList<>(); private Instant createdAt; @@ -33,7 +31,7 @@ public class ChatDTO { /** * Constructor with only required parameters */ - public ChatDTO(String title, Set memberIds) { + public ChatDTO(String title, List memberIds) { this.title = title; this.memberIds = memberIds; } @@ -59,7 +57,8 @@ public class ChatDTO { return this; } - @NotNull @Size(min = 1, max = 100) + @NotNull + @CodePointLength(min = 1, max = 100) @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("title") public String getTitle() { @@ -70,14 +69,14 @@ public class ChatDTO { this.title = title; } - public ChatDTO memberIds(Set memberIds) { + public ChatDTO memberIds(List memberIds) { this.memberIds = memberIds; return this; } public ChatDTO addMemberIdsItem(UUID memberIdsItem) { if (this.memberIds == null) { - this.memberIds = new LinkedHashSet<>(); + this.memberIds = new ArrayList<>(); } this.memberIds.add(memberIdsItem); return this; @@ -86,12 +85,11 @@ public class ChatDTO { @NotNull @Valid @Size(min = 1, max = 100) @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("member_ids") - public Set getMemberIds() { + public List getMemberIds() { return memberIds; } - @JsonDeserialize(as = LinkedHashSet.class) - public void setMemberIds(Set memberIds) { + public void setMemberIds(List memberIds) { this.memberIds = memberIds; } diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java index c601455d..718cb0f3 100644 --- a/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java @@ -4,6 +4,7 @@ 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; @@ -19,7 +20,8 @@ public class CreateMessageDTO { return this; } - @NotNull @Size(min = 1, max = 4000) + @NotNull + @CodePointLength(min = 1, max = 4000) @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("text") public String getText() { return text; } diff --git a/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java index 10f915e2..703b3acd 100644 --- a/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java @@ -5,6 +5,7 @@ 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; @@ -109,7 +110,8 @@ public class MessageDTO { * Get text * @return text */ - @NotNull @Size(min = 1, max = 4000) + @NotNull + @CodePointLength(min = 1, max = 4000) @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("text") public String getText() { diff --git a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java index 269fa6dd..85976360 100644 --- a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -6,6 +6,7 @@ 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.*; @@ -83,7 +84,8 @@ public class UserDTO { * Get displayName * @return displayName */ - @NotNull @Size(min = 1, max = 100) + @NotNull + @CodePointLength(min = 1, max = 100) @Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("display_name") public String getDisplayName() { @@ -103,7 +105,8 @@ public class UserDTO { * Get password * @return password */ - @NotNull @Size(min = 12, max = 128) + @NotNull + @CodePointLength(min = 1, max = 100) @Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("password") public String getPassword() { diff --git a/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java index a36668cf..012a5d73 100644 --- a/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java +++ b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java @@ -7,17 +7,17 @@ import ru.mtusi.messenger.dto.ChatDTO; import ru.mtusi.messenger.model.Chat; import ru.mtusi.messenger.model.User; -import java.util.LinkedHashSet; +import java.util.ArrayList; +import java.util.List; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; @Mapper(componentModel = "spring") public interface ChatMapper { @Mapping(target = "id", ignore = true) @Mapping(target = "createdAt", ignore = true) - @Mapping(target = "members", ignore = true) // ← заполнит ChatService + @Mapping(target = "members", ignore = true) @Mapping(target = "messages", ignore = true) Chat toChat(ChatDTO dto); @@ -25,10 +25,10 @@ public interface ChatMapper { ChatDTO toChatDto(Chat chat); @Named("usersToIds") - default Set usersToIds(Set users) { - if (users == null) return new LinkedHashSet<>(); - return users.stream() - .map(User::getId) - .collect(Collectors.toCollection(LinkedHashSet::new)); + 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/security/SessionAuthenticationFilter.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java index d6202098..6bfe5d00 100644 --- a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java @@ -5,10 +5,10 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpHeaders; 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; @@ -24,16 +24,22 @@ public class SessionAuthenticationFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String token = bearerTokenResolver.resolve(request); + try { + String token = bearerTokenResolver.resolve(request); if (token != null && !token.isBlank()) { try { Authentication auth = authenticationManager.authenticate( new SessionAuthenticationToken(token)); - SecurityContextHolder.getContext().setAuthentication(auth); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(auth); + SecurityContextHolder.setContext(context); } catch (AuthenticationException e) { SecurityContextHolder.clearContext(); } } - chain.doFilter(request, response); + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } } } \ 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 index 5bb6ff8b..c8b69b7b 100644 --- a/src/main/java/ru/mtusi/messenger/service/ChatService.java +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -14,6 +14,7 @@ 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.*; @@ -23,55 +24,74 @@ import java.util.*; @RequiredArgsConstructor public class ChatService { private final ChatMapper chatMapper; - private final UserService userService; + private final ChatValidator chatValidator; private final ChatRepository chatRepository; @Transactional - public ChatDTO createChat(UUID caller , ChatDTO chatDTO) { - Set members = validateCreate(caller, chatDTO); + public ChatDTO createChat(UUID caller, ChatDTO chatDTO) { + Set members = chatValidator.validateCreate(caller, chatDTO); Chat chat = buildChat(chatDTO, members); - try { - chat = chatRepository.saveAndFlush(chat); - } catch (DataIntegrityViolationException e) { - throw new NotFoundException("Cannot create chat: referenced entity is missing"); - } + chat = persistChat(chat); return chatMapper.toChatDto(chat); } - private Set validateCreate(UUID caller, ChatDTO chatDTO) { - Set memberIds = chatDTO.getMemberIds(); - if (!memberIds.contains(caller)) { - throw new InvalidRequestException("Вызывающий должен быть участником"); - } - return userService.requireUsers(memberIds); - } - private Chat buildChat(ChatDTO chatDTO, Set members) { Chat chat = chatMapper.toChat(chatDTO); chat.setMembers(members); return chat; } + private Chat persistChat(Chat chat) { + try { + return chatRepository.saveAndFlush(chat); + } catch (DataIntegrityViolationException e) { + throw new InvalidRequestException("Cannot create chat: invalid data"); + } + } + @Transactional(readOnly = true) public ChatDTO getChatDTO(UUID caller, UUID chatId) { - Chat chat = 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"); - } + 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 = (limit == null) ? 50 : limit; + int size = resolveSize(limit); CursorCodec.Cursor decoded = parseChatsCursor(cursor); - List rows = (decoded == null) ? chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)) - : chatRepository.findPageByMemberAfterCursor(userId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1)); + List rows = loadChatPage(userId, decoded, size); return buildPage(rows, size); } + private int resolveSize(Integer limit) { + return (limit == null) ? 50 : limit; + } + + private List loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) { + if (cursor == null) { + return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)); + } + return chatRepository.findPageByMemberAfterCursor( + userId, + cursor.boundary().createdAt(), + cursor.boundary().id(), + Pageable.ofSize(size + 1)); + } + private CursorCodec.Cursor parseChatsCursor(String cursor) { if (cursor == null || cursor.isBlank()) { return null; @@ -106,15 +126,4 @@ public class ChatService { private CursorCodec.PageBoundary boundaryOf(Chat chat) { return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); } - - @Transactional(readOnly = true) - public Chat getChat(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; - } -} +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java new file mode 100644 index 00000000..8573e426 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java @@ -0,0 +1,65 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.cache.CacheHealthTracker; +import ru.mtusi.messenger.repository.SessionRepository; + +@Slf4j +@Service +@RequiredArgsConstructor +public class SessionCacheService { + + public static final String SESSIONS = "sessions"; + + private final SessionRepository sessionRepository; + private final CacheManager cacheManager; + private final CacheHealthTracker cacheHealthTracker; + + @Cacheable(value = SESSIONS, key = "#hex", unless = "#result == null") + @Transactional(readOnly = true) + public SessionService.SessionRecord lookupByHash(String hex) { + byte[] hash = hexToBytes(hex); + return sessionRepository.findByTokenHash(hash) + .filter(s -> s.getRevokedAt() == null) + .map(s -> new SessionService.SessionRecord( + s.getId(), s.getUserId(), s.getExpiresAt())) + .orElse(null); + } + + @CacheEvict(value = SESSIONS, key = "#hex") + public void evict(String hex) { + } + + public void dropCacheIfStale() { + if (!cacheHealthTracker.consumeStale()) { + return; + } + try { + Cache cache = cacheManager.getCache(SESSIONS); + if (cache != null) { + cache.clear(); + } + log.info("Cache '{}' cleared after stale flag", SESSIONS); + } catch (RuntimeException e) { + log.warn("Cache clear failed: {}", e.getMessage()); + cacheHealthTracker.markStale(); + } + } + + private static byte[] hexToBytes(String hex) { + int len = hex.length(); + byte[] out = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + out[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); + } + return out; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionService.java b/src/main/java/ru/mtusi/messenger/service/SessionService.java index 54be3c4a..fe6f5557 100644 --- a/src/main/java/ru/mtusi/messenger/service/SessionService.java +++ b/src/main/java/ru/mtusi/messenger/service/SessionService.java @@ -2,10 +2,7 @@ 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.Cacheable; -import org.springframework.stereotype.Service; + import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.mtusi.messenger.config.properties.SessionProperties; import ru.mtusi.messenger.dto.SessionDTO; @@ -20,22 +17,17 @@ import ru.mtusi.messenger.util.TokenHasher; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.UUID; -import java.util.concurrent.ExecutorService; @Slf4j @RequiredArgsConstructor @Service public class SessionService { - private static final String SESSIONS = "sessions"; - private final TokenGenerator tokenGenerator; private final TokenHasher tokenHasher; private final SessionProperties sessionProperties; private final SessionRepository sessionRepository; private final SessionMapper sessionMapper; - private final CacheManager cacheManager; - private final ExecutorService cacheEvictExecutor; - + private final SessionCacheService sessionCacheService; @Transactional public SessionDTO createSession(UserDTO userDTO) { @@ -44,43 +36,46 @@ public class SessionService { return sessionMapper.toSessionDTO(session, token, userDTO); } - @Cacheable(value = SESSIONS, key = "@tokenHasher.hash(#token)") - @Transactional(readOnly = true) public SessionRecord requireActive(String token) { - Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token)) - .filter(x -> x.getRevokedAt() == null) - .filter(x -> x.getExpiresAt().isAfter(Instant.now())) - .orElseThrow(() -> new UnauthorizedException("Invalid or expired session")); - return new SessionRecord(s.getId(), s.getUserId()); + 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(s -> { - if (s.getRevokedAt() == null) { - s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)); - } - String key = tokenHasher.hash(s.getTokenHash()); - cacheEvictExecutor.submit(() -> { - try { - Cache cache = cacheManager.getCache(SESSIONS); - if (cache != null) { - cache.evict(key); - } - } catch (RuntimeException e) { - log.warn("Cache EVICT failed (sessions): {}", e.getMessage()); - } - }); - }); + 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)); + session.setExpiresAt(Instant.now() + .plus(sessionProperties.ttl()) + .truncatedTo(ChronoUnit.MILLIS)); return session; } - public record SessionRecord(UUID sessionId, UUID userId) {} + 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 index 5f2bfba0..37bce670 100644 --- a/src/main/java/ru/mtusi/messenger/service/UserService.java +++ b/src/main/java/ru/mtusi/messenger/service/UserService.java @@ -14,6 +14,7 @@ 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; @@ -28,10 +29,11 @@ public class UserService { private final UserRepository userRepository; @Transactional - public Set requireUsers(Set ids) { - Set users = userRepository.findAllByIdForShare(ids); - if (users.size() != ids.size()) { - throw new NotFoundException("Users not found: " + findMissing(ids, users)); + 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; } @@ -78,4 +80,4 @@ public class UserService { public User getReferenceUserById(UUID senderId) { return userRepository.getReferenceById(senderId); } -} +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java new file mode 100644 index 00000000..b954e5b8 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java @@ -0,0 +1,66 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.service.UserService; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class ChatValidator { + + private final UserService userService; + + public Set validateCreate(UUID caller, ChatDTO chatDTO) { + List memberIds = chatDTO.getMemberIds(); + String title = chatDTO.getTitle(); + + requireNotBlank(title, "Title must not be blank"); + requireNonEmpty(memberIds, "member_ids must not be empty"); + requireNoDuplicates(memberIds, "member_ids contains duplicates"); + requireContains(memberIds, caller, "Вызывающий должен быть участником"); + + return requireAllUsersExist(memberIds); + } + + private void requireNotBlank(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNonEmpty(List ids, String message) { + if (ids == null || ids.isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNoDuplicates(List ids, String message) { + Set unique = new HashSet<>(ids); + if (unique.size() != ids.size()) { + throw new InvalidRequestException(message); + } + } + + private void requireContains(List ids, UUID value, String message) { + if (!ids.contains(value)) { + throw new InvalidRequestException(message); + } + } + + private Set requireAllUsersExist(List ids) { + try { + return userService.requireUsers(ids); + } catch (NotFoundException e) { + throw new InvalidRequestException(e.getMessage()); + } + } +} \ No newline at end of file -- 2.54.0