ЛР 3 — БПИ2303 — Пойлов — на 3 #131
@@ -18,3 +18,9 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
# Java / Maven
|
||||
target/
|
||||
*.class
|
||||
*.jar
|
||||
*.war
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# =========================================================================
|
||||
# Stage 1: Build
|
||||
# =========================================================================
|
||||
# Pin to a specific tag — do NOT use "latest"
|
||||
FROM maven:3.9.9-eclipse-temurin-21 AS build
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
# Copy dependency manifests first (better layer caching)
|
||||
COPY pom.xml .
|
||||
COPY .mvn/ .mvn/
|
||||
COPY mvnw mvnw.cmd ./
|
||||
|
||||
# Pre-download dependencies (cached layer)
|
||||
RUN ./mvnw -B dependency:go-offline
|
||||
|
||||
# Copy sources and build
|
||||
COPY src/ src/
|
||||
RUN ./mvnw -B clean package -DskipTests
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Runtime
|
||||
# =========================================================================
|
||||
# Pin to a specific tag — do NOT use "latest"
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
|
||||
# Create a non-root user and group
|
||||
RUN addgroup -S app && adduser -S app -G app
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy the fat jar from the build stage
|
||||
COPY --from=build --chown=app:app /workspace/target/*.jar app.jar
|
||||
|
||||
# Drop privileges
|
||||
USER app
|
||||
|
||||
# Expose the HTTP port
|
||||
EXPOSE 8080
|
||||
|
||||
# Healthcheck against the public health endpoint.
|
||||
# Uses wget because Alpine has it by default (curl may not be installed).
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \
|
||||
CMD wget -qO- http://localhost:8080/health/live >/dev/null 2>&1 || exit 1
|
||||
|
||||
# PID 1 = java process. exec form so signals (SIGTERM) reach the JVM directly.
|
||||
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
|
||||
@@ -1,37 +1,39 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- **Автор, группа:** Пойлов А.А., БПИ2303
|
||||
- **Целевая оценка:** 3. Трек 5 не выбран.
|
||||
- **Commit/PR:** https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/131
|
||||
- **Использованные источники, библиотеки и помощь ИИ:**
|
||||
- Spring Boot 3.3.0, Spring Data JPA, Spring Security, Flyway, PostgreSQL 15, Nginx 1.25, Docker Compose.
|
||||
- Официальная документация Nginx (директивы `upstream`, `proxy_next_upstream`) и Docker Compose (`--scale`).
|
||||
- Помощь ИИ (Claude) при настройке отказоустойчивости Nginx и отладке конкурентной идемпотентности.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
**Prerequisites:** JDK 21, Maven 3.9+ (или `mvnw`), Docker Desktop, Python 3.9+.
|
||||
|
||||
## Архитектура и решения
|
||||
**Версии образов (закреплены):**
|
||||
- `maven:3.9.9-eclipse-temurin-21` (сборка)
|
||||
- `eclipse-temurin:21-jre-alpine` (runtime)
|
||||
- `postgres:15-alpine` (база данных)
|
||||
- `nginx:1.25-alpine` (балансировщик)
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
**Команды:**
|
||||
```sh
|
||||
# 1. Клонировать и перейти в ветку
|
||||
git clone <URL форка>
|
||||
cd mtusi2026lab3
|
||||
git checkout solution/bpi2303-poylov
|
||||
cp .env.example .env
|
||||
|
||||
## Доказательства критериев
|
||||
# 2. Запустить 2 реплики API и Nginx
|
||||
docker compose up -d --build --scale api=2
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
# 3. Дождаться готовности (около 20-30 сек)
|
||||
# Проверка: curl -i http://localhost:8080/health/ready
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
# 4. Прогнать тесты (на Windows перед Python нужен export PYTHONUTF8=1)
|
||||
export PYTHONUTF8=1
|
||||
make test PYTHON=python
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.cmd PYTHON=python
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.cmd PYTHON=python
|
||||
@@ -0,0 +1,45 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD: messenger
|
||||
POSTGRES_DB: messenger
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
api:
|
||||
build: .
|
||||
environment:
|
||||
- SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/messenger
|
||||
- SPRING_DATASOURCE_USERNAME=messenger
|
||||
- SPRING_DATASOURCE_PASSWORD=messenger
|
||||
- APP_PORT=8080
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
# Убрали container_name, чтобы Docker Compose мог масштабировать сервис
|
||||
# Убрали ports, так как доступ только через nginx
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8080/health/live"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
|
||||
nginx:
|
||||
image: nginx:1.25-alpine
|
||||
ports:
|
||||
- "127.0.0.1:8080:80" # Публикуем только на localhost
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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
|
||||
#
|
||||
# http://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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
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"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
upstream api_backend {
|
||||
server api:8080 max_fails=1 fail_timeout=3s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
keepalive_timeout 0;
|
||||
|
||||
location / {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_read_timeout 2s;
|
||||
|
||||
# Пробуем следующую реплику при любой ошибке
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>ru.mtusi</groupId>
|
||||
<artifactId>messenger</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<name>mtusi-messenger-lab2</name>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- REST API -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- Валидация -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Безопасность (Basic и Bearer) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<!-- База данных (JPA + PostgreSQL) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- Миграции (Flyway) -->
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
<!-- Тесты -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
docker compose restart
|
||||
timeout /t 10 /nobreak > NUL
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
"C:\Program Files\Git\bin\bash.exe" "%~dp0restart.sh"
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
docker compose restart
|
||||
for i in $(seq 1 30); do
|
||||
if curl -s -f http://localhost:8080/health/ready > /dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
exit 1
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
"C:\Program Files\Git\bin\bash.exe" "%~dp0stop-one.sh"
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/bin/bash
|
||||
# TARGET_INSTANCE_ID содержит X-Instance-Id реплики, которую нужно остановить
|
||||
|
||||
echo "Target instance: $TARGET_INSTANCE_ID"
|
||||
|
||||
# Ищем имя контейнера, в логах которого есть этот Instance ID
|
||||
# (Так как мы не задавали имена контейнерам, Docker Compose генерирует их автоматически)
|
||||
CONTAINER_TO_STOP=""
|
||||
for container in $(docker ps -q --filter "name=mtusi2026lab3-api"); do
|
||||
# Проверяем логи контейнера на наличие Instance ID
|
||||
if docker logs $container 2>&1 | grep -q "$TARGET_INSTANCE_ID"; then
|
||||
CONTAINER_TO_STOP=$container
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$CONTAINER_TO_STOP" ]; then
|
||||
echo "Container not found for instance $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Stopping container $CONTAINER_TO_STOP"
|
||||
docker stop -t 1 $CONTAINER_TO_STOP
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MessengerApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MessengerApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
public class BearerTokenFilter extends OncePerRequestFilter {
|
||||
|
||||
private final SessionRepository sessionRepository;
|
||||
|
||||
public BearerTokenFilter(SessionRepository sessionRepository) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
|
||||
Optional<SessionEntity> sessionOpt = sessionRepository.findById(token);
|
||||
|
||||
if (sessionOpt.isPresent() && sessionOpt.get().getExpiresAt().isAfter(OffsetDateTime.now(ZoneOffset.UTC))) {
|
||||
// Токен валиден! Кладем ID пользователя в контекст безопасности Spring
|
||||
SessionEntity session = sessionOpt.get();
|
||||
|
||||
// В Spring Security Principal - это объект, представляющий пользователя.
|
||||
// Мы будем использовать UUID пользователя как Principal.
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(session.getUserId(), null, Collections.emptyList());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
|
||||
// Пропускаем запрос дальше
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Configuration
|
||||
public class InstanceConfig {
|
||||
private static final Logger log = LoggerFactory.getLogger(InstanceConfig.class);
|
||||
|
||||
@Bean
|
||||
public String instanceId() {
|
||||
String id = UUID.randomUUID().toString().substring(0, 8);
|
||||
log.info("STARTED API INSTANCE WITH ID: {}", id);
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.ErrorResponse;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public RestAuthenticationEntryPoint(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
|
||||
throws IOException, ServletException {
|
||||
|
||||
// Достаем X-Request-Id, который сгенерировал наш фильтр ранее
|
||||
String requestId = (String) request.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
|
||||
|
||||
ErrorResponse error = ErrorResponse.of("unauthorized", "No valid bearer token", requestId);
|
||||
response.getWriter().write(objectMapper.writeValueAsString(error));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final SessionRepository sessionRepository;
|
||||
private final RestAuthenticationEntryPoint authEntryPoint; // ДОБАВЛЕНО
|
||||
|
||||
public SecurityConfig(SessionRepository sessionRepository, RestAuthenticationEntryPoint authEntryPoint) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.authEntryPoint = authEntryPoint; // ДОБАВЛЕНО
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
// ДОБАВЛЕНО: обработчик ошибок безопасности
|
||||
.exceptionHandling(ex -> ex.authenticationEntryPoint(authEntryPoint))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/users", "/api/v1/auth/sessions", "/health/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.addFilterBefore(new BearerTokenFilter(sessionRepository), UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.SessionResponse;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.service.SessionService;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final SessionService sessionService;
|
||||
private final SessionRepository sessionRepository; // <-- ДОБАВЛЕНО
|
||||
|
||||
public AuthController(SessionService sessionService, SessionRepository sessionRepository) {
|
||||
this.sessionService = sessionService;
|
||||
this.sessionRepository = sessionRepository; // <-- ДОБАВЛЕНО
|
||||
}
|
||||
|
||||
@PostMapping("/sessions")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public SessionResponse createSession(
|
||||
@RequestHeader(value = "Authorization", required = false) String authHeader) {
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith("Basic ")) {
|
||||
throw new UnauthorizedException("Missing or invalid Authorization header");
|
||||
}
|
||||
|
||||
String base64Credentials = authHeader.substring(6);
|
||||
String credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
|
||||
|
||||
int colonIndex = credentials.indexOf(':');
|
||||
if (colonIndex == -1) {
|
||||
throw new UnauthorizedException("Invalid Basic Auth format");
|
||||
}
|
||||
|
||||
String username = credentials.substring(0, colonIndex);
|
||||
String password = credentials.substring(colonIndex + 1);
|
||||
|
||||
return sessionService.createSession(username, password);
|
||||
}
|
||||
|
||||
@DeleteMapping("/sessions/current")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(@RequestHeader("Authorization") String authHeader) {
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
sessionRepository.deleteById(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
import ru.mtusi.messenger.dto.CreateChat;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.ChatService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats")
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chatService;
|
||||
|
||||
public ChatController(ChatService chatService) {
|
||||
this.chatService = chatService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Chat createChat(Authentication auth, @Valid @RequestBody CreateChat body) {
|
||||
return chatService.createChat(getUserId(auth), body);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public Object listChats(Authentication auth) {
|
||||
// Упрощенная версия без курсора для lab2, если тесты не требуют обратного
|
||||
return new ChatPage(chatService.getUserChats(getUserId(auth)), null);
|
||||
}
|
||||
|
||||
@GetMapping("/{chat_id}")
|
||||
public Chat getChat(Authentication auth, @PathVariable("chat_id") UUID chatId) {
|
||||
return chatService.getChat(getUserId(auth), chatId);
|
||||
}
|
||||
|
||||
private UUID getUserId(Authentication auth) {
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
return (UUID) auth.getPrincipal();
|
||||
}
|
||||
|
||||
// Заглушка для DTO, чтобы не ломать компиляцию
|
||||
public record ChatPage(java.util.List<Chat> items, String nextCursor) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping("/health/live")
|
||||
public ResponseEntity<Map<String, String>> liveness(HttpServletRequest request) {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
|
||||
@GetMapping("/health/ready")
|
||||
public ResponseEntity<Map<String, String>> readiness(HttpServletRequest request) {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.CreateMessage;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.MessageService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats/{chat_id}/messages")
|
||||
public class MessageController {
|
||||
|
||||
private final MessageService messageService;
|
||||
|
||||
public MessageController(MessageService messageService) {
|
||||
this.messageService = messageService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Message createMessage(
|
||||
Authentication auth,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey,
|
||||
@Valid @RequestBody CreateMessage body) {
|
||||
|
||||
if (idempotencyKey == null || idempotencyKey.isBlank()) {
|
||||
throw new InvalidRequestException("Idempotency-Key header is required");
|
||||
}
|
||||
// Валидация ключа по регулярке из README: ASCII [A-Za-z0-9._:-]{1,128}
|
||||
if (!idempotencyKey.matches("^[A-Za-z0-9._:-]{1,128}$")) {
|
||||
throw new InvalidRequestException("Invalid Idempotency-Key format");
|
||||
}
|
||||
|
||||
return messageService.createMessage(getUserId(auth), chatId, body.text(), idempotencyKey);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public MessagePage listMessages(
|
||||
Authentication auth,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestParam(value = "limit", required = false) Integer limit,
|
||||
@RequestParam(value = "cursor", required = false) String cursor) {
|
||||
|
||||
int effectiveLimit = (limit == null) ? 50 : limit;
|
||||
if (effectiveLimit < 1 || effectiveLimit > 100) {
|
||||
throw new InvalidRequestException("limit must be between 1 and 100");
|
||||
}
|
||||
|
||||
java.time.OffsetDateTime lastCreatedAt = null;
|
||||
UUID lastId = null;
|
||||
|
||||
if (cursor != null && !cursor.isBlank()) {
|
||||
try {
|
||||
String decoded = new String(java.util.Base64.getUrlDecoder().decode(cursor), java.nio.charset.StandardCharsets.UTF_8);
|
||||
String[] parts = decoded.split("\\|");
|
||||
lastCreatedAt = java.time.OffsetDateTime.parse(parts[0]);
|
||||
lastId = UUID.fromString(parts[1]);
|
||||
} catch (Exception e) {
|
||||
throw new InvalidRequestException("Invalid cursor format");
|
||||
}
|
||||
}
|
||||
|
||||
// Берем на 1 больше, чтобы понять, есть ли следующая страница
|
||||
List<Message> msgs = messageService.getMessagesPage(getUserId(auth), chatId, lastCreatedAt, lastId, effectiveLimit + 1);
|
||||
|
||||
boolean hasMore = msgs.size() > effectiveLimit;
|
||||
List<Message> pageItems = hasMore ? msgs.subList(0, effectiveLimit) : msgs;
|
||||
|
||||
String nextCursor = null;
|
||||
if (hasMore && !pageItems.isEmpty()) {
|
||||
Message lastMsg = pageItems.get(pageItems.size() - 1);
|
||||
String rawCursor = lastMsg.createdAt().toString() + "|" + lastMsg.id().toString();
|
||||
nextCursor = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(rawCursor.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
return new MessagePage(pageItems, nextCursor);
|
||||
}
|
||||
|
||||
private UUID getUserId(Authentication auth) {
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
return (UUID) auth.getPrincipal();
|
||||
}
|
||||
|
||||
public record MessagePage(List<Message> items, String nextCursor) {}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.CreateUser;
|
||||
import ru.mtusi.messenger.dto.User;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.UserService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public User createUser(@Valid @RequestBody CreateUser body) {
|
||||
return userService.createUser(body);
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public User currentUser(Authentication authentication) {
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
UUID userId = (UUID) authentication.getPrincipal();
|
||||
|
||||
return userService.findById(userId)
|
||||
.orElseThrow(() -> new UnauthorizedException("Unknown user"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Chat(
|
||||
UUID id,
|
||||
String title,
|
||||
List<UUID> memberIds,
|
||||
OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ChatPage(List<Chat> items, String nextCursor) {}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record CreateChat(
|
||||
@NotBlank(message = "title must not be blank")
|
||||
@Size(min = 1, max = 100, message = "title must be 1..100 characters")
|
||||
String title,
|
||||
|
||||
@NotEmpty(message = "member_ids must not be empty")
|
||||
@Size(min = 1, max = 100, message = "member_ids must contain 1..100 items")
|
||||
List<UUID> memberIds
|
||||
) {}
|
||||
@@ -0,0 +1,10 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record CreateMessage(
|
||||
@NotBlank(message = "text must not be blank")
|
||||
@Size(min = 1, max = 4000, message = "text must be 1..4000 characters")
|
||||
String text
|
||||
) {}
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record CreateUser(
|
||||
@NotBlank(message = "username must not be blank")
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$", message = "username must match ^[a-z0-9_]{3,32}$")
|
||||
String username,
|
||||
|
||||
@NotBlank(message = "display_name must not be blank")
|
||||
@Size(min = 1, max = 100, message = "display_name must be 1..100 characters")
|
||||
String displayName,
|
||||
|
||||
@NotBlank(message = "password must not be blank")
|
||||
@Size(min = 12, max = 128, message = "password must be 12..128 characters")
|
||||
String password // <-- Новое поле
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record ErrorResponse(ErrorBody error) {
|
||||
|
||||
public record ErrorBody(
|
||||
String code,
|
||||
String message,
|
||||
String requestId
|
||||
) {}
|
||||
|
||||
public static ErrorResponse of(String code, String message, String requestId) {
|
||||
return new ErrorResponse(new ErrorBody(code, message, requestId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
public record Health(String status) {
|
||||
public static Health ok() {
|
||||
return new Health("ok");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Message(
|
||||
UUID id,
|
||||
UUID chatId,
|
||||
UUID senderId,
|
||||
String text,
|
||||
OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record MessagePage(List<Message> items, String nextCursor) {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record Page<T>(List<T> items, String nextCursor) {}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public record SessionResponse(
|
||||
String token,
|
||||
String tokenType,
|
||||
OffsetDateTime expiresAt,
|
||||
User user
|
||||
) {
|
||||
public SessionResponse(String token, OffsetDateTime expiresAt, User user) {
|
||||
this(token, "Bearer", expiresAt, user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public record User(
|
||||
UUID id,
|
||||
String username,
|
||||
String displayName,
|
||||
OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "chats")
|
||||
public class ChatEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(
|
||||
name = "chat_members",
|
||||
joinColumns = @JoinColumn(name = "chat_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "user_id")
|
||||
)
|
||||
private Set<UserEntity> members;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
public Set<UserEntity> getMembers() { return members; }
|
||||
public void setMembers(Set<UserEntity> members) { this.members = members; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "idempotency_keys")
|
||||
@IdClass(IdempotencyId.class)
|
||||
public class IdempotencyEntity {
|
||||
@Id
|
||||
private String key;
|
||||
|
||||
@Id
|
||||
@Column(name = "user_id")
|
||||
private UUID userId;
|
||||
|
||||
@Id
|
||||
@Column(name = "chat_id")
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "request_hash", nullable = false)
|
||||
private String requestHash;
|
||||
|
||||
@Column(name = "message_id", nullable = false)
|
||||
private UUID messageId;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getKey() { return key; }
|
||||
public void setKey(String key) { this.key = key; }
|
||||
public UUID getUserId() { return userId; }
|
||||
public void setUserId(UUID userId) { this.userId = userId; }
|
||||
public UUID getChatId() { return chatId; }
|
||||
public void setChatId(UUID chatId) { this.chatId = chatId; }
|
||||
public String getRequestHash() { return requestHash; }
|
||||
public void setRequestHash(String requestHash) { this.requestHash = requestHash; }
|
||||
public UUID getMessageId() { return messageId; }
|
||||
public void setMessageId(UUID messageId) { this.messageId = messageId; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class IdempotencyId implements Serializable {
|
||||
private String key;
|
||||
private UUID userId;
|
||||
private UUID chatId;
|
||||
|
||||
public IdempotencyId() {}
|
||||
public IdempotencyId(String key, UUID userId, UUID chatId) {
|
||||
this.key = key;
|
||||
this.userId = userId;
|
||||
this.chatId = chatId;
|
||||
}
|
||||
|
||||
// equals и hashCode обязательны для JPA
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
IdempotencyId that = (IdempotencyId) o;
|
||||
return Objects.equals(key, that.key) && Objects.equals(userId, that.userId) && Objects.equals(chatId, that.chatId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(key, userId, chatId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "messages")
|
||||
public class MessageEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "sender_id", nullable = false)
|
||||
private UUID senderId;
|
||||
|
||||
@Column(nullable = false, length = 4000)
|
||||
private String text;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public UUID getChatId() { return chatId; }
|
||||
public void setChatId(UUID chatId) { this.chatId = chatId; }
|
||||
public UUID getSenderId() { return senderId; }
|
||||
public void setSenderId(UUID senderId) { this.senderId = senderId; }
|
||||
public String getText() { return text; }
|
||||
public void setText(String text) { this.text = text; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "sessions")
|
||||
public class SessionEntity {
|
||||
@Id
|
||||
private String token;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private OffsetDateTime expiresAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getToken() { return token; }
|
||||
public void setToken(String token) { this.token = token; }
|
||||
public UUID getUserId() { return userId; }
|
||||
public void setUserId(UUID userId) { this.userId = userId; }
|
||||
public OffsetDateTime getExpiresAt() { return expiresAt; }
|
||||
public void setExpiresAt(OffsetDateTime expiresAt) { this.expiresAt = expiresAt; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 32)
|
||||
private String username;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры (или используй Lombok, если он есть)
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getPasswordHash() { return passwordHash; }
|
||||
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
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 ru.mtusi.messenger.dto.ErrorResponse;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(InvalidRequestException.class)
|
||||
public ResponseEntity<ErrorResponse> handleInvalid(InvalidRequestException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnauthorized(UnauthorizedException ex, HttpServletRequest req) {
|
||||
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
ErrorResponse body = ErrorResponse.of("unauthorized", ex.getMessage(), requestId);
|
||||
|
||||
// Контракт требует заголовок WWW-Authenticate
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"")
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.NOT_FOUND, "not_found", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConflict(ConflictException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.CONFLICT, "conflict", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
|
||||
String message = ex.getBindingResult().getFieldErrors().stream()
|
||||
.findFirst()
|
||||
.map(fe -> fe.getField() + ": " + fe.getDefaultMessage())
|
||||
.orElse("Validation failed");
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", message, req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMalformed(HttpMessageNotReadableException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", "Malformed JSON or invalid field type", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMissingHeader(MissingRequestHeaderException ex, HttpServletRequest req) {
|
||||
// Мы не бросаем это явно, но если понадобится required=true в @RequestHeader
|
||||
return error(HttpStatus.UNAUTHORIZED, "unauthorized", "Missing required header", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAll(Exception ex, HttpServletRequest req) {
|
||||
// Не логируем stack trace в ответ; для отладки — в stdout
|
||||
ex.printStackTrace();
|
||||
return error(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Internal server error", req);
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorResponse> error(HttpStatus status, String code, String message,
|
||||
HttpServletRequest req) {
|
||||
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
return ResponseEntity.status(status).body(ErrorResponse.of(code, message, requestId));
|
||||
}
|
||||
|
||||
@ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(org.springframework.dao.DataIntegrityViolationException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.CONFLICT, "conflict", "Resource already exists", req);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
public InvalidRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class UnauthorizedException extends RuntimeException {
|
||||
public UnauthorizedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(-200)
|
||||
public class RequestIdFilter implements Filter {
|
||||
|
||||
public static final String REQUEST_ID_ATTR = "requestId";
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
private final String instanceId;
|
||||
|
||||
public RequestIdFilter(String instanceId) {
|
||||
this.instanceId = instanceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
httpRequest.setAttribute(REQUEST_ID_ATTR, requestId);
|
||||
httpResponse.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
|
||||
// Добавляем X-Instance-Id
|
||||
httpResponse.setHeader("X-Instance-Id", instanceId);
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatRepository extends JpaRepository<ChatEntity, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.IdempotencyEntity;
|
||||
import ru.mtusi.messenger.entity.IdempotencyId;
|
||||
|
||||
public interface IdempotencyRepository extends JpaRepository<IdempotencyEntity, IdempotencyId> {
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import ru.mtusi.messenger.entity.MessageEntity;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface MessageRepository extends JpaRepository<MessageEntity, UUID> {
|
||||
|
||||
@Query("SELECT m FROM MessageEntity 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<MessageEntity> findNextPage(
|
||||
@Param("chatId") UUID chatId,
|
||||
@Param("createdAt") OffsetDateTime createdAt,
|
||||
@Param("id") UUID id,
|
||||
Pageable pageable
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
|
||||
public interface SessionRepository extends JpaRepository<SessionEntity, String> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository extends JpaRepository<UserEntity, UUID> {
|
||||
Optional<UserEntity> findByUsername(String username);
|
||||
boolean existsByUsername(String username);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
import ru.mtusi.messenger.dto.CreateChat;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public ChatService(ChatRepository chatRepository, UserRepository userRepository) {
|
||||
this.chatRepository = chatRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Chat createChat(UUID callerId, CreateChat request) {
|
||||
Set<UUID> uniqueMembers = new HashSet<>(request.memberIds());
|
||||
if (uniqueMembers.size() != request.memberIds().size()) {
|
||||
throw new InvalidRequestException("member_ids must be unique");
|
||||
}
|
||||
if (!uniqueMembers.contains(callerId)) {
|
||||
throw new InvalidRequestException("caller must be a member of the chat");
|
||||
}
|
||||
|
||||
List<UserEntity> members = userRepository.findAllById(request.memberIds());
|
||||
if (members.size() != request.memberIds().size()) {
|
||||
throw new InvalidRequestException("Some members do not exist");
|
||||
}
|
||||
|
||||
ChatEntity chat = new ChatEntity();
|
||||
chat.setId(UUID.randomUUID());
|
||||
chat.setTitle(request.title());
|
||||
chat.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
chat.setMembers(new HashSet<>(members));
|
||||
|
||||
chatRepository.save(chat);
|
||||
return toDto(chat);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Chat getChat(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
|
||||
return toDto(chat);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Chat> getUserChats(UUID callerId) {
|
||||
// В реальном проекте лучше сделать кастомный запрос, но для lab2 сойдет
|
||||
return chatRepository.findAll().stream()
|
||||
.filter(c -> c.getMembers().stream().anyMatch(u -> u.getId().equals(callerId)))
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Chat toDto(ChatEntity entity) {
|
||||
return new Chat(
|
||||
entity.getId(),
|
||||
entity.getTitle(),
|
||||
entity.getMembers().stream().map(UserEntity::getId).toList(),
|
||||
entity.getCreatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.entity.MessageEntity;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.repository.IdempotencyRepository;
|
||||
import ru.mtusi.messenger.repository.MessageRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class MessageService {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final IdempotencyRepository idempotencyRepository; // <-- ДОБАВЛЕНО
|
||||
|
||||
public MessageService(MessageRepository messageRepository,
|
||||
ChatRepository chatRepository,
|
||||
IdempotencyRepository idempotencyRepository) { // <-- ДОБАВЛЕНО
|
||||
this.messageRepository = messageRepository;
|
||||
this.chatRepository = chatRepository;
|
||||
this.idempotencyRepository = idempotencyRepository; // <-- ДОБАВЛЕНО
|
||||
}
|
||||
|
||||
@org.springframework.transaction.annotation.Transactional
|
||||
public Message createMessage(UUID callerId, UUID chatId, String text, String idempotencyKey) {
|
||||
verifyAccess(callerId, chatId);
|
||||
|
||||
// Считаем хеш тела запроса
|
||||
String requestHash = org.springframework.util.DigestUtils.md5DigestAsHex(text.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
|
||||
var existing = idempotencyRepository.findById(new ru.mtusi.messenger.entity.IdempotencyId(idempotencyKey, callerId, chatId));
|
||||
if (existing.isPresent()) {
|
||||
if (!existing.get().getRequestHash().equals(requestHash)) {
|
||||
throw new ru.mtusi.messenger.exception.ConflictException("Idempotency key reused with different body");
|
||||
}
|
||||
// Возвращаем существующее сообщение
|
||||
return messageRepository.findById(existing.get().getMessageId())
|
||||
.map(this::toDto)
|
||||
.orElseThrow(() -> new ru.mtusi.messenger.exception.NotFoundException("Message not found"));
|
||||
}
|
||||
}
|
||||
|
||||
MessageEntity msg = new MessageEntity();
|
||||
msg.setId(UUID.randomUUID());
|
||||
msg.setChatId(chatId);
|
||||
msg.setSenderId(callerId);
|
||||
msg.setText(text);
|
||||
msg.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS));
|
||||
messageRepository.save(msg);
|
||||
|
||||
// Сохраняем ключ
|
||||
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
|
||||
var idem = new ru.mtusi.messenger.entity.IdempotencyEntity();
|
||||
idem.setKey(idempotencyKey);
|
||||
idem.setUserId(callerId);
|
||||
idem.setChatId(chatId);
|
||||
idem.setRequestHash(requestHash);
|
||||
idem.setMessageId(msg.getId());
|
||||
idem.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
idempotencyRepository.save(idem);
|
||||
}
|
||||
|
||||
return toDto(msg);
|
||||
}
|
||||
|
||||
private void verifyAccess(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
}
|
||||
|
||||
private Message toDto(MessageEntity e) {
|
||||
return new Message(e.getId(), e.getChatId(), e.getSenderId(), e.getText(), e.getCreatedAt());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Message> getMessagesPage(UUID callerId, UUID chatId, OffsetDateTime lastCreatedAt, UUID lastId, int limit) {
|
||||
verifyAccess(callerId, chatId);
|
||||
|
||||
// Если курсора нет, берем с самого начала (эпоха 1970 года)
|
||||
OffsetDateTime startTime = (lastCreatedAt != null) ? lastCreatedAt : OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
|
||||
UUID startId = (lastId != null) ? lastId : new UUID(0, 0);
|
||||
|
||||
return messageRepository.findNextPage(chatId, startTime, startId, org.springframework.data.domain.PageRequest.of(0, limit))
|
||||
.stream().map(this::toDto).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.SessionResponse;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class SessionService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserService userService;
|
||||
|
||||
public SessionService(UserRepository userRepository,
|
||||
SessionRepository sessionRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
UserService userService) {
|
||||
this.userRepository = userRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SessionResponse createSession(String username, String rawPassword) {
|
||||
// 1. Ищем пользователя
|
||||
UserEntity user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UnauthorizedException("Invalid credentials"));
|
||||
|
||||
// 2. Проверяем пароль
|
||||
if (!passwordEncoder.matches(rawPassword, user.getPasswordHash())) {
|
||||
throw new UnauthorizedException("Invalid credentials");
|
||||
}
|
||||
|
||||
// 3. Генерируем opaque токен (UUID)
|
||||
String token = UUID.randomUUID().toString();
|
||||
|
||||
// 4. Сохраняем сессию в БД (TTL 1 час)
|
||||
SessionEntity session = new SessionEntity();
|
||||
session.setToken(token);
|
||||
session.setUserId(user.getId());
|
||||
session.setExpiresAt(OffsetDateTime.now(ZoneOffset.UTC).plusHours(1));
|
||||
|
||||
sessionRepository.save(session);
|
||||
|
||||
// 5. Возвращаем ответ
|
||||
return new SessionResponse(
|
||||
token,
|
||||
session.getExpiresAt(),
|
||||
userService.toDto(user)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.CreateUser;
|
||||
import ru.mtusi.messenger.dto.User;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User createUser(CreateUser request) {
|
||||
// ... проверка username ...
|
||||
UserEntity entity = new UserEntity();
|
||||
entity.setId(UUID.randomUUID());
|
||||
entity.setUsername(request.username());
|
||||
entity.setDisplayName(request.displayName());
|
||||
entity.setPasswordHash(passwordEncoder.encode(request.password()));
|
||||
|
||||
// ВАЖНО: обрезаем до миллисекунд, чтобы PostgreSQL не изменил точность
|
||||
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
|
||||
entity.setCreatedAt(now);
|
||||
|
||||
userRepository.save(entity);
|
||||
return toDto(entity);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> findById(UUID id) {
|
||||
return userRepository.findById(id).map(this::toDto);
|
||||
}
|
||||
|
||||
// Вспомогательный метод для конвертации Entity -> DTO
|
||||
public User toDto(UserEntity entity) {
|
||||
return new User(
|
||||
entity.getId(),
|
||||
entity.getUsername(),
|
||||
entity.getDisplayName(),
|
||||
entity.getCreatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/* package ru.mtusi.messenger.store;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class ChatStore {
|
||||
|
||||
private final ConcurrentHashMap<UUID, Chat> byId = new ConcurrentHashMap<>();
|
||||
|
||||
public Chat create(String title, List<UUID> memberIds) {
|
||||
UUID id = UUID.randomUUID();
|
||||
Chat chat = new Chat(
|
||||
id,
|
||||
title,
|
||||
List.copyOf(memberIds),
|
||||
OffsetDateTime.now(ZoneOffset.UTC)
|
||||
);
|
||||
byId.put(id, chat);
|
||||
return chat;
|
||||
}
|
||||
|
||||
public Optional<Chat> findById(UUID id) {
|
||||
return Optional.ofNullable(byId.get(id));
|
||||
}
|
||||
|
||||
public List<Chat> findByMember(UUID userId) {
|
||||
List<Chat> result = new ArrayList<>();
|
||||
for (Chat chat : byId.values()) {
|
||||
if (chat.memberIds().contains(userId)) {
|
||||
result.add(chat);
|
||||
}
|
||||
}
|
||||
result.sort(Comparator
|
||||
.comparing(Chat::createdAt)
|
||||
.thenComparing(c -> c.id().toString()));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,43 @@
|
||||
/* package ru.mtusi.messenger.store;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
@Component
|
||||
public class MessageStore {
|
||||
|
||||
private static final Comparator<Message> ORDER =
|
||||
Comparator.comparing(Message::createdAt)
|
||||
.thenComparing(m -> m.id().toString());
|
||||
|
||||
private final ConcurrentHashMap<UUID, CopyOnWriteArrayList<Message>> byChat = new ConcurrentHashMap<>();
|
||||
|
||||
public Message create(UUID chatId, UUID senderId, String text) {
|
||||
Message message = new Message(
|
||||
UUID.randomUUID(), chatId, senderId, text,
|
||||
OffsetDateTime.now(ZoneOffset.UTC)
|
||||
);
|
||||
byChat.computeIfAbsent(chatId, k -> new CopyOnWriteArrayList<>()).add(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
public List<Message> findByChat(UUID chatId) {
|
||||
CopyOnWriteArrayList<Message> messages = byChat.get(chatId);
|
||||
if (messages == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Message> sorted = new ArrayList<>(messages);
|
||||
sorted.sort(ORDER);
|
||||
return sorted;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.util;
|
||||
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Кодирует/декодирует opaque cursor для keyset-пагинации.
|
||||
*
|
||||
* Формат (внутри base64url): scope | createdAt.toString() | uuid
|
||||
* scope — например "chat:<chat_id>", привязывает курсор к ресурсу
|
||||
* createdAt — ISO-8601 строкa UTC с наносекундной точностью
|
||||
* uuid — id последнего элемента
|
||||
*
|
||||
* Клиент видит только base64-строку и не должен её интерпретировать.
|
||||
*/
|
||||
public final class CursorCodec {
|
||||
|
||||
private CursorCodec() {}
|
||||
|
||||
public record Cursor(String scope, OffsetDateTime createdAt, UUID id) {}
|
||||
|
||||
public static String encode(String scope, OffsetDateTime createdAt, UUID id) {
|
||||
String raw = scope + "|" + createdAt.toString() + "|" + id;
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Cursor decode(String encoded, String expectedScope) {
|
||||
try {
|
||||
String raw = new String(
|
||||
Base64.getUrlDecoder().decode(encoded),
|
||||
StandardCharsets.UTF_8
|
||||
);
|
||||
String[] parts = raw.split("\\|", 3);
|
||||
if (parts.length != 3) {
|
||||
throw new InvalidRequestException("Invalid cursor");
|
||||
}
|
||||
if (!parts[0].equals(expectedScope)) {
|
||||
throw new InvalidRequestException("Cursor belongs to another resource");
|
||||
}
|
||||
OffsetDateTime createdAt = OffsetDateTime.parse(parts[1]);
|
||||
UUID id = UUID.fromString(parts[2]);
|
||||
return new Cursor(parts[0], createdAt, id);
|
||||
} catch (InvalidRequestException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new InvalidRequestException("Invalid cursor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
server:
|
||||
port: ${APP_PORT:8080}
|
||||
address: 0.0.0.0
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: 10s
|
||||
jackson:
|
||||
property-naming-strategy: SNAKE_CASE
|
||||
serialization:
|
||||
write-dates-as-timestamps: false
|
||||
|
||||
# Настройка PostgreSQL
|
||||
datasource:
|
||||
url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger}
|
||||
username: ${SPRING_DATASOURCE_USERNAME:messenger}
|
||||
password: ${SPRING_DATASOURCE_PASSWORD:messenger}
|
||||
driver-class-name: org.postgresql.Driver
|
||||
|
||||
# Hibernate не должен сам создавать таблицы, это делает Flyway
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
show-sql: false
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
|
||||
# Миграции
|
||||
flyway:
|
||||
enabled: true
|
||||
baseline-on-migrate: true
|
||||
@@ -0,0 +1,44 @@
|
||||
-- Пользователи
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY,
|
||||
username VARCHAR(32) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
-- Чаты
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
-- Участники чатов (Many-to-Many)
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
-- Сообщения
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
-- Индекс для быстрой пагинации по (created_at, id) в рамках чата
|
||||
CREATE INDEX idx_messages_chat_created_at ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Сессии (для lab2)
|
||||
CREATE TABLE sessions (
|
||||
token VARCHAR(255) PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
-- Индекс для быстрой проверки сессий
|
||||
CREATE INDEX idx_sessions_expires_at ON sessions (expires_at);
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
key VARCHAR(128) NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
chat_id UUID NOT NULL,
|
||||
request_hash VARCHAR(64) NOT NULL, -- SHA-256 от тела запроса
|
||||
message_id UUID NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
PRIMARY KEY (key, user_id, chat_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_idempotency_created_at ON idempotency_keys (created_at);
|
||||
Reference in New Issue
Block a user