forked from mtusi2026/mtusi2026lab4
Compare commits
4
Commits
main
..
solution-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
556889ff34 | ||
|
|
a5284efe7b | ||
|
|
da12a510bc | ||
|
|
034d5537cf |
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
.github
|
||||||
.env
|
Lido/.env
|
||||||
.env.*
|
Lido/.env
|
||||||
!.env.example
|
!Lido/.env
|
||||||
secrets
|
secrets
|
||||||
certs
|
certs
|
||||||
volumes
|
volumes
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
|
||||||
APP_HOST=0.0.0.0
|
|
||||||
APP_PORT=8080
|
|
||||||
APP_ENV=lab
|
|
||||||
SESSION_TTL_SECONDS=3600
|
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
|
||||||
SESSION_STORE=postgres
|
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
|
||||||
API_REPLICAS=2
|
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
|
||||||
S3_ENDPOINT=http://s3:9000
|
|
||||||
S3_REGION=us-east-1
|
|
||||||
S3_BUCKET=messenger-attachments
|
|
||||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
|
||||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
|
||||||
MAX_UPLOAD_BYTES=10485760
|
|
||||||
MAX_IMAGE_PIXELS=40000000
|
|
||||||
@@ -1,18 +1,26 @@
|
|||||||
## Лабораторная 4
|
## Лабораторная 4
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Гуреев Дмитрий, БПИ2301
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 4
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: не заявляется
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Что реализовано и что перенесено: перенесён минимум lab3 (пользователи, чаты, сообщения, пагинация, сессии, идемпотентность). Добавлены: таблица attachments, связь message_attachments, endpoint загрузки/скачивания вложений, S3-хранение байтов в приватном bucket, стриминговый валидатор изображений, реконсилер «осиротевших» объектов с grace period.
|
||||||
Команды запуска из чистого clone: TODO
|
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
|
||||||
Ограничения / известные ошибки: TODO
|
|
||||||
Источники и использование ИИ: TODO
|
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
Команды запуска из чистого clone:
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
1. Скопировать compose.example.yaml в docker-compose.yml, заполнить локальный .env.
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
2. docker compose --env-file .env up -d --build
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
3. Дождаться /health/ready.
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
4. make test BASE_URL=http://localhost:8080
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
|
||||||
|
Результаты проверок и ссылка на REPORT.md: make test проходит (PASS: lab4 public API scenario). REPORT.md содержит доказательства критериев оценки 4.
|
||||||
|
|
||||||
|
Ограничения / известные ошибки: не реализован presigned-upload flow (трек 5), отдельные S3 credentials с ограниченными правами документированы в scripts/minio-init.sh, MinIO консоль (9001) не экспонируется наружу.
|
||||||
|
|
||||||
|
Источники и использование ИИ: документация Spring Boot 3, PostgreSQL 16, Redis 7, nginx, Flyway, k6, MiniO; консультации по архитектуре multi-instance, health/readiness, идемпотентности.
|
||||||
|
|
||||||
|
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
|
- [x] Контракт и публичные тесты не ослаблены.
|
||||||
|
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||||
|
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||||
|
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||||
|
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||||
|
|||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
# Local/private state
|
# Local/private state
|
||||||
.env
|
Lido/.env
|
||||||
.env.*
|
Lido/.env
|
||||||
!.env.example
|
!Lido/.env
|
||||||
secrets/
|
secrets/
|
||||||
certs/private/
|
certs/private/
|
||||||
*.key
|
*.key
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.gradle
|
||||||
|
build
|
||||||
|
.git
|
||||||
|
*.iml
|
||||||
|
.idea
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
MINIO_ROOT_USER=minioadmin
|
||||||
|
MINIO_ROOT_PASSWORD=minioadmin_change_me
|
||||||
|
S3_ENDPOINT=http://minio:9000
|
||||||
|
S3_BUCKET=messenger-attachments
|
||||||
|
S3_ACCESS_KEY=minioadmin
|
||||||
|
S3_SECRET_KEY=minioadmin_change_me
|
||||||
|
S3_REGION=eu-east-1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
build.gradle.kts
|
||||||
|
.gradle
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
FROM eclipse-temurin:22-jdk-alpine AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
RUN apk add --no-cache dos2unix
|
||||||
|
COPY gradlew .
|
||||||
|
COPY gradle gradle
|
||||||
|
COPY build.gradle.* settings.gradle* build.gradle.kts* settings.gradle.kts* ./
|
||||||
|
RUN dos2unix gradlew && chmod +x gradlew
|
||||||
|
RUN ./gradlew dependencies --no-daemon || true
|
||||||
|
COPY src src
|
||||||
|
RUN apk add --no-cache curl
|
||||||
|
RUN ./gradlew bootJar -x test --no-daemon
|
||||||
|
|
||||||
|
FROM eclipse-temurin:22-jre-alpine AS runtime
|
||||||
|
WORKDIR /app
|
||||||
|
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
|
||||||
|
COPY --from=builder /app/build/libs/*.jar app.jar
|
||||||
|
RUN chown -R appuser:appgroup /app
|
||||||
|
USER appuser
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/actuator/health || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["java", "-jar", "app.jar"]
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: Lido-db
|
||||||
|
mem_limit: 128m
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: lido_db
|
||||||
|
POSTGRES_USER: user
|
||||||
|
POSTGRES_PASSWORD: user
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
volumes:
|
||||||
|
- messenger_pg_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U user -d lido_db"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks: [messenger]
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
mem_limit: 128m
|
||||||
|
container_name: lido-redis
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
volumes:
|
||||||
|
- lido_redis_data:/data
|
||||||
|
command: [ "redis-server", "--appendonly", "yes" ]
|
||||||
|
healthcheck:
|
||||||
|
test: [ "CMD", "redis-cli", "ping" ]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
networks: [messenger]
|
||||||
|
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
networks: [messenger]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
mem_reservation: 256m
|
||||||
|
environment:
|
||||||
|
FLYWAY_ENABLED: "false"
|
||||||
|
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/lido_db
|
||||||
|
SPRING_DATASOURCE_USERNAME: user
|
||||||
|
SPRING_DATASOURCE_PASSWORD: user
|
||||||
|
SPRING_DATA_REDIS_HOST: redis
|
||||||
|
SPRING_DATA_REDIS_PORT: "6379"
|
||||||
|
SESSION_TTL_SECONDS: "604800"
|
||||||
|
SERVER_SHUTDOWN: graceful
|
||||||
|
S3_ENDPOINT: http://minio:9000
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
|
S3_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
S3_REGION: eu-east-1
|
||||||
|
deploy:
|
||||||
|
replicas: 3
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "wget -q -O- http://127.0.0.1:8080/health/live || exit 1"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
start_period: 40s
|
||||||
|
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
image: nginx:1.27-alpine
|
||||||
|
mem_limit: 128m
|
||||||
|
ports:
|
||||||
|
- "8080:80"
|
||||||
|
volumes:
|
||||||
|
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
depends_on:
|
||||||
|
- api
|
||||||
|
networks: [ messenger ]
|
||||||
|
|
||||||
|
minio:
|
||||||
|
image: bitnamilegacy/minio:latest
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
|
||||||
|
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
|
||||||
|
volumes:
|
||||||
|
- minio_data:/bitnami/minio/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:9000:9000"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks: [ messenger ]
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/lido_db
|
||||||
|
SPRING_DATASOURCE_USERNAME: user
|
||||||
|
SPRING_DATASOURCE_PASSWORD: user
|
||||||
|
FLYWAY_ENABLED: "true"
|
||||||
|
SPRING_MAIN_WEB_APPLICATION_TYPE: none
|
||||||
|
networks: [ messenger ]
|
||||||
|
restart: "no"
|
||||||
|
image: flyway/flyway:10
|
||||||
|
command: -url=jdbc:postgresql://db:5432/lido_db -user=user -password=user -locations=filesystem:/flyway/sql migrate
|
||||||
|
volumes:
|
||||||
|
- ./src/main/resources/db/migration:/flyway/sql:ro
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
|
||||||
|
minio-init:
|
||||||
|
image: bitnamilegacy/minio:latest
|
||||||
|
depends_on:
|
||||||
|
minio:
|
||||||
|
condition: service_started
|
||||||
|
env_file: .env
|
||||||
|
volumes:
|
||||||
|
- ../../scripts/minio-init.sh:/minio-init.sh:ro
|
||||||
|
entrypoint: ["/bin/sh", "/minio-init.sh"]
|
||||||
|
networks: [ messenger ]
|
||||||
|
restart: "no"
|
||||||
|
volumes:
|
||||||
|
messenger_pg_data:
|
||||||
|
lido_redis_data:
|
||||||
|
minio_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
messenger:
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
model {
|
||||||
|
messenger = softwareSystem "Messenger" {
|
||||||
|
api = container "API" "Spring Boot" {
|
||||||
|
userSvc = component "UserService"
|
||||||
|
chatSvc = component "ChatService"
|
||||||
|
msgSvc = component "MessageService"
|
||||||
|
}
|
||||||
|
db = container "PostgreSQL" "users, chats, chat_members, messages"
|
||||||
|
}
|
||||||
|
api -> db "JDBC / Flyway"
|
||||||
|
}
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,8 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
|
|
||||||
+249
@@ -0,0 +1,249 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# 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" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
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, 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" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+92
@@ -0,0 +1,92 @@
|
|||||||
|
@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
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
worker_processes auto;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
client_max_body_size 12M;
|
||||||
|
|
||||||
|
upstream api_backend {
|
||||||
|
least_conn;
|
||||||
|
server api:8080 max_fails=2 fail_timeout=5s;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
|
||||||
|
location /health/live {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_read_timeout 5s;
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /health/ready {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_read_timeout 5s;
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_send_timeout 30s;
|
||||||
|
proxy_read_timeout 30s;
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
proxy_next_upstream_tries 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
rootProject.name = "Lido"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package org.example;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@EnableScheduling
|
||||||
|
public class LidoApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(LidoApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.example.repository.SessionRepository;
|
||||||
|
import org.example.service.AuthService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuthFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final AuthService authService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||||
|
String path = request.getRequestURI();
|
||||||
|
return path.startsWith("/health/")
|
||||||
|
|| path.startsWith("/actuator/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
|
||||||
|
String auth = request.getHeader("Authorization");
|
||||||
|
if (auth != null && auth.startsWith("Bearer ")) {
|
||||||
|
String token = auth.substring(7).trim();
|
||||||
|
if (!token.isEmpty()) {
|
||||||
|
authService.resolveUserByBearer(token)
|
||||||
|
.ifPresent(UserContext::setCurrentUser);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
UserContext.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import jakarta.validation.Constraint;
|
||||||
|
import jakarta.validation.Payload;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
@Documented
|
||||||
|
@Constraint(validatedBy = CodePointSizeValidator.class)
|
||||||
|
@Target({ ElementType.FIELD, ElementType.PARAMETER })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface CodePointSize {
|
||||||
|
int min() default 0;
|
||||||
|
int max() default Integer.MAX_VALUE;
|
||||||
|
String message() default "size must be between {min} and {max} code points";
|
||||||
|
Class<?>[] groups() default {};
|
||||||
|
Class<? extends Payload>[] payload() default {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import jakarta.validation.ConstraintValidator;
|
||||||
|
import jakarta.validation.ConstraintValidatorContext;
|
||||||
|
|
||||||
|
public class CodePointSizeValidator implements ConstraintValidator<CodePointSize, String> {
|
||||||
|
|
||||||
|
private int min;
|
||||||
|
private int max;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void initialize(CodePointSize annotation) {
|
||||||
|
this.min = annotation.min();
|
||||||
|
this.max = annotation.max();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||||
|
if (value == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
int n = value.codePointCount(0, value.length());
|
||||||
|
return n >= min && n <= max;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import org.springframework.context.event.ContextClosedEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class GracefulShutdownListener {
|
||||||
|
|
||||||
|
private final ReadinessState state;
|
||||||
|
|
||||||
|
public GracefulShutdownListener(ReadinessState state) {
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ContextClosedEvent.class)
|
||||||
|
public void onClose(){
|
||||||
|
state.setReady(false);
|
||||||
|
try {
|
||||||
|
Thread.sleep(2000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import org.example.exception.BadRequestException;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ImageUploadValidator {
|
||||||
|
|
||||||
|
public static final long MAX_BYTES = 10L * 1024 * 1024;
|
||||||
|
public static final long MAX_PIXELS = 40_000_000L;
|
||||||
|
|
||||||
|
private static final Set<String> ALLOWED = Set.of("image/png", "image/jpeg");
|
||||||
|
|
||||||
|
public record ValidatedImage(
|
||||||
|
Path tempFile,
|
||||||
|
String contentType,
|
||||||
|
String safeFilename,
|
||||||
|
int width,
|
||||||
|
int height,
|
||||||
|
long sizeBytes,
|
||||||
|
String sha256Hex
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public ValidatedImage validate(String filename, InputStream in) throws IOException {
|
||||||
|
if (in == null) {
|
||||||
|
throw new BadRequestException("Empty body");
|
||||||
|
}
|
||||||
|
|
||||||
|
String safeName = sanitizeFilename(filename);
|
||||||
|
|
||||||
|
byte[] header = new byte[8];
|
||||||
|
int totalRead = 0;
|
||||||
|
int read;
|
||||||
|
while (totalRead < header.length && (read = in.read(header, totalRead, header.length - totalRead)) != -1) {
|
||||||
|
totalRead += read;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalRead == 0) {
|
||||||
|
throw new BadRequestException("Empty file");
|
||||||
|
}
|
||||||
|
|
||||||
|
String detected = detectMime(header, totalRead);
|
||||||
|
if (!ALLOWED.contains(detected)) {
|
||||||
|
throw new BadRequestException("Only PNG and JPEG are allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
Path tempFile = Files.createTempFile("upload-", ".tmp");
|
||||||
|
MessageDigest digest;
|
||||||
|
try {
|
||||||
|
digest = MessageDigest.getInstance("SHA-256");
|
||||||
|
} catch (Exception e) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
throw new IllegalStateException("SHA-256 not available", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
long sizeBytes = 0;
|
||||||
|
boolean success = false;
|
||||||
|
try (OutputStream out = Files.newOutputStream(tempFile)) {
|
||||||
|
out.write(header, 0, totalRead);
|
||||||
|
digest.update(header, 0, totalRead);
|
||||||
|
sizeBytes += totalRead;
|
||||||
|
|
||||||
|
byte[] buffer = new byte[8192];
|
||||||
|
while ((read = in.read(buffer)) != -1) {
|
||||||
|
sizeBytes += read;
|
||||||
|
if (sizeBytes > MAX_BYTES) {
|
||||||
|
throw new BadRequestException("File too large (max 10 MiB)");
|
||||||
|
}
|
||||||
|
out.write(buffer, 0, read);
|
||||||
|
digest.update(buffer, 0, read);
|
||||||
|
}
|
||||||
|
success = true;
|
||||||
|
} finally {
|
||||||
|
if (!success) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sizeBytes == 0) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
throw new BadRequestException("Empty file");
|
||||||
|
}
|
||||||
|
|
||||||
|
BufferedImage image;
|
||||||
|
try (InputStream imageIn = Files.newInputStream(tempFile)) {
|
||||||
|
try {
|
||||||
|
image = ImageIO.read(imageIn);
|
||||||
|
} catch (IOException e) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
throw new BadRequestException("Invalid image");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (image == null) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
throw new BadRequestException("Invalid image");
|
||||||
|
}
|
||||||
|
|
||||||
|
int width = image.getWidth();
|
||||||
|
int height = image.getHeight();
|
||||||
|
long pixels = (long) width * (long) height;
|
||||||
|
if (width <= 0 || height <= 0 || pixels > MAX_PIXELS) {
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
throw new BadRequestException("Image exceeds pixel limit");
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder(64);
|
||||||
|
for (byte b : digest.digest()) {
|
||||||
|
sb.append(String.format("%02x", b));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ValidatedImage(tempFile, detected, safeName, width, height, sizeBytes, sb.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String detectMime(byte[] b, int len) {
|
||||||
|
if (len >= 3
|
||||||
|
&& (b[0] & 0xFF) == 0xFF
|
||||||
|
&& (b[1] & 0xFF) == 0xD8
|
||||||
|
&& (b[2] & 0xFF) == 0xFF) {
|
||||||
|
return "image/jpeg";
|
||||||
|
}
|
||||||
|
if (len >= 8
|
||||||
|
&& (b[0] & 0xFF) == 0x89
|
||||||
|
&& b[1] == 0x50
|
||||||
|
&& b[2] == 0x4E
|
||||||
|
&& b[3] == 0x47
|
||||||
|
&& b[4] == 0x0D
|
||||||
|
&& b[5] == 0x0A
|
||||||
|
&& b[6] == 0x1A
|
||||||
|
&& b[7] == 0x0A) {
|
||||||
|
return "image/png";
|
||||||
|
}
|
||||||
|
return "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String sanitizeFilename(String name) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
throw new BadRequestException("filename is required");
|
||||||
|
}
|
||||||
|
String base = name.replace('\\', '/').trim();
|
||||||
|
int slash = base.lastIndexOf('/');
|
||||||
|
if (slash >= 0) {
|
||||||
|
base = base.substring(slash + 1);
|
||||||
|
}
|
||||||
|
if (base.isEmpty()
|
||||||
|
|| ".".equals(base)
|
||||||
|
|| "..".equals(base)
|
||||||
|
|| base.indexOf('\0') >= 0
|
||||||
|
|| base.length() > 255) {
|
||||||
|
throw new BadRequestException("Invalid filename");
|
||||||
|
}
|
||||||
|
if (!base.matches("[\\w.\\- ()\\[\\]]+")) {
|
||||||
|
throw new BadRequestException("Invalid filename");
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class InstanceIdFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
public static final String HEADER = "X-Instance-Id";
|
||||||
|
private final String instanceId;
|
||||||
|
|
||||||
|
public InstanceIdFilter() {
|
||||||
|
this.instanceId = resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String resolve() {
|
||||||
|
String id = firstNonBlank(
|
||||||
|
System.getenv("INSTANCE_ID"),
|
||||||
|
System.getenv("HOSTNAME"),
|
||||||
|
System.getProperty("HOSTNAME")
|
||||||
|
);
|
||||||
|
if (id == null) {
|
||||||
|
id = "unknown-" + UUID.randomUUID().toString().substring(0, 8);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstNonBlank(String... values) {
|
||||||
|
if (values == null) return null;
|
||||||
|
for (String v : values) {
|
||||||
|
if (v != null && !v.isBlank()) return v.trim();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain
|
||||||
|
) throws ServletException, IOException {
|
||||||
|
response.setHeader(HEADER, instanceId);
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class PasswordConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
||||||
|
|
||||||
|
return new PasswordEncoder() {
|
||||||
|
private String prehash(String raw) {
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return HexFormat.of().formatHex(digest);
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String encode(CharSequence rawPassword) {
|
||||||
|
return bcrypt.encode(prehash(rawPassword.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(CharSequence rawPassword, String encodedPassword) {
|
||||||
|
return bcrypt.matches(prehash(rawPassword.toString()), encodedPassword);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ReadinessState {
|
||||||
|
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||||
|
public boolean isReady() {
|
||||||
|
return ready.get();
|
||||||
|
}
|
||||||
|
public void setReady(boolean v) {
|
||||||
|
ready.set(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
|
||||||
|
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.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class RequestIdFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
|
||||||
|
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||||
|
|
||||||
|
if (requestId == null || requestId.trim().isEmpty()) {
|
||||||
|
requestId = UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
MDC.put(REQUEST_ID_HEADER, requestId);
|
||||||
|
|
||||||
|
request.setAttribute(REQUEST_ID_HEADER, requestId);
|
||||||
|
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
MDC.remove(REQUEST_ID_HEADER);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||||
|
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||||
|
import software.amazon.awssdk.regions.Region;
|
||||||
|
import software.amazon.awssdk.services.s3.S3Client;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class S3Config {
|
||||||
|
private final S3Properties props;
|
||||||
|
|
||||||
|
@Bean(destroyMethod = "close")
|
||||||
|
public S3Client s3Client() {
|
||||||
|
return S3Client.builder()
|
||||||
|
.endpointOverride(URI.create(props.getEndpoint()))
|
||||||
|
.region(Region.of(props.getRegion()))
|
||||||
|
.credentialsProvider(StaticCredentialsProvider.create(
|
||||||
|
AwsBasicCredentials.create(props.getAccessKey(), props.getSecretKey())))
|
||||||
|
.forcePathStyle(props.isPathStyle())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "app.s3")
|
||||||
|
public class S3Properties {
|
||||||
|
private String endpoint;
|
||||||
|
private String region = "eu-east-1";
|
||||||
|
private String bucket;
|
||||||
|
private String accessKey;
|
||||||
|
private String secretKey;
|
||||||
|
private boolean pathStyle = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||||
|
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class StrictStringDeserializer extends JsonDeserializer<String> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||||
|
if (p.currentToken() != JsonToken.VALUE_STRING) {
|
||||||
|
return (String) ctxt.handleUnexpectedToken(String.class, p);
|
||||||
|
}
|
||||||
|
return p.getValueAsString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
public final class TokenHasher {
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
|
||||||
|
public TokenHasher() {}
|
||||||
|
|
||||||
|
public static String newRawToken(){
|
||||||
|
byte[] bytes = new byte[32];
|
||||||
|
RANDOM.nextBytes(bytes);
|
||||||
|
return HexFormat.of().formatHex(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sha256(String rawToken) {
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
byte[] dig = md.digest(rawToken.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return HexFormat.of().formatHex(dig);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.example.config;
|
||||||
|
|
||||||
|
import org.example.model.User;
|
||||||
|
|
||||||
|
public class UserContext {
|
||||||
|
private static final ThreadLocal<User> CURRENT_USER = new ThreadLocal<>();
|
||||||
|
|
||||||
|
public static void setCurrentUser(User user) {
|
||||||
|
CURRENT_USER.set(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static User getCurrentUser() {
|
||||||
|
return CURRENT_USER.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void clear() {
|
||||||
|
CURRENT_USER.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package org.example.controller;
|
||||||
|
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.response.AttachmentResponse;
|
||||||
|
import org.example.service.AttachmentService;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AttachmentController {
|
||||||
|
|
||||||
|
private final AttachmentService attachmentService;
|
||||||
|
|
||||||
|
@PostMapping(
|
||||||
|
path = "/api/v1/chats/{chat_id}/attachments",
|
||||||
|
consumes = { MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE }
|
||||||
|
)
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public AttachmentResponse uploadAttachment(
|
||||||
|
@PathVariable("chat_id") UUID chatId,
|
||||||
|
@RequestParam("filename") String fileName,
|
||||||
|
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
|
||||||
|
HttpServletRequest request
|
||||||
|
) throws IOException {
|
||||||
|
return attachmentService.upload(
|
||||||
|
chatId,
|
||||||
|
fileName,
|
||||||
|
contentType,
|
||||||
|
request.getInputStream()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/v1/attachments/{attachment_id}")
|
||||||
|
public AttachmentResponse getAttachment(
|
||||||
|
@PathVariable("attachment_id") UUID attachmentId) {
|
||||||
|
return attachmentService.getMeta(attachmentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/v1/attachments/{attachment_id}/content")
|
||||||
|
public void downloadAttachment(
|
||||||
|
@PathVariable("attachment_id") UUID attachmentId,
|
||||||
|
@RequestParam(value = "variant", defaultValue = "original") String variant,
|
||||||
|
HttpServletResponse response) throws IOException {
|
||||||
|
attachmentService.writeContent(attachmentId, variant, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package org.example.controller;
|
||||||
|
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.response.SessionInfoResponse;
|
||||||
|
import org.example.dto.response.SessionResponse;
|
||||||
|
import org.example.exception.UnauthorizedException;
|
||||||
|
import org.example.service.AuthService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/auth")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuthController {
|
||||||
|
|
||||||
|
private final AuthService authService;
|
||||||
|
|
||||||
|
@PostMapping("/sessions")
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public SessionResponse login(HttpServletRequest request) {
|
||||||
|
String header = request.getHeader("Authorization");
|
||||||
|
if (header == null || !header.startsWith("Basic ")) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
String decoded;
|
||||||
|
try {
|
||||||
|
decoded = new String(
|
||||||
|
Base64.getDecoder().decode(header.substring(6).trim()),
|
||||||
|
StandardCharsets.UTF_8);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
int colon = decoded.indexOf(':');
|
||||||
|
if (colon < 0) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
String username = decoded.substring(0, colon);
|
||||||
|
String password = decoded.substring(colon + 1);
|
||||||
|
return authService.login(username, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/sessions/current")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void revokeCurrent(HttpServletRequest request) {
|
||||||
|
String header = request.getHeader("Authorization");
|
||||||
|
if (header == null || !header.startsWith("Bearer ")) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
String token = header.substring(7).trim();
|
||||||
|
if (token.isEmpty()) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
authService.logoutCurrent(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/sessions")
|
||||||
|
public List<SessionInfoResponse> sessions() {
|
||||||
|
return authService.listSessionsForCurrentUser();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package org.example.controller;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Max;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.ChatPage;
|
||||||
|
import org.example.dto.MessagePage;
|
||||||
|
import org.example.dto.create.CreateChatDto;
|
||||||
|
import org.example.dto.create.CreateMessageDto;
|
||||||
|
import org.example.dto.response.ChatResponse;
|
||||||
|
import org.example.dto.update.UpdateChatDto;
|
||||||
|
import org.example.dto.update.UpdateMessageDto;
|
||||||
|
import org.example.model.Message;
|
||||||
|
import org.example.service.ChatService;
|
||||||
|
import org.example.service.MessageService;
|
||||||
|
import org.example.service.UserService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/chats")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Validated
|
||||||
|
public class ChatController {
|
||||||
|
|
||||||
|
private final ChatService chatService;
|
||||||
|
private final MessageService messageService;
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
// ——— Chats ———
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public ChatResponse createChat(@Valid @RequestBody CreateChatDto dto) {
|
||||||
|
return chatService.createChat(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ChatPage getChats(
|
||||||
|
@RequestParam(defaultValue = "50")
|
||||||
|
@Max(100)
|
||||||
|
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||||
|
) {
|
||||||
|
return chatService.getChatsForCurrentUser(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ChatResponse getChatById(@PathVariable UUID id) {
|
||||||
|
return chatService.getChatById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ChatResponse updateChat(
|
||||||
|
@PathVariable UUID id,
|
||||||
|
@Valid @RequestBody UpdateChatDto object
|
||||||
|
) {
|
||||||
|
return chatService.updateChat(id, object);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void deleteChat(@PathVariable UUID id) {
|
||||||
|
chatService.deleteChat(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ——— Messages ———
|
||||||
|
|
||||||
|
@PostMapping("/{id}/messages")
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public Message sendMessage(
|
||||||
|
@PathVariable("id") UUID id,
|
||||||
|
@RequestHeader("Idempotency-Key") String idempotencyKey,
|
||||||
|
@Valid @RequestBody CreateMessageDto messageDto
|
||||||
|
) {
|
||||||
|
UUID senderId = userService.getCurrentUser().getId();
|
||||||
|
return messageService.sendMessage(id, senderId, messageDto, idempotencyKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}/messages")
|
||||||
|
public MessagePage getMessages(
|
||||||
|
@PathVariable("id") UUID id,
|
||||||
|
@RequestParam(required = false) String cursor,
|
||||||
|
@RequestParam(defaultValue = "50")
|
||||||
|
@Max(100)
|
||||||
|
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||||
|
) {
|
||||||
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
|
return messageService.getMessage(id, userId, cursor, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}/messages/{messageId}")
|
||||||
|
public Message updateMessage(
|
||||||
|
@PathVariable("id") UUID id,
|
||||||
|
@PathVariable UUID messageId,
|
||||||
|
@Valid @RequestBody UpdateMessageDto object
|
||||||
|
) {
|
||||||
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
|
return messageService.updateMessage(id, messageId, userId, object);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}/messages/{messageId}")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void deleteMessage(
|
||||||
|
@PathVariable("id") UUID id,
|
||||||
|
@PathVariable UUID messageId
|
||||||
|
) {
|
||||||
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
|
messageService.deleteMessage(id, messageId, userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package org.example.controller;
|
||||||
|
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/health")
|
||||||
|
public class HealthController {
|
||||||
|
|
||||||
|
private final DataSource dataSource;
|
||||||
|
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||||
|
|
||||||
|
public HealthController(DataSource dataSource) {
|
||||||
|
this.dataSource = dataSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping({"/live"})
|
||||||
|
public ResponseEntity<Map<String, String>> live() {
|
||||||
|
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/ready")
|
||||||
|
public ResponseEntity<Map<String, String>> ready(){
|
||||||
|
if (!ready.get()){
|
||||||
|
return ResponseEntity.status(503).body(Map.of("status", "NOT_READY"));
|
||||||
|
}
|
||||||
|
try (Connection c = dataSource.getConnection()){
|
||||||
|
if (!c.isValid(1)){
|
||||||
|
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||||
|
}
|
||||||
|
} catch (Exception e){
|
||||||
|
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markNotReady() {
|
||||||
|
ready.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package org.example.controller;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.create.CreateUserDto;
|
||||||
|
import org.example.dto.update.UpdateUserDto;
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.example.service.UserService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/users")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserController {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public User createUser(@Valid @RequestBody CreateUserDto dto) {
|
||||||
|
return userService.createUser(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/me")
|
||||||
|
public User getCurrentUser() {
|
||||||
|
return userService.getCurrentUser();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public User getUserById(@PathVariable UUID id) {
|
||||||
|
return userService.getUserById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public User updateUser(@PathVariable String id,
|
||||||
|
@Valid @RequestBody UpdateUserDto object) {
|
||||||
|
return userService.updateUser(id, object);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void delete(@PathVariable String id) {
|
||||||
|
userService.deleteUser(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package org.example.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.example.dto.response.ChatResponse;
|
||||||
|
import org.example.model.Chat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||||
|
public class ChatPage {
|
||||||
|
private List<ChatResponse> items;
|
||||||
|
@JsonProperty("next_cursor")
|
||||||
|
private String nextCursor;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package org.example.dto;
|
||||||
|
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ErrorDetail {
|
||||||
|
private String code;
|
||||||
|
private String message;
|
||||||
|
private String request_id;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package org.example.dto;
|
||||||
|
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.model.Message;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MessagePage {
|
||||||
|
private List<Message> items;
|
||||||
|
private String nextCursor;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package org.example.dto.create;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class CreateChatDto {
|
||||||
|
@NotBlank(message = "Title не может быть пустым")
|
||||||
|
@CodePointSize(min = 1, max = 100)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@JsonProperty("member_ids")
|
||||||
|
@NotEmpty(message = "Список участников не может быть пустым")
|
||||||
|
private List<@NotNull UUID> memberIds;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.example.dto.create;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class CreateMessageDto {
|
||||||
|
|
||||||
|
@CodePointSize(min = 0, max = 4000)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String text;
|
||||||
|
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
private List<UUID> attachmentIds;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package org.example.dto.create;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class CreateUserDto {
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 3, max = 32)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@NotBlank(message = "Display name не может быть пустым")
|
||||||
|
@CodePointSize(min = 1, max = 128)
|
||||||
|
@JsonProperty("display_name")
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String displayName;
|
||||||
|
|
||||||
|
@NotBlank(message = "Password не может быть пустым")
|
||||||
|
@CodePointSize(min = 12, max = 128)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String password;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Value;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.example.model.VariantResponse;
|
||||||
|
|
||||||
|
@Value
|
||||||
|
@Builder
|
||||||
|
public class AttachmentResponse {
|
||||||
|
|
||||||
|
@JsonProperty("id")
|
||||||
|
UUID id;
|
||||||
|
|
||||||
|
@JsonProperty("chat_id")
|
||||||
|
UUID chatId;
|
||||||
|
|
||||||
|
@JsonProperty("owner_id")
|
||||||
|
UUID ownerId;
|
||||||
|
|
||||||
|
@JsonProperty("filename")
|
||||||
|
String filename;
|
||||||
|
|
||||||
|
@JsonProperty("content_type")
|
||||||
|
String contentType;
|
||||||
|
|
||||||
|
@JsonProperty("size_bytes")
|
||||||
|
long sizeBytes;
|
||||||
|
|
||||||
|
@JsonProperty("sha256")
|
||||||
|
String sha256;
|
||||||
|
|
||||||
|
@JsonProperty("status")
|
||||||
|
String status;
|
||||||
|
|
||||||
|
@JsonProperty("variants")
|
||||||
|
List<VariantResponse> variants;
|
||||||
|
|
||||||
|
@JsonProperty("error_code")
|
||||||
|
String errorCode;
|
||||||
|
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
Instant createdAt;
|
||||||
|
|
||||||
|
@JsonProperty("updated_at")
|
||||||
|
Instant updatedAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class ChatResponse {
|
||||||
|
private UUID id;
|
||||||
|
private String title;
|
||||||
|
@JsonProperty("member_ids")
|
||||||
|
private List<UUID> memberIds;
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.dto.ErrorDetail;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ErrorResponse {
|
||||||
|
private ErrorDetail error;
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class MessageResponse {
|
||||||
|
private UUID id;
|
||||||
|
@JsonProperty("chat_id")
|
||||||
|
private UUID chatId;
|
||||||
|
@JsonProperty("sender_id")
|
||||||
|
private UUID senderId;
|
||||||
|
private String text;
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
List<UUID> attachmentIds;
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class SessionInfoResponse {
|
||||||
|
private UUID id;
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
@JsonProperty("expires_at")
|
||||||
|
private Instant expiresAt;
|
||||||
|
@JsonProperty("revoked_at")
|
||||||
|
private Instant revokedAt;
|
||||||
|
private boolean active;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Data
|
||||||
|
public class SessionResponse {
|
||||||
|
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@JsonProperty("token_type")
|
||||||
|
private String tokenType;
|
||||||
|
|
||||||
|
@JsonProperty("expires_at")
|
||||||
|
private Instant expiresAt;
|
||||||
|
|
||||||
|
private UserResponse user;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package org.example.dto.response;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class UserResponse {
|
||||||
|
private UUID id;
|
||||||
|
private String username;
|
||||||
|
@JsonProperty("display_name")
|
||||||
|
private String displayName;
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package org.example.dto.update;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class UpdateChatDto {
|
||||||
|
@NotBlank
|
||||||
|
@CodePointSize(min = 1, max = 100)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String title;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package org.example.dto.update;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class UpdateMessageDto {
|
||||||
|
@NotBlank
|
||||||
|
@CodePointSize(min = 1, max = 4000)
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String text;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package org.example.dto.update;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.example.config.CodePointSize;
|
||||||
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class UpdateUserDto {
|
||||||
|
@NotBlank
|
||||||
|
@CodePointSize(min = 1, max = 128)
|
||||||
|
@JsonProperty("display_name")
|
||||||
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
|
private String displayName;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
public class BadRequestException extends RuntimeException {
|
||||||
|
public BadRequestException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
public class ConflictException extends RuntimeException {
|
||||||
|
public ConflictException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
public class ForbiddenException extends RuntimeException {
|
||||||
|
public ForbiddenException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.validation.ConstraintViolationException;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.example.config.RequestIdFilter;
|
||||||
|
import org.example.dto.ErrorDetail;
|
||||||
|
import org.example.dto.response.ErrorResponse;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
|
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class GlobalExceptionHandler {
|
||||||
|
|
||||||
|
private String resolveRequestId(HttpServletRequest request) {
|
||||||
|
Object attr = request.getAttribute(RequestIdFilter.REQUEST_ID_HEADER);
|
||||||
|
if (attr instanceof String s && !s.isBlank()) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
String header = request.getHeader(RequestIdFilter.REQUEST_ID_HEADER);
|
||||||
|
if (header != null && !header.isBlank()) {
|
||||||
|
return header.trim();
|
||||||
|
}
|
||||||
|
return UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(NotFoundException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest request) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("not_found", ex.getMessage(), reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(ForbiddenException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleForbidden(ForbiddenException ex, HttpServletRequest request) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("forbidden", ex.getMessage(), reqId)
|
||||||
|
);
|
||||||
|
// если в openapi нет code "forbidden" — замени на "unauthorized" или как в контракте
|
||||||
|
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(ConflictException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleConflictException(
|
||||||
|
ConflictException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
log.debug("Validation failed", ex);
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("conflict", "conflict", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(BadRequestException.class)
|
||||||
|
public ResponseEntity<?> handleBadRequest(BadRequestException ex, HttpServletRequest request) {
|
||||||
|
String requestId = resolveRequestId(request); // как у вас в других handler
|
||||||
|
Map<String, Object> body = Map.of(
|
||||||
|
"error", Map.of(
|
||||||
|
"code", "invalid_request",
|
||||||
|
"message", ex.getMessage() != null ? ex.getMessage() : "Bad request",
|
||||||
|
"request_id", requestId
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", requestId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleValidationException(
|
||||||
|
MethodArgumentNotValidException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
log.debug("Validation failed", ex);
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", "Validation Failed", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleMissingHeader(
|
||||||
|
MissingRequestHeaderException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", "Malformed JSON request body", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleMalformedJson(
|
||||||
|
HttpMessageNotReadableException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", "Malformed JSON request body", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleBadRequest(
|
||||||
|
IllegalArgumentException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", ex.getMessage(), reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(UserAlreadyExistsException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleUserAlreadyExists(
|
||||||
|
UserAlreadyExistsException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("conflict", ex.getMessage(), reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(UnauthorizedException.class)
|
||||||
|
public ResponseEntity<Map<String, Object>> handleUnauthorized(
|
||||||
|
UnauthorizedException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String requestId = resolveRequestId(request);
|
||||||
|
|
||||||
|
String path = request.getRequestURI();
|
||||||
|
String www;
|
||||||
|
if (path != null
|
||||||
|
&& path.startsWith("/api/v1/auth/sessions")
|
||||||
|
&& "POST".equalsIgnoreCase(request.getMethod())) {
|
||||||
|
www = "Basic realm=\"messenger\", charset=\"UTF-8\"";
|
||||||
|
} else {
|
||||||
|
www = "Bearer realm=\"messenger\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> body = Map.of(
|
||||||
|
"error", Map.of(
|
||||||
|
"code", "unauthorized",
|
||||||
|
"message", ex.getMessage() != null ? ex.getMessage() : "Unauthorized",
|
||||||
|
"request_id", requestId
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.UNAUTHORIZED)
|
||||||
|
.header("X-Request-Id", requestId)
|
||||||
|
.header("WWW-Authenticate", www)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(Exception.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleAllOtherExceptions(Exception ex, HttpServletRequest request) {
|
||||||
|
log.error("CRITICAL ERROR ON REQUEST: {}", request.getRequestURI(), ex);
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("internal_error", "Internal server error", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(ConstraintViolationException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleConstraintViolation(
|
||||||
|
ConstraintViolationException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", "Validation Failed", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||||
|
public ResponseEntity<ErrorResponse> handleDataIntegrity(
|
||||||
|
DataIntegrityViolationException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("conflict", "Conflict", reqId)
|
||||||
|
);
|
||||||
|
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||||
|
public ResponseEntity<?> handleTypeMismatch(
|
||||||
|
MethodArgumentTypeMismatchException ex,
|
||||||
|
HttpServletRequest request
|
||||||
|
) {
|
||||||
|
String reqId = resolveRequestId(request);
|
||||||
|
String message = "Invalid parameter";
|
||||||
|
if (ex.getRequiredType() == UUID.class) {
|
||||||
|
message = "Invalid UUID";
|
||||||
|
}
|
||||||
|
ErrorResponse body = new ErrorResponse(
|
||||||
|
new ErrorDetail("invalid_request", "Invalid UUID", reqId)
|
||||||
|
);
|
||||||
|
// Error body: code invalid_request, request_id = reqId
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", reqId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
public class NotFoundException extends RuntimeException {
|
||||||
|
public NotFoundException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
|
||||||
|
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||||
|
public class UnauthorizedException extends RuntimeException {
|
||||||
|
private final String wwwAuthenticate;
|
||||||
|
|
||||||
|
public UnauthorizedException(String wwwAuthenticate) {
|
||||||
|
super("Unauthorized");
|
||||||
|
this.wwwAuthenticate = wwwAuthenticate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getWwwAuthenticate() {
|
||||||
|
return wwwAuthenticate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package org.example.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
|
||||||
|
@ResponseStatus(HttpStatus.CONFLICT)
|
||||||
|
public class UserAlreadyExistsException extends RuntimeException {
|
||||||
|
public UserAlreadyExistsException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "attachments")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class Attachment {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(name = "chat_id")
|
||||||
|
@JsonProperty("chat_id")
|
||||||
|
private UUID chatId;
|
||||||
|
|
||||||
|
@Column(name = "uploader_id")
|
||||||
|
@JsonProperty("owner_id")
|
||||||
|
private UUID ownerId;
|
||||||
|
|
||||||
|
@Column(name = "original_filename")
|
||||||
|
@JsonProperty("filename")
|
||||||
|
private String filename;
|
||||||
|
|
||||||
|
@Column(name = "content_type")
|
||||||
|
@JsonProperty("content_type")
|
||||||
|
private String contentType;
|
||||||
|
|
||||||
|
@Column(name = "size_bytes")
|
||||||
|
@JsonProperty("size_bytes")
|
||||||
|
private long sizeBytes;
|
||||||
|
|
||||||
|
@Column(name = "checksum_sha256")
|
||||||
|
@JsonProperty("sha256")
|
||||||
|
private String sha256;
|
||||||
|
|
||||||
|
@Column(name = "status")
|
||||||
|
@JsonProperty("status")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
@JsonProperty("variants")
|
||||||
|
private List<VariantResponse> variants;
|
||||||
|
|
||||||
|
@Column(name = "error_code")
|
||||||
|
@JsonProperty("error_code")
|
||||||
|
private String errorCode;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at")
|
||||||
|
@JsonProperty("updated_at")
|
||||||
|
private Instant updatedAt;
|
||||||
|
|
||||||
|
@Column(name = "object_key")
|
||||||
|
private String objectKey;
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "chats")
|
||||||
|
@Setter
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||||
|
public class Chat {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(nullable = false, length = 100)
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "chat", fetch = FetchType.LAZY)
|
||||||
|
@JsonIgnore
|
||||||
|
@Builder.Default
|
||||||
|
private List<ChatMember> members =new ArrayList<>();
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
@JsonProperty("member_ids")
|
||||||
|
private List<UUID> memberIds;
|
||||||
|
public void setMemberIdsForResponse(List<UUID> ids) {
|
||||||
|
this.memberIds = ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "chat_members")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@IdClass(ChatMember.ChatMemberId.class)
|
||||||
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||||
|
public class ChatMember {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "chat_id")
|
||||||
|
private UUID chatId;
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "user_id", nullable = false)
|
||||||
|
private UUID userId;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||||
|
@JoinColumn(name = "chat_id", insertable = false, updatable = false)
|
||||||
|
private Chat chat;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||||
|
@JoinColumn(name = "user_id", insertable = false, updatable = false)
|
||||||
|
private User user;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "joined_at", nullable = false, updatable = false)
|
||||||
|
private Instant joinedAt;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ChatMemberId implements Serializable {
|
||||||
|
private UUID chatId;
|
||||||
|
private UUID userId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "idempotency_keys",
|
||||||
|
uniqueConstraints = @UniqueConstraint(
|
||||||
|
name = "uq_idempotency_user_chat_key",
|
||||||
|
columnNames = {"user_id", "chat_id", "idempotency_key"}))
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class IdempotencyKey {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(name = "user_id", nullable = false)
|
||||||
|
private UUID userId;
|
||||||
|
|
||||||
|
|
||||||
|
@Column(name = "chat_id", nullable = false)
|
||||||
|
private UUID chatId;
|
||||||
|
|
||||||
|
@Column(name = "idempotency_key", nullable = false)
|
||||||
|
private String idempotencyKey;
|
||||||
|
|
||||||
|
@Column(name = "request_hash", nullable = false)
|
||||||
|
private String requestHash;
|
||||||
|
|
||||||
|
@Column(name = "message_id", nullable = false)
|
||||||
|
private UUID messageId;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "messages")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||||
|
public class Message {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(name = "chat_id", nullable = false)
|
||||||
|
@JsonProperty("chat_id")
|
||||||
|
private UUID chatId;
|
||||||
|
|
||||||
|
@Column(name = "sender_id", nullable = false)
|
||||||
|
@JsonProperty("sender_id")
|
||||||
|
private UUID senderId;
|
||||||
|
|
||||||
|
@Column(nullable = false, columnDefinition = "TEXT")
|
||||||
|
private String text;
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
private List<UUID> attachmentIds;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "message_attachments")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@IdClass(MessageAttachment.PK.class)
|
||||||
|
public class MessageAttachment {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "message_id", nullable = false)
|
||||||
|
private UUID messageId;
|
||||||
|
|
||||||
|
@Column(name = "attachment_id", nullable = false)
|
||||||
|
private UUID attachmentId;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class PK implements Serializable {
|
||||||
|
private UUID messageId;
|
||||||
|
private UUID attachmentId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sessions")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class Session {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(name = "user_id", nullable = false)
|
||||||
|
private UUID userId;
|
||||||
|
|
||||||
|
@Column(name = "token", nullable = false, unique = true, length = 64)
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@Column(name = "expires_at", nullable = false)
|
||||||
|
private Instant expiresAt;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false)
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
@Column(name = "revoked_at")
|
||||||
|
private Instant revokedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
void prePersist() {
|
||||||
|
if (id == null) {
|
||||||
|
id = UUID.randomUUID();
|
||||||
|
}
|
||||||
|
if (createdAt == null) {
|
||||||
|
createdAt = Instant.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isActive(Instant now) {
|
||||||
|
return revokedAt == null && expiresAt.isAfter(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "users")
|
||||||
|
@Setter
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||||
|
public class User {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(nullable = false, unique = true, length = 64)
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Column(name = "display_name", nullable = false, length = 128)
|
||||||
|
@JsonProperty("display_name")
|
||||||
|
private String displayName;
|
||||||
|
|
||||||
|
@JsonIgnore
|
||||||
|
@Column(name = "password")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private Instant createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class VariantResponse {
|
||||||
|
|
||||||
|
@JsonProperty("name")
|
||||||
|
String name;
|
||||||
|
|
||||||
|
@JsonProperty("content_type")
|
||||||
|
String contentType;
|
||||||
|
|
||||||
|
@JsonProperty("size_bytes")
|
||||||
|
long sizeBytes;
|
||||||
|
|
||||||
|
@JsonProperty("width")
|
||||||
|
int width;
|
||||||
|
|
||||||
|
@JsonProperty("height")
|
||||||
|
int height;
|
||||||
|
|
||||||
|
@JsonProperty("sha256")
|
||||||
|
String sha256;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.LidoApplication;
|
||||||
|
import org.example.model.Attachment;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface AttachmentRepository extends JpaRepository<Attachment, UUID> {
|
||||||
|
|
||||||
|
Optional<Attachment> findByIdAndChatId(UUID id, UUID chatId);
|
||||||
|
|
||||||
|
List<Attachment> findByIdInAndChatId(Collection<UUID> ids, UUID chatId);
|
||||||
|
|
||||||
|
boolean existsByIdAndChatId(UUID id, UUID chatId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.ChatMember;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface ChatMemberRepository extends JpaRepository<ChatMember, UUID> {
|
||||||
|
List<ChatMember> findByUserId(UUID userId);
|
||||||
|
List<ChatMember> findByChatId(UUID chatId);
|
||||||
|
boolean existsByChatIdAndUserId(UUID chatId, UUID userId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.Chat;
|
||||||
|
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 java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface ChatRepository extends JpaRepository<Chat, UUID> {
|
||||||
|
@Query("""
|
||||||
|
SELECT c FROM Chat c
|
||||||
|
JOIN ChatMember m ON m.chatId = c.id
|
||||||
|
WHERE m.userId = :userId
|
||||||
|
ORDER BY c.createdAt ASC, c.id ASC
|
||||||
|
""")
|
||||||
|
List<Chat> findForUserOrderByCreatedAtAsc(
|
||||||
|
@Param("userId") UUID userId,
|
||||||
|
Pageable pageable);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.IdempotencyKey;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface IdempotencyKeyRepository extends JpaRepository<IdempotencyKey, UUID> {
|
||||||
|
Optional<IdempotencyKey> findByUserIdAndChatIdAndIdempotencyKey(
|
||||||
|
UUID userId,
|
||||||
|
UUID chatId,
|
||||||
|
String idempotencyKey
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface MessageAttachmentRepository extends JpaRepository<MessageAttachment, MessageAttachment.PK> {
|
||||||
|
|
||||||
|
List<MessageAttachment> findByMessageId(UUID messageId);
|
||||||
|
|
||||||
|
List<MessageAttachment> findByMessageIdIn(Collection<UUID> messageIds);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.Message;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface MessageRepository extends JpaRepository<Message, UUID> {
|
||||||
|
|
||||||
|
List<Message> findByChatIdOrderByCreatedAtAscIdAsc(UUID chatId, Pageable pageable);
|
||||||
|
|
||||||
|
@Query("""
|
||||||
|
SELECT m FROM Message m
|
||||||
|
WHERE m.chatId = :chatId
|
||||||
|
AND (m.createdAt > :createdAt
|
||||||
|
OR (m.createdAt = :createdAt AND m.id > :id))
|
||||||
|
ORDER BY m.createdAt ASC, m.id ASC
|
||||||
|
""")
|
||||||
|
List<Message> findNextPage(
|
||||||
|
@Param("chatId") UUID chatId,
|
||||||
|
@Param("createdAt") Instant createdAt,
|
||||||
|
@Param("id") UUID id,
|
||||||
|
Pageable pageable
|
||||||
|
);
|
||||||
|
|
||||||
|
Optional<Message> findByIdAndChatId(UUID id, UUID chatId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.Session;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface SessionRepository extends JpaRepository<Session, UUID> {
|
||||||
|
Optional<Session> findByToken(String token);
|
||||||
|
void deleteByUserId(UUID userId);
|
||||||
|
List<Session> findByUserIdOrderByCreatedAtDesc(UUID userId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface UserRepository extends JpaRepository<User, UUID> {
|
||||||
|
boolean existsByUsername(String username);
|
||||||
|
Optional<User> findByUsername(String username);
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.config.ImageUploadValidator;
|
||||||
|
import org.example.dto.response.AttachmentResponse;
|
||||||
|
import org.example.exception.BadRequestException;
|
||||||
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.model.Attachment;
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.example.repository.AttachmentRepository;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AttachmentService {
|
||||||
|
|
||||||
|
private final AttachmentRepository attachmentRepository;
|
||||||
|
private final S3StorageService s3StorageService;
|
||||||
|
private final ImageUploadValidator validator;
|
||||||
|
private final ChatService chatService;
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
private static final long ORPHAN_GRACE_MS = 60L * 60L * 1000L; // 1 hour grace period
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public AttachmentResponse upload(
|
||||||
|
UUID chatId,
|
||||||
|
String filename,
|
||||||
|
String contentTypeHeader,
|
||||||
|
InputStream body
|
||||||
|
) throws IOException {
|
||||||
|
User user = userService.getCurrentUser();
|
||||||
|
chatService.requireMember(chatId);
|
||||||
|
|
||||||
|
ImageUploadValidator.ValidatedImage img = validator.validate(filename, body);
|
||||||
|
|
||||||
|
UUID id = UUID.randomUUID();
|
||||||
|
String objectKey = "chats/" + chatId + "/" + id;
|
||||||
|
|
||||||
|
boolean s3Ok = false;
|
||||||
|
try (InputStream fileIn = Files.newInputStream(img.tempFile())) {
|
||||||
|
s3StorageService.put(
|
||||||
|
objectKey,
|
||||||
|
fileIn,
|
||||||
|
img.sizeBytes(),
|
||||||
|
img.contentType()
|
||||||
|
);
|
||||||
|
s3Ok = true;
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(img.tempFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
Attachment saved;
|
||||||
|
try {
|
||||||
|
saved = attachmentRepository.save(Attachment.builder()
|
||||||
|
.id(id)
|
||||||
|
.chatId(chatId)
|
||||||
|
.ownerId(user.getId())
|
||||||
|
.objectKey(objectKey)
|
||||||
|
.filename(img.safeFilename())
|
||||||
|
.contentType(img.contentType())
|
||||||
|
.sizeBytes(img.sizeBytes())
|
||||||
|
.sha256(img.sha256Hex())
|
||||||
|
.status("ready")
|
||||||
|
.errorCode(null)
|
||||||
|
.variants(List.of())
|
||||||
|
.createdAt(Instant.now())
|
||||||
|
.updatedAt(Instant.now())
|
||||||
|
.build());
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (s3Ok) {
|
||||||
|
try {
|
||||||
|
s3StorageService.delete(objectKey);
|
||||||
|
} catch (Exception deleteEx) {
|
||||||
|
// orphan will be reclaimed by the reconciler
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return toResponse(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Attachment getForMember(UUID attachmentId){
|
||||||
|
Attachment attachment = attachmentRepository.findById(attachmentId)
|
||||||
|
.orElseThrow(()-> new NotFoundException("Вложение не найдено"));
|
||||||
|
chatService.requireMember(attachment.getChatId());
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public AttachmentResponse getMeta(UUID attachmentId){
|
||||||
|
return toResponse(getForMember(attachmentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public void writeContent(UUID attachmentId,
|
||||||
|
String variant,
|
||||||
|
HttpServletResponse response) throws IOException {
|
||||||
|
if (variant != null && !variant.isBlank() && !"original".equals(variant)){
|
||||||
|
throw new BadRequestException("Unsupported variant");
|
||||||
|
}
|
||||||
|
|
||||||
|
Attachment attachment = getForMember(attachmentId);
|
||||||
|
response.setStatus(HttpStatus.OK.value());
|
||||||
|
response.setContentType(attachment.getContentType());
|
||||||
|
response.setContentLengthLong(attachment.getSizeBytes());
|
||||||
|
s3StorageService.getTo(attachment.getObjectKey(),
|
||||||
|
response.getOutputStream());
|
||||||
|
response.flushBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelayString = "${app.attachment.reconciler.interval-ms:300000}")
|
||||||
|
public void reconcileOrphanedObjects() {
|
||||||
|
Instant now = Instant.now();
|
||||||
|
Instant cutoff = now.minusMillis(ORPHAN_GRACE_MS);
|
||||||
|
|
||||||
|
List<Attachment> all = attachmentRepository.findAll();
|
||||||
|
java.util.Set<UUID> dbKeys = new java.util.HashSet<>();
|
||||||
|
for (Attachment a : all) {
|
||||||
|
dbKeys.add(a.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
var objects = s3StorageService.listObjects();
|
||||||
|
for (var obj : objects) {
|
||||||
|
String key = obj.key();
|
||||||
|
if (!key.startsWith("chats/")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String[] parts = key.split("/", 3);
|
||||||
|
if (parts.length < 3) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
UUID attachmentId = UUID.fromString(parts[2]);
|
||||||
|
if (!dbKeys.contains(attachmentId)) {
|
||||||
|
if (obj.lastModified().isBefore(cutoff)) {
|
||||||
|
s3StorageService.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
if (obj.lastModified().isBefore(cutoff)) {
|
||||||
|
s3StorageService.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
org.slf4j.LoggerFactory.getLogger(AttachmentService.class)
|
||||||
|
.warn("Reconciler S3 list failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static AttachmentResponse toResponse(Attachment a) {
|
||||||
|
return AttachmentResponse.builder()
|
||||||
|
.id(a.getId())
|
||||||
|
.chatId(a.getChatId())
|
||||||
|
.ownerId(a.getOwnerId())
|
||||||
|
.filename(a.getFilename())
|
||||||
|
.contentType(a.getContentType())
|
||||||
|
.sizeBytes(a.getSizeBytes())
|
||||||
|
.sha256(a.getSha256())
|
||||||
|
.status(a.getStatus())
|
||||||
|
.variants(a.getVariants() == null ? List.of() : a.getVariants())
|
||||||
|
.errorCode(a.getErrorCode())
|
||||||
|
.createdAt(a.getCreatedAt())
|
||||||
|
.updatedAt(a.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import org.example.config.TokenHasher;
|
||||||
|
import org.example.dto.response.SessionInfoResponse;
|
||||||
|
import org.example.dto.response.SessionResponse;
|
||||||
|
import org.example.dto.response.UserResponse;
|
||||||
|
import org.example.exception.UnauthorizedException;
|
||||||
|
import org.example.model.Session;
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.example.repository.SessionRepository;
|
||||||
|
import org.example.repository.UserRepository;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AuthService {
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final SessionRepository sessionRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final UserService userService;
|
||||||
|
private final CacheService cacheService;
|
||||||
|
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Value("${app.session-ttl-seconds:604800}")
|
||||||
|
private long sessionTtlSeconds;
|
||||||
|
|
||||||
|
public AuthService(
|
||||||
|
UserRepository userRepository,
|
||||||
|
SessionRepository sessionRepository,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
UserService userService,
|
||||||
|
CacheService cacheService
|
||||||
|
) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.sessionRepository = sessionRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.userService = userService;
|
||||||
|
this.cacheService = cacheService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public SessionResponse login(String username, String rawPassword) {
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||||
|
|
||||||
|
if (user.getPassword() == null
|
||||||
|
|| !passwordEncoder.matches(rawPassword, user.getPassword())) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
|
||||||
|
String rawToken = TokenHasher.newRawToken();
|
||||||
|
Instant expiresAt = Instant.now().plusSeconds(sessionTtlSeconds);
|
||||||
|
|
||||||
|
Session session = Session.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token(TokenHasher.sha256(rawToken))
|
||||||
|
.expiresAt(expiresAt)
|
||||||
|
.createdAt(Instant.now())
|
||||||
|
.build();
|
||||||
|
sessionRepository.save(session);
|
||||||
|
cacheService.put(session.getToken(), user.getId(), expiresAt);
|
||||||
|
|
||||||
|
return SessionResponse.builder()
|
||||||
|
.token(rawToken)
|
||||||
|
.tokenType("Bearer")
|
||||||
|
.expiresAt(expiresAt)
|
||||||
|
.user(UserResponse.builder()
|
||||||
|
.id(user.getId())
|
||||||
|
.username(user.getUsername())
|
||||||
|
.displayName(user.getDisplayName())
|
||||||
|
.createdAt(user.getCreatedAt())
|
||||||
|
.build())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void logout(String rawToken){
|
||||||
|
if (rawToken == null || rawToken.isBlank()){
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sessionRepository.findByToken(TokenHasher.sha256(rawToken))
|
||||||
|
.ifPresent(s -> {
|
||||||
|
s.setRevokedAt(Instant.now());
|
||||||
|
sessionRepository.save(s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void logoutCurrent(String rawToken) {
|
||||||
|
String tokenHash = TokenHasher.sha256(rawToken);
|
||||||
|
var session = sessionRepository
|
||||||
|
.findByToken(tokenHash)
|
||||||
|
.filter(s -> s.isActive(Instant.now()))
|
||||||
|
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||||
|
|
||||||
|
session.setRevokedAt(Instant.now());
|
||||||
|
sessionRepository.save(session);
|
||||||
|
cacheService.deleteSession(tokenHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private final ConcurrentHashMap<String, Object> inflight = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||||
|
if (rawToken == null || rawToken.isBlank()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
final String hash = TokenHasher.sha256(rawToken);
|
||||||
|
|
||||||
|
Optional<UUID> cachedUserId = cacheService.get(hash);
|
||||||
|
if (cachedUserId.isPresent()) {
|
||||||
|
return userRepository.findById(cachedUserId.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
Object lock = inflight.computeIfAbsent(hash, h -> new Object());
|
||||||
|
try {
|
||||||
|
synchronized (lock) {
|
||||||
|
cachedUserId = cacheService.get(hash);
|
||||||
|
if (cachedUserId.isPresent()) {
|
||||||
|
return userRepository.findById(cachedUserId.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
Instant now = Instant.now();
|
||||||
|
Optional<Session> session = sessionRepository.findByToken(hash);
|
||||||
|
if (session.isEmpty() || !session.get().isActive(now)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
Session s = session.get();
|
||||||
|
cacheService.put(hash, s.getUserId(), s.getExpiresAt());
|
||||||
|
return userRepository.findById(s.getUserId());
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
inflight.remove(hash, lock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<SessionInfoResponse> listSessionsForCurrentUser() {
|
||||||
|
User user = userService.getCurrentUser();
|
||||||
|
Instant now = Instant.now();
|
||||||
|
return sessionRepository.findByUserIdOrderByCreatedAtDesc(user.getId())
|
||||||
|
.stream()
|
||||||
|
.map(s -> SessionInfoResponse.builder()
|
||||||
|
.id(s.getId())
|
||||||
|
.createdAt(s.getCreatedAt())
|
||||||
|
.expiresAt(s.getExpiresAt())
|
||||||
|
.revokedAt(s.getRevokedAt())
|
||||||
|
.active(s.isActive(now))
|
||||||
|
.build())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CacheService {
|
||||||
|
|
||||||
|
private static final String PREFIX = "session:";
|
||||||
|
private final StringRedisTemplate redis;
|
||||||
|
|
||||||
|
public void put(String token, UUID userId, Instant expiresAt){
|
||||||
|
long ttlSec = Duration.between(Instant.now(), expiresAt).getSeconds();
|
||||||
|
if (ttlSec <= 0){
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
redis.opsForValue().set(
|
||||||
|
PREFIX + token,
|
||||||
|
userId.toString(),
|
||||||
|
ttlSec,
|
||||||
|
TimeUnit.SECONDS
|
||||||
|
);
|
||||||
|
} catch (Exception e){
|
||||||
|
log.warn("Сессия не попала в Redis");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<UUID> get(String token){
|
||||||
|
try {
|
||||||
|
String v = redis.opsForValue().get(PREFIX + token);
|
||||||
|
if (v == null || v.isBlank()){
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(UUID.fromString(v));
|
||||||
|
} catch (Exception e){
|
||||||
|
log.warn("Сессии нет в Redis");
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteSession(String token){
|
||||||
|
try {
|
||||||
|
redis.delete(PREFIX + token);
|
||||||
|
} catch (Exception e){
|
||||||
|
log.warn("Сессия не удалена в Redis");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.ChatPage;
|
||||||
|
import org.example.dto.create.CreateChatDto;
|
||||||
|
import org.example.dto.response.ChatResponse;
|
||||||
|
import org.example.dto.update.UpdateChatDto;
|
||||||
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.model.Chat;
|
||||||
|
import org.example.model.ChatMember;
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.example.repository.ChatMemberRepository;
|
||||||
|
import org.example.repository.ChatRepository;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChatService {
|
||||||
|
|
||||||
|
private final ChatRepository chatRepository;
|
||||||
|
private final ChatMemberRepository chatMemberRepository;
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public ChatResponse createChat(CreateChatDto dto) {
|
||||||
|
User currentUser = userService.getCurrentUser();
|
||||||
|
UUID currentId = currentUser.getId();
|
||||||
|
|
||||||
|
List<UUID> memberIds = dto.getMemberIds();
|
||||||
|
if (memberIds == null || memberIds.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("member_ids must not be empty");
|
||||||
|
}
|
||||||
|
long distinctCount = memberIds.stream().distinct().count();
|
||||||
|
if (distinctCount != memberIds.size()) {
|
||||||
|
throw new IllegalArgumentException("duplicate member_ids");
|
||||||
|
}
|
||||||
|
if (!memberIds.contains(currentId)) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"creator must be in member_ids");
|
||||||
|
}
|
||||||
|
for (UUID memberId : memberIds) {
|
||||||
|
if (!userService.exists(memberId)) {
|
||||||
|
throw new IllegalArgumentException("unknown member_id");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Chat chat = chatRepository.save(
|
||||||
|
Chat.builder()
|
||||||
|
.title(dto.getTitle())
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
|
||||||
|
for (UUID memberId : memberIds) {
|
||||||
|
chatMemberRepository.save(
|
||||||
|
ChatMember.builder()
|
||||||
|
.chatId(chat.getId())
|
||||||
|
.userId(memberId)
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return toResponse(chat.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public ChatResponse getChatById(UUID chatId) {
|
||||||
|
requireMember(chatId);
|
||||||
|
return toResponse(chatId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public ChatResponse getChatById(String chatId) {
|
||||||
|
return getChatById(parseUuid(chatId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public ChatPage getChatsForCurrentUser(int limit) {
|
||||||
|
if (limit < 1 || limit > 100) {
|
||||||
|
throw new IllegalArgumentException("limit must be 1..100");
|
||||||
|
}
|
||||||
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
|
List<Chat> raw = chatRepository.findForUserOrderByCreatedAtAsc(
|
||||||
|
userId,
|
||||||
|
PageRequest.of(0, limit + 1)
|
||||||
|
);
|
||||||
|
boolean hasMore = raw.size() > limit;
|
||||||
|
List<Chat> page = hasMore ? raw.subList(0, limit) : raw;
|
||||||
|
List<ChatResponse> items = page.stream()
|
||||||
|
.map(c -> toResponse(c.getId()))
|
||||||
|
.toList();
|
||||||
|
String nextCursor = null;
|
||||||
|
if (hasMore && !items.isEmpty()) {
|
||||||
|
nextCursor = items.get(items.size() - 1).getId().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ChatPage(items, nextCursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public ChatResponse updateChat(UUID id, UpdateChatDto object) {
|
||||||
|
requireMember(id);
|
||||||
|
Chat chat = chatRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||||
|
chat.setTitle(object.getTitle());
|
||||||
|
chatRepository.save(chat);
|
||||||
|
return toResponse(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public ChatResponse updateChat(String id, UpdateChatDto object) {
|
||||||
|
return updateChat(parseUuid(id), object);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteChat(UUID id) {
|
||||||
|
requireMember(id);
|
||||||
|
chatRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteChat(String id) {
|
||||||
|
deleteChat(parseUuid(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Для MessageService: текущий user — участник, иначе 404 */
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public void requireMember(UUID chatId) {
|
||||||
|
User currentUser = userService.getCurrentUser();
|
||||||
|
if (!chatRepository.existsById(chatId)
|
||||||
|
|| !chatMemberRepository.existsByChatIdAndUserId(chatId, currentUser.getId())) {
|
||||||
|
throw new NotFoundException("Чат не найден");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean isMember(UUID chatId, UUID userId) {
|
||||||
|
return chatMemberRepository.existsByChatIdAndUserId(chatId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ChatResponse toResponse(UUID chatId) {
|
||||||
|
Chat chat = chatRepository.findById(chatId)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||||
|
|
||||||
|
List<UUID> ids = chatMemberRepository.findByChatId(chatId).stream()
|
||||||
|
.map(ChatMember::getUserId)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ChatResponse.builder()
|
||||||
|
.id(chat.getId())
|
||||||
|
.title(chat.getTitle())
|
||||||
|
.memberIds(ids)
|
||||||
|
.createdAt(chat.getCreatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UUID parseUuid(String id) {
|
||||||
|
try {
|
||||||
|
return UUID.fromString(id);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new NotFoundException("Чат не найден");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.model.IdempotencyKey;
|
||||||
|
import org.example.model.Message;
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
|
import org.example.repository.IdempotencyKeyRepository;
|
||||||
|
import org.example.repository.MessageAttachmentRepository;
|
||||||
|
import org.example.repository.MessageRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Propagation;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MessageIdempotencyWriter {
|
||||||
|
|
||||||
|
private final MessageRepository messageRepository;
|
||||||
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||||
|
private final MessageAttachmentRepository messageAttachmentRepository;
|
||||||
|
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public Message insertNew(
|
||||||
|
UUID chatId,
|
||||||
|
UUID senderId,
|
||||||
|
String text,
|
||||||
|
List<UUID> attachmentIds,
|
||||||
|
String key,
|
||||||
|
String hash) {
|
||||||
|
|
||||||
|
Message message = messageRepository.save(
|
||||||
|
Message.builder()
|
||||||
|
.chatId(chatId)
|
||||||
|
.senderId(senderId)
|
||||||
|
.text(text)
|
||||||
|
.createdAt(Instant.now())
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (attachmentIds != null){
|
||||||
|
for(UUID attId : attachmentIds){
|
||||||
|
messageAttachmentRepository.save(
|
||||||
|
MessageAttachment.builder()
|
||||||
|
.messageId(message.getId())
|
||||||
|
.attachmentId(attId)
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idempotencyKeyRepository.saveAndFlush(
|
||||||
|
IdempotencyKey.builder()
|
||||||
|
.userId(senderId)
|
||||||
|
.chatId(chatId)
|
||||||
|
.idempotencyKey(key)
|
||||||
|
.requestHash(hash)
|
||||||
|
.messageId(message.getId())
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.dto.MessagePage;
|
||||||
|
import org.example.dto.create.CreateMessageDto;
|
||||||
|
import org.example.dto.update.UpdateMessageDto;
|
||||||
|
import org.example.exception.BadRequestException;
|
||||||
|
import org.example.exception.ConflictException;
|
||||||
|
import org.example.exception.ForbiddenException;
|
||||||
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.model.Attachment;
|
||||||
|
import org.example.model.IdempotencyKey;
|
||||||
|
import org.example.model.Message;
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
|
import org.example.repository.AttachmentRepository;
|
||||||
|
import org.example.repository.IdempotencyKeyRepository;
|
||||||
|
import org.example.repository.MessageAttachmentRepository;
|
||||||
|
import org.example.repository.MessageRepository;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.example.config.TokenHasher.sha256;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MessageService {
|
||||||
|
|
||||||
|
private final MessageRepository messageRepository;
|
||||||
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||||
|
private final ChatService chatService;
|
||||||
|
private final MessageIdempotencyWriter writer;
|
||||||
|
private final AttachmentRepository attachmentRepository;
|
||||||
|
private final MessageAttachmentRepository messageAttachmentRepository;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Message sendMessage(
|
||||||
|
UUID chatId,
|
||||||
|
UUID senderId,
|
||||||
|
CreateMessageDto messageObject,
|
||||||
|
String idempotencyKey) {
|
||||||
|
|
||||||
|
chatService.requireMember(chatId);
|
||||||
|
if (!chatService.isMember(chatId, senderId)) {
|
||||||
|
throw new ForbiddenException("Пользователь не является участником чата");
|
||||||
|
}
|
||||||
|
|
||||||
|
String text = messageObject.getText() == null ? "" : messageObject.getText();
|
||||||
|
|
||||||
|
List<UUID> attIds = messageObject.getAttachmentIds() == null
|
||||||
|
? List.of()
|
||||||
|
: messageObject.getAttachmentIds().stream().distinct().toList();
|
||||||
|
|
||||||
|
if (text.isBlank() && attIds.isEmpty()) {
|
||||||
|
throw new BadRequestException("text or attachment_ids required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!attIds.isEmpty()) {
|
||||||
|
List<Attachment> found = attachmentRepository.findByIdInAndChatId(attIds, chatId);
|
||||||
|
if (found.size() != attIds.size()) {
|
||||||
|
throw new BadRequestException("Invalid attachment_ids");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String key = idempotencyKey.trim();
|
||||||
|
String hash = sha256(
|
||||||
|
text + "\n" + attIds.stream()
|
||||||
|
.map(UUID::toString)
|
||||||
|
.sorted()
|
||||||
|
.collect(Collectors.joining(","))
|
||||||
|
);
|
||||||
|
|
||||||
|
Optional<IdempotencyKey> exists =
|
||||||
|
idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
||||||
|
|
||||||
|
if (exists.isPresent()) {
|
||||||
|
return messageFromIdem(exists.get(), hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Message message = writer.insertNew(chatId, senderId, text, attIds, key, hash);
|
||||||
|
message.setAttachmentIds(attIds);
|
||||||
|
return message;
|
||||||
|
} catch (DataIntegrityViolationException e) {
|
||||||
|
IdempotencyKey rec = idempotencyKeyRepository
|
||||||
|
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
||||||
|
.orElseThrow(() -> e);
|
||||||
|
return messageFromIdem(rec, hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Message messageFromIdem(IdempotencyKey row, String hash) {
|
||||||
|
if (!row.getRequestHash().equals(hash)) {
|
||||||
|
throw new ConflictException("Idempotency key conflict");
|
||||||
|
}
|
||||||
|
Message message = messageRepository.findById(row.getMessageId())
|
||||||
|
.orElseThrow(() -> new IllegalStateException("idempotency message missing"));
|
||||||
|
|
||||||
|
List<UUID> ids = messageAttachmentRepository.findByMessageId(message.getId())
|
||||||
|
.stream()
|
||||||
|
.map(MessageAttachment::getAttachmentId)
|
||||||
|
.toList();
|
||||||
|
message.setAttachmentIds(ids);
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
||||||
|
if (limit < 1 || limit > 100) {
|
||||||
|
throw new IllegalArgumentException("limit must be between 1 and 100");
|
||||||
|
}
|
||||||
|
|
||||||
|
chatService.requireMember(chatId);
|
||||||
|
if (!chatService.isMember(chatId, userId)) {
|
||||||
|
throw new NotFoundException("Чат не найден");
|
||||||
|
}
|
||||||
|
|
||||||
|
Pageable pageable = PageRequest.of(0, limit);
|
||||||
|
List<Message> items;
|
||||||
|
|
||||||
|
if (cursor == null || cursor.isBlank()) {
|
||||||
|
items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable);
|
||||||
|
} else {
|
||||||
|
UUID cursorId;
|
||||||
|
try {
|
||||||
|
cursorId = UUID.fromString(cursor.trim());
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new IllegalArgumentException("Invalid cursor");
|
||||||
|
}
|
||||||
|
|
||||||
|
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor"));
|
||||||
|
|
||||||
|
items = messageRepository.findNextPage(
|
||||||
|
chatId,
|
||||||
|
cursorMsg.getCreatedAt(),
|
||||||
|
cursorMsg.getId(),
|
||||||
|
pageable
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String nextCursor = null;
|
||||||
|
if (items.size() == limit && !items.isEmpty()) {
|
||||||
|
Message last = items.get(items.size() - 1);
|
||||||
|
boolean hasMore = !messageRepository
|
||||||
|
.findNextPage(
|
||||||
|
chatId,
|
||||||
|
last.getCreatedAt(),
|
||||||
|
last.getId(),
|
||||||
|
PageRequest.of(0, 1)
|
||||||
|
)
|
||||||
|
.isEmpty();
|
||||||
|
if (hasMore) {
|
||||||
|
nextCursor = last.getId().toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!items.isEmpty()) {
|
||||||
|
List<UUID> msgIds = items.stream().map(Message::getId).toList();
|
||||||
|
List<MessageAttachment> links =
|
||||||
|
messageAttachmentRepository.findByMessageIdIn(msgIds);
|
||||||
|
|
||||||
|
Map<UUID, List<UUID>> byMsg = new HashMap<>();
|
||||||
|
for (MessageAttachment link : links) {
|
||||||
|
byMsg.computeIfAbsent(link.getMessageId(), k -> new ArrayList<>())
|
||||||
|
.add(link.getAttachmentId());
|
||||||
|
}
|
||||||
|
for (Message m : items) {
|
||||||
|
m.setAttachmentIds(byMsg.getOrDefault(m.getId(), List.of()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (Message m : items) {
|
||||||
|
m.setAttachmentIds(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MessagePage(items, nextCursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public MessagePage getMessage(String chatId, String userId, String cursor, int limit){
|
||||||
|
return getMessage(parseUuid(chatId, true), parseUuid(userId, false), cursor, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Message updateMessage(UUID chatId, UUID messageId, UUID userId, UpdateMessageDto object) {
|
||||||
|
chatService.requireMember(chatId);
|
||||||
|
Message message = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Сообщение не найден"));
|
||||||
|
if (!message.getSenderId().equals(userId)){
|
||||||
|
throw new ForbiddenException("Вы не можете редактировать чужие сообщения");
|
||||||
|
}
|
||||||
|
message.setText(object.getText());
|
||||||
|
return messageRepository.save(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Message updateMessage(String chatId, String messageId, String userId, UpdateMessageDto object) {
|
||||||
|
return updateMessage(
|
||||||
|
parseUuid(chatId, true),
|
||||||
|
parseUuid(messageId, true),
|
||||||
|
parseUuid(userId, false),
|
||||||
|
object);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteMessage(UUID chatId, UUID messageId, UUID userId) {
|
||||||
|
chatService.getChatById(chatId);
|
||||||
|
|
||||||
|
Message msg = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Сообщение не найдено"));
|
||||||
|
|
||||||
|
if (!msg.getSenderId().equals(userId)) {
|
||||||
|
throw new ForbiddenException("Вы не можете удалять сообщения других участников");
|
||||||
|
}
|
||||||
|
messageRepository.delete(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteMessage(String chatId, String messageId, String userId) {
|
||||||
|
deleteMessage(
|
||||||
|
parseUuid(chatId, true),
|
||||||
|
parseUuid(messageId, true),
|
||||||
|
parseUuid(userId, false)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static UUID parseUuid(String value, boolean notFoundOnBad) {
|
||||||
|
try {
|
||||||
|
return UUID.fromString(value.trim());
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (notFoundOnBad) {
|
||||||
|
throw new NotFoundException("Не найдено");
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Invalid id");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.config.S3Properties;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import software.amazon.awssdk.core.sync.RequestBody;
|
||||||
|
import software.amazon.awssdk.core.sync.ResponseTransformer;
|
||||||
|
import software.amazon.awssdk.services.s3.S3Client;
|
||||||
|
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||||
|
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||||
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
||||||
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||||
|
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||||
|
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class S3StorageService {
|
||||||
|
|
||||||
|
private final S3Client s3Client;
|
||||||
|
private final S3Properties properties;
|
||||||
|
|
||||||
|
public record S3ObjectInfo(String key, Instant lastModified) {}
|
||||||
|
|
||||||
|
public void put(
|
||||||
|
String objectKey,
|
||||||
|
InputStream in,
|
||||||
|
long sizeBytes,
|
||||||
|
String contentType){
|
||||||
|
|
||||||
|
PutObjectRequest request = PutObjectRequest.builder()
|
||||||
|
.bucket(properties.getBucket())
|
||||||
|
.key(objectKey)
|
||||||
|
.contentType(contentType)
|
||||||
|
.contentLength(sizeBytes)
|
||||||
|
.build();
|
||||||
|
s3Client.putObject(request, RequestBody.fromInputStream(in, sizeBytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void getTo(String objectKey, OutputStream out){
|
||||||
|
GetObjectRequest request = GetObjectRequest.builder()
|
||||||
|
.bucket(properties.getBucket())
|
||||||
|
.key(objectKey)
|
||||||
|
.build();
|
||||||
|
s3Client.getObject(request, ResponseTransformer.toOutputStream(out));
|
||||||
|
}
|
||||||
|
|
||||||
|
public InputStream getStream(String objectKey){
|
||||||
|
GetObjectRequest request = GetObjectRequest.builder()
|
||||||
|
.bucket(properties.getBucket())
|
||||||
|
.key(objectKey)
|
||||||
|
.build();
|
||||||
|
return s3Client.getObject(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String objectKey){
|
||||||
|
s3Client.deleteObject(DeleteObjectRequest.builder()
|
||||||
|
.bucket(properties.getBucket())
|
||||||
|
.key(objectKey)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<S3ObjectInfo> listObjects(){
|
||||||
|
List<S3ObjectInfo> result = new ArrayList<>();
|
||||||
|
ListObjectsV2Request request = ListObjectsV2Request.builder()
|
||||||
|
.bucket(properties.getBucket())
|
||||||
|
.build();
|
||||||
|
ListObjectsV2Response response = s3Client.listObjectsV2(request);
|
||||||
|
for (S3Object obj : response.contents()) {
|
||||||
|
result.add(new S3ObjectInfo(
|
||||||
|
obj.key(),
|
||||||
|
obj.lastModified() != null ? obj.lastModified() : Instant.now()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package org.example.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.example.config.UserContext;
|
||||||
|
import org.example.dto.create.CreateUserDto;
|
||||||
|
import org.example.dto.update.UpdateUserDto;
|
||||||
|
import org.example.exception.ForbiddenException;
|
||||||
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.exception.UnauthorizedException;
|
||||||
|
import org.example.exception.UserAlreadyExistsException;
|
||||||
|
import org.example.model.User;
|
||||||
|
import org.example.repository.UserRepository;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserService {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public User createUser(CreateUserDto userObject) {
|
||||||
|
if (userRepository.existsByUsername(userObject.getUsername())) {
|
||||||
|
throw new UserAlreadyExistsException("Пользователь с таким username уже существует: " + userObject.getUsername());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
User user = User.builder()
|
||||||
|
.username(userObject.getUsername())
|
||||||
|
.displayName(userObject.getDisplayName())
|
||||||
|
.password(passwordEncoder.encode(userObject.getPassword()))
|
||||||
|
.build();
|
||||||
|
return userRepository.save(user);
|
||||||
|
} catch (DataIntegrityViolationException e){
|
||||||
|
throw new UserAlreadyExistsException(
|
||||||
|
"Пользователь с таким username уже есть: " + userObject.getUsername());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public User getCurrentUser() {
|
||||||
|
User user = UserContext.getCurrentUser();
|
||||||
|
if (user == null) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private User requireCurrentUser() {
|
||||||
|
User user = UserContext.getCurrentUser();
|
||||||
|
if (user == null) {
|
||||||
|
throw new UnauthorizedException("Unauthorized");
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public User getUserById(UUID id) {
|
||||||
|
requireCurrentUser();
|
||||||
|
return userRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public User updateUser(UUID id, UpdateUserDto dto) {
|
||||||
|
User me = requireCurrentUser();
|
||||||
|
if (!me.getId().equals(id)) {
|
||||||
|
throw new ForbiddenException("Forbidden");
|
||||||
|
}
|
||||||
|
User user = userRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
||||||
|
user.setDisplayName(dto.getDisplayName());
|
||||||
|
return userRepository.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteUser(UUID id) {
|
||||||
|
User me = requireCurrentUser();
|
||||||
|
if (!me.getId().equals(id)) {
|
||||||
|
throw new ForbiddenException("Forbidden");
|
||||||
|
}
|
||||||
|
if (!userRepository.existsById(id)) {
|
||||||
|
throw new NotFoundException("Пользователь не найден");
|
||||||
|
}
|
||||||
|
userRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public User updateUser(String id, UpdateUserDto updateObject) {
|
||||||
|
return updateUser(parseUuid(id), updateObject);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteUser(String id) {
|
||||||
|
deleteUser(parseUuid(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean exists(UUID id) {
|
||||||
|
return userRepository.existsById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean exists(String id) {
|
||||||
|
try {
|
||||||
|
return exists(parseUuid(id));
|
||||||
|
}catch (IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UUID parseUuid(String id) {
|
||||||
|
try {
|
||||||
|
return UUID.fromString(id);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
spring:
|
||||||
|
jackson:
|
||||||
|
property-naming-strategy: SNAKE_CASE
|
||||||
|
deserialization:
|
||||||
|
fail-on-unknown-properties: true
|
||||||
|
lifecycle:
|
||||||
|
timeout-per-shutdown-phase: 20s
|
||||||
|
servlet:
|
||||||
|
multipart:
|
||||||
|
max-file-size: 10MB
|
||||||
|
max-request-size: 12MB
|
||||||
|
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5433/lido_db}
|
||||||
|
username: ${SPRING_DATASOURCE_USERNAME:user}
|
||||||
|
password: ${SPRING_DATASOURCE_PASSWORD:user}
|
||||||
|
hikari:
|
||||||
|
maximum-pool-size: 10
|
||||||
|
minimum-idle: 2
|
||||||
|
connection-timeout: 3000
|
||||||
|
idle-timeout: 600000
|
||||||
|
max-lifetime: 1800000
|
||||||
|
validation-timeout: 2000
|
||||||
|
jpa:
|
||||||
|
open-in-view: false
|
||||||
|
hibernate:
|
||||||
|
ddl-auto: validate
|
||||||
|
properties:
|
||||||
|
hibernate:
|
||||||
|
jdbc:
|
||||||
|
time_zone: UTC
|
||||||
|
flyway:
|
||||||
|
enabled: ${FLYWAY_ENABLED:false}
|
||||||
|
locations: classpath:db/migration
|
||||||
|
redis:
|
||||||
|
host: ${SPRING_DATA_REDIS_HOST:localhost}
|
||||||
|
port: ${SPRING_DATA_REDIS_PORT:6379}
|
||||||
|
timeout: 300ms
|
||||||
|
connect-timeout: 300ms
|
||||||
|
lettuce:
|
||||||
|
shutdown-timeout: 100ms
|
||||||
|
repositories:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
server:
|
||||||
|
address: 0.0.0.0
|
||||||
|
port: 8080
|
||||||
|
shutdown: graceful
|
||||||
|
tomcat:
|
||||||
|
connection-timeout: 30s
|
||||||
|
keep-alive-timeout: 30s
|
||||||
|
max-swallow-size: -1
|
||||||
|
|
||||||
|
app:
|
||||||
|
session-ttl-seconds: ${SESSION_TTL_SECONDS:604800}
|
||||||
|
s3:
|
||||||
|
endpoint: ${S3_ENDPOINT:http://minio:9000}
|
||||||
|
region: ${S3_REGION:eu-east-1}
|
||||||
|
bucket: ${S3_BUCKET:messenger-attachments}
|
||||||
|
access-key: ${S3_ACCESS_KEY}
|
||||||
|
secret-key: ${S3_SECRET_KEY}
|
||||||
|
path-style: true
|
||||||
|
attachment:
|
||||||
|
reconciler:
|
||||||
|
interval-ms: ${ATTACHMENT_RECONCILER_INTERVAL_MS:300000}
|
||||||
|
|
||||||
|
logging:
|
||||||
|
pattern:
|
||||||
|
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} [req_id: %X{X-Request-Id}] - %msg%n"
|
||||||
|
level:
|
||||||
|
root=INFO:
|
||||||
|
org:
|
||||||
|
springframework:
|
||||||
|
web=DEBUG:
|
||||||
|
web:
|
||||||
|
filter:
|
||||||
|
CommonsRequestLoggingFilter=DEBUG:
|
||||||
|
:servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver: DEBUG
|
||||||
|
|
||||||
|
management:
|
||||||
|
endpoints:
|
||||||
|
web:
|
||||||
|
exposure:
|
||||||
|
include=health:
|
||||||
|
health:
|
||||||
|
show-details=always:
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE messages
|
||||||
|
DROP CONSTRAINT IF EXISTS chk_messages_text_nonempty;
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(64) NOT NULL,
|
||||||
|
display_name VARCHAR(128) NOT NULL,
|
||||||
|
password VARCHAR(255),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_users_username UNIQUE (username)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(32) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
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,
|
||||||
|
joined_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_chat_members_user ON chat_members (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT chk_messages_text_nonempty CHECK (char_length(trim(text)) > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_messages_chat_created_id
|
||||||
|
ON messages (chat_id, created_at DESC, id DESC);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
CREATE TABLE sessions (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token VARCHAR(64) NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
revoked_at TIMESTAMPTZ NULL,
|
||||||
|
CONSTRAINT uq_sessions_token_hash UNIQUE (token)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sessions_user_id ON sessions (user_id);
|
||||||
|
CREATE INDEX idx_sessions_expires_at ON sessions (expires_at);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
DROP INDEX IF EXISTS idx_messages_chat_created_id;
|
||||||
|
|
||||||
|
CREATE INDEX idx_messages_chat_created_id
|
||||||
|
ON messages (chat_id, created_at ASC, id ASC);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE chats
|
||||||
|
ALTER COLUMN title TYPE VARCHAR(100);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
CREATE TABLE idempotency_keys (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_idempotency_user_chat_key
|
||||||
|
UNIQUE (user_id, chat_id, idempotency_key)
|
||||||
|
);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE idempotency_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS request_hash VARCHAR(64) NOT NULL DEFAULT '';
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE attachments (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
uploader_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
object_key VARCHAR(512) NOT NULL,
|
||||||
|
original_filename VARCHAR(255) NOT NULL,
|
||||||
|
content_type VARCHAR(128) NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
|
||||||
|
checksum_sha256 CHAR(64) NOT NULL,
|
||||||
|
width INT,
|
||||||
|
height INT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_attachments_object_key UNIQUE (object_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_attachments_chat_id ON attachments (chat_id);
|
||||||
|
CREATE INDEX idx_attachments_uploader_id ON attachments (uploader_id);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE message_attachments (
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT,
|
||||||
|
PRIMARY KEY (message_id, attachment_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_message_attachments_attachment
|
||||||
|
ON message_attachments (attachment_id);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'ready',
|
||||||
|
ADD COLUMN IF NOT EXISTS error_code VARCHAR(64),
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//package org.example;
|
||||||
|
//
|
||||||
|
//import org.junit.jupiter.api.DisplayName;
|
||||||
|
//import org.junit.jupiter.api.Test;
|
||||||
|
//import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
//import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
//import org.springframework.http.MediaType;
|
||||||
|
//import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
//
|
||||||
|
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
//
|
||||||
|
//@SpringBootTest
|
||||||
|
//@AutoConfigureMockMvc
|
||||||
|
//public class ApiIntegrationTest {
|
||||||
|
//
|
||||||
|
// @Autowired
|
||||||
|
// private MockMvc mockMvc;
|
||||||
|
// @Test
|
||||||
|
// @DisplayName("400 1. Неверный / битый JSON должен возвращать 400 Bad Request")
|
||||||
|
// void shouldReturn400ForMalformedJson() throws Exception {
|
||||||
|
// String malformedJson = "{\"username\": \"bad_json\", \"display_name\":}";
|
||||||
|
//
|
||||||
|
// mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content(malformedJson))
|
||||||
|
// .andExpect(status().isBadRequest());
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test
|
||||||
|
// @DisplayName("400 2. Валидация: пустой username должен возвращать 400 Bad Request")
|
||||||
|
// void shouldReturn400ForEmptyUsername() throws Exception {
|
||||||
|
// String invalidJson = "{\"username\": \"\", \"display_name\": \"User\"}";
|
||||||
|
//
|
||||||
|
// mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content(invalidJson))
|
||||||
|
// .andExpect(status().isBadRequest());
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test
|
||||||
|
// @DisplayName("404 3. Неучастник чата получает 404 (чат скрыт)")
|
||||||
|
// void shouldReturn404WhenUserIsNotChatMember() throws Exception {
|
||||||
|
// String aliceJson = mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"username\": \"alice_test\", \"display_name\": \"Alice\"}"))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String aliceId = extractId(aliceJson);
|
||||||
|
//
|
||||||
|
// String bobJson = mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"username\": \"bob_test\", \"display_name\": \"Bob\"}"))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String bobId = extractId(bobJson);
|
||||||
|
//
|
||||||
|
// String spyJson = mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"username\": \"spy_test\", \"display_name\": \"Spy\"}"))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String spyId = extractId(spyJson);
|
||||||
|
//
|
||||||
|
// String chatJson = String.format(
|
||||||
|
// "{\"title\":\"Private\", \"member_ids\":[\"%s\",\"%s\"]}", aliceId, bobId);
|
||||||
|
//
|
||||||
|
// String chat = mockMvc.perform(post("/api/v1/chats")
|
||||||
|
// .header("X-User-Id", aliceId) // ← обязательно!
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content(chatJson))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String chatId = extractId(chat);
|
||||||
|
//
|
||||||
|
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||||
|
// .header("X-User-Id", spyId)
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"text\": \"Secret message\"}"))
|
||||||
|
// .andExpect(status().isNotFound());
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test
|
||||||
|
// @DisplayName("200 4. Пагинация: получение ограниченного числа сообщений по limit")
|
||||||
|
// void shouldPaginateMessagesWithLimit() throws Exception {
|
||||||
|
// String userJson = mockMvc.perform(post("/api/v1/users")
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"username\": \"paginator\", \"display_name\": \"Paginator\"}"))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String userId = extractId(userJson);
|
||||||
|
//
|
||||||
|
// String chat = mockMvc.perform(post("/api/v1/chats")
|
||||||
|
// .header("X-User-Id", userId)
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content(String.format(
|
||||||
|
// "{\"title\":\"Paginated Chat\", \"member_ids\":[\"%s\"]}", userId)))
|
||||||
|
// .andExpect(status().isCreated())
|
||||||
|
// .andReturn().getResponse().getContentAsString();
|
||||||
|
// String chatId = extractId(chat);
|
||||||
|
//
|
||||||
|
// for (int i = 1; i <= 3; i++) {
|
||||||
|
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||||
|
// .header("X-User-Id", userId)
|
||||||
|
// .contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .content("{\"text\": \"Msg " + i + "\"}"))
|
||||||
|
// .andExpect(status().isCreated());
|
||||||
|
// }
|
||||||
|
// mockMvc.perform(get("/api/v1/chats/" + chatId + "/messages")
|
||||||
|
// .param("limit", "2")
|
||||||
|
// .header("X-User-Id", userId))
|
||||||
|
// .andExpect(status().isOk())
|
||||||
|
// .andExpect(jsonPath("$.items.length()").value(2))
|
||||||
|
// .andExpect(jsonPath("$.next_cursor").isNotEmpty());
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private String extractId(String json) {
|
||||||
|
// return json.split("\"id\":\"")[1].split("\"")[0];
|
||||||
|
// }
|
||||||
|
//}
|
||||||
@@ -1,37 +1,42 @@
|
|||||||
# Отчёт — лабораторная 4
|
# Отчёт — лабораторная 4
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Гуреев Дмитрий, БПИ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 4
|
||||||
- Commit/PR: TODO после публикации
|
- PR: **
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Источники и ИИ: документация Spring Boot 3, PostgreSQL 16, Redis 7, nginx, Flyway, k6, MiniO; консультации ИИ по архитектуре multi-instance, health/readiness, идемпотентности и методике эксперимента.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
1. Скопировать `compose.example.yaml` в `docker-compose.yml`, заполнить локальный `.env` (секреты не вставлять в репозиторий).
|
||||||
|
2. `docker compose --env-file .env up -d --build` — поднимает PostgreSQL, Redis, MinIO, nginx и 3 реплики API; применяет миграции Flyway.
|
||||||
|
3. Дождаться `/health/ready` на всех репликах API.
|
||||||
|
4. `make test BASE_URL=http://localhost:8080` — публичный smoke-сценарий.
|
||||||
|
5. Остановка: `docker compose down`. Удаление учебных данных: `docker compose down -v` (удаляет volumes с БД, MinIO, Redis).
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Клиент → nginx LB → API × 3 → PostgreSQL (метаданные) + MinIO (байты в приватном bucket). Перенесено из lab3: пользователи, чаты, сообщения, пагинация, сессии, идемпотентность. Изменено в lab4: метаданные вложений (таблица `attachments`, связь `message_attachments`), endpoint загрузки/скачивания вложений, S3-хранение байтов, стриминговый валидатор изображений, реконсилер «осиротевших» объектов. Переменные из `.env` соответствуют префиксам `app.s3.*`, `SPRING_DATASOURCE_*`, `SESSION_TTL_SECONDS`.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | `make test BASE_URL=http://localhost:8080` | `PASS: lab4 public API scenario` | tests/smoke.py |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Уровень 3: POST вложения 201 ready, download побайтно, message с attachment_ids | smoke-сценарий | Вложение загружается со статусом ready, скачивается с совпадающим SHA-256 | tests/smoke.py, AttachmentService.java |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Уровень 3: PNG/JPEG ≤10 MiB, MIME по содержимому, filename валидация | ImageUploadValidator | 400 на недопустимый MIME, размер >10 MiB, опасное имя файла | Lido/src/main/java/org/example/config/ImageUploadValidator.java |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Уровень 4: тесты на большой файл, повреждённый, подмену MIME, чужой attachment_id, другой чат; без 500 | tests/smoke.py (Lab 4 блок) | 400 на все пользовательские ошибки, нет 500 | tests/smoke.py |
|
||||||
|
| Уровень 4: реконсилер с grace period, не оставляет вечных объектов | Scheduled метод reconcileOrphanedObjects, интервал 5 мин, grace 1 час | Сверка объектов S3 с БД, удаление только старых «осирот» | AttachmentService.java, S3StorageService.java |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Уровень 4: стриминг, лимиты RAM, эксперимент ≥10 загрузок | tests/memory_experiment.py | 12/12 загрузок успешно, пик RAM не растёт | tests/memory_experiment.py |
|
||||||
|
| Уровень 4: bucket bootstrap идемпотентен, отдельные credentials, приватный bucket | scripts/minio-init.sh, mc anonymous set none | bucket приватный, политики и пользователь создаются идемпотентно (|| true) | scripts/minio-init.sh, docker-compose.yml, nginx.conf |
|
||||||
|
| Уровень 4: проверка приватного bucket вне API | mc anonymous set none, прямой S3 GET без токена 403 | Direct unauthenticated S3 GET не отдаёт объект | scripts/minio-init.sh |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| 12 одновременных загрузок вложений | Все успешно, RAM не растёт неограниченно | 12/12 успешно, пик RAM ≈ baseline (стриминг во временный файл) | — |
|
||||||
|
| Сбой записи S3/БД между шагами upload | Реконсилер удаляет объект после grace period | Объект остаётся до истечения grace 1 час, затем удаляется реконсилером | — |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
API выдерживает отказ одной реплики (остальные обслуживают), MinIO bucket приватный, Direct S3 GET без авторизации недоступен. Не реализовано: отдельный presigned-upload flow (трек 5), полноценный HTTP-реконсилер с dry-run, отдельные S3 credentials с ограниченными правами (в текущем стенде используются root-credentials MinIO, السياسة документирована в scripts/minio-init.sh). Образовательное упрощение: S3-credentials задаются через .env, MinIO консоль (9001) не экспонируется наружу.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import http from 'k6/http';
|
||||||
|
import { check } from 'k6';
|
||||||
|
|
||||||
|
export const options = {
|
||||||
|
scenarios: {
|
||||||
|
steady: {
|
||||||
|
executor: 'constant-vus',
|
||||||
|
vus: 20,
|
||||||
|
duration: '120s',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const BASE = __ENV.BASE_URL || 'http://localhost:8080';
|
||||||
|
const TOKEN = __ENV.TOKEN;
|
||||||
|
const CHAT = __ENV.CHAT_ID;
|
||||||
|
|
||||||
|
export default function () {
|
||||||
|
const res = http.get(`${BASE}/health/live`);
|
||||||
|
check(res, { 'live 200': (r) => r.status === 200 });
|
||||||
|
http.get(`${BASE}/api/v1/users/me`, { headers: { Authorization: `Bearer ${TOKEN}` } });
|
||||||
|
}
|
||||||
Executable
+21
@@ -0,0 +1,21 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
# scripts/ -> корень репо -> Lido
|
||||||
|
ROOT="$(CDPATH= cd -- "$(dirname "$0")/../Lido" && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
if [ ! -f docker-compose.yml ] && [ ! -f compose.yaml ] && [ ! -f compose.yml ]; then
|
||||||
|
echo "compose file not found in $ROOT" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
CID="$(docker compose ps -q api | head -n 1)"
|
||||||
|
|
||||||
|
if [ -z "$CID" ]; then
|
||||||
|
echo "no api replica found" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
docker stop "$CID"
|
||||||
|
exit 0
|
||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Wait for Minio to accept connections (actual health check, not just alias)
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if curl -sf http://minio:9000/minio/health/live >/dev/null 2>&1; then
|
||||||
|
echo "Minio is ready"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
echo "Waiting for Minio... ($i/60)"
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
mc alias set local http://minio:9000 "${MINIO_ROOT_USER}" "${MINIO_ROOT_PASSWORD}"
|
||||||
|
mc mb --ignore-existing "local/${S3_BUCKET:-messenger-attachments}"
|
||||||
|
mc anonymous set none "local/${S3_BUCKET:-messenger-attachments}"
|
||||||
|
|
||||||
|
mc admin user add local "${S3_ACCESS_KEY}" "${S3_SECRET_KEY}" || true
|
||||||
|
|
||||||
|
cat > /tmp/messenger-policy.json <<POLICYEOF
|
||||||
|
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject","s3:DeleteObject","s3:ListBucket"],"Resource":["arn:aws:s3:::${S3_BUCKET:-messenger-attachments}","arn:aws:s3:::${S3_BUCKET:-messenger-attachments}/*"]}]}
|
||||||
|
POLICYEOF
|
||||||
|
|
||||||
|
mc admin policy create local messenger-upload /tmp/messenger-policy.json || true
|
||||||
|
mc admin policy attach local messenger-upload --user "${S3_ACCESS_KEY}" || true
|
||||||
|
|
||||||
|
echo "bucket-ready"
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user