concurrency

This commit is contained in:
2026-10-08 13:08:31 +03:00
parent b95197a6fc
commit 65bd58c409
42 changed files with 743 additions and 224 deletions
+53 -62
View File
@@ -1,24 +1,5 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
# Created by https://www.gitignore.io/api/git,java,maven,eclipse,windows
### Git ### ### Git ###
# Created by git for backups. To disable backups in Git:
# $ git config --global mergetool.keepBackup false
*.orig *.orig
# Created by git when using merge tools for conflicts
*.BACKUP.* *.BACKUP.*
*.BASE.* *.BASE.*
*.LOCAL.* *.LOCAL.*
@@ -29,7 +10,6 @@
*_REMOTE_*.txt *_REMOTE_*.txt
### Java ### ### Java ###
# Compiled class file
*.class *.class
# Log file # Log file
@@ -37,11 +17,9 @@
# BlueJ files # BlueJ files
*.ctxt *.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/
# Package Files # # Package files
*.jar *.jar
*.war *.war
*.nar *.nar
@@ -50,69 +28,82 @@
*.tar.gz *.tar.gz
*.rar *.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # JVM crash logs
hs_err_pid* hs_err_pid*
replay_pid*
### Gradle ###
.gradle/
build/
!gradle/wrapper/gradle-wrapper.jar
### Maven ###
target/
!.mvn/wrapper/maven-wrapper.jar
dependency-reduced-pom.xml
### IntelliJ IDEA ###
.idea/
*.iws
*.iml
*.ipr
### Eclipse / STS ###
.apt_generated
.classpath
.factorypath
.project
.settings/
.springBeans
.sts4-cache
### VS Code ###
.vscode/
### Windows ### ### Windows ###
# Windows thumbnail cache files
Thumbs.db Thumbs.db
ehthumbs.db ehthumbs.db
ehthumbs_vista.db ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini [Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/ $RECYCLE.BIN/
# Windows Installer files
*.cab *.cab
*.msi *.msi
*.msix *.msix
*.msm *.msm
*.msp *.msp
# Windows shortcuts
*.lnk *.lnk
### IntelliJ IDEA ### ### macOS ###
SpringTech/.idea .DS_Store
*.iws .AppleDouble
*.iml .LSOverride
*.ipr
### VS Code ### ### Miscellaneous ###
.vscode/
### Some additional ignores (sort later)
*.DS_Store
*.sw? *.sw?
.#* .#*
*# *#
*~ *~
.classpath bin/
.project
.settings
bin
/build/*
target
dependency-reduced-pom.xml
*.sublime-*
/scratch /scratch
.gradle *.sublime-*
README.html
*.iml ### Environment / Secrets ###
.idea
.exercism
# Environment
.env .env
.env.* .env.*
!.env.example !.env.example
secrets/
secrets/*.txt
!secrets/.gitkeep
### Python / venv ###
__pycache__/ __pycache__/
*.pyc *.pyc
!gradle/wrapper/gradle-wrapper.jar .venv/
secrets/ .venv
venv/
### Lab evidence ###
evidence/**/*.dump
evidence/**/*.sql.gz
evidence/**/raw/
evidence/**/*.raw
+4 -3
View File
@@ -36,9 +36,6 @@ dependencies {
implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1' implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1'
implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'com.fasterxml.jackson.core:jackson-databind'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1' testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1'
@@ -58,6 +55,10 @@ dependencies {
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
} }
tasks.withType(JavaCompile).configureEach {
options.compilerArgs << '-parameters'
}
tasks.named('test') { tasks.named('test') {
useJUnitPlatform() useJUnitPlatform()
} }
+33
View File
@@ -16,9 +16,32 @@
"bearerAuth": [] "bearerAuth": []
} }
], ],
"tags": [
{
"name": "Health",
"description": "Проверки живости и готовности процесса. Публичные, без аутентификации."
},
{
"name": "Users",
"description": "Регистрация пользователей и доступ к профилю текущего пользователя."
},
{
"name": "Auth",
"description": "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена."
},
{
"name": "Chats",
"description": "Управление чатами и доступ к чатам текущего пользователя."
},
{
"name": "Messages",
"description": "Отправка и чтение сообщений внутри доступного чата."
}
],
"paths": { "paths": {
"/health/live": { "/health/live": {
"get": { "get": {
"tags": ["Health"],
"operationId": "liveness", "operationId": "liveness",
"summary": "Процесс жив", "summary": "Процесс жив",
"responses": { "responses": {
@@ -66,6 +89,7 @@
}, },
"/health/ready": { "/health/ready": {
"get": { "get": {
"tags": ["Health"],
"operationId": "readiness", "operationId": "readiness",
"summary": "Готов принимать трафик", "summary": "Готов принимать трафик",
"responses": { "responses": {
@@ -132,6 +156,7 @@
}, },
"/api/v1/users": { "/api/v1/users": {
"post": { "post": {
"tags": ["Users"],
"operationId": "registerUser", "operationId": "registerUser",
"summary": "Создать пользователя", "summary": "Создать пользователя",
"responses": { "responses": {
@@ -272,6 +297,7 @@
}, },
"/api/v1/users/me": { "/api/v1/users/me": {
"get": { "get": {
"tags": ["Users"],
"operationId": "currentUser", "operationId": "currentUser",
"summary": "Текущий пользователь", "summary": "Текущий пользователь",
"responses": { "responses": {
@@ -445,6 +471,7 @@
}, },
"/api/v1/chats": { "/api/v1/chats": {
"post": { "post": {
"tags": ["Chats"],
"operationId": "createChat", "operationId": "createChat",
"summary": "Создать чат; вызывающий должен входить в member_ids", "summary": "Создать чат; вызывающий должен входить в member_ids",
"responses": { "responses": {
@@ -626,6 +653,7 @@
} }
}, },
"get": { "get": {
"tags": ["Chats"],
"operationId": "listChats", "operationId": "listChats",
"summary": "Чаты текущего пользователя", "summary": "Чаты текущего пользователя",
"responses": { "responses": {
@@ -819,6 +847,7 @@
}, },
"/api/v1/chats/{chat_id}": { "/api/v1/chats/{chat_id}": {
"get": { "get": {
"tags": ["Chats"],
"operationId": "getChat", "operationId": "getChat",
"summary": "Получить доступный чат", "summary": "Получить доступный чат",
"responses": { "responses": {
@@ -1003,6 +1032,7 @@
}, },
"/api/v1/chats/{chat_id}/messages": { "/api/v1/chats/{chat_id}/messages": {
"post": { "post": {
"tags": ["Messages"],
"operationId": "createMessage", "operationId": "createMessage",
"summary": "Отправить сообщение", "summary": "Отправить сообщение",
"responses": { "responses": {
@@ -1195,6 +1225,7 @@
} }
}, },
"get": { "get": {
"tags": ["Messages"],
"operationId": "listMessages", "operationId": "listMessages",
"summary": "Сообщения по (created_at, id) по возрастанию", "summary": "Сообщения по (created_at, id) по возрастанию",
"responses": { "responses": {
@@ -1397,6 +1428,7 @@
}, },
"/api/v1/auth/sessions": { "/api/v1/auth/sessions": {
"post": { "post": {
"tags": ["Auth"],
"operationId": "createSession", "operationId": "createSession",
"summary": "Вход: Basic username:password; выдаёт сессию", "summary": "Вход: Basic username:password; выдаёт сессию",
"responses": { "responses": {
@@ -1537,6 +1569,7 @@
}, },
"/api/v1/auth/sessions/current": { "/api/v1/auth/sessions/current": {
"delete": { "delete": {
"tags": ["Auth"],
"operationId": "revokeSession", "operationId": "revokeSession",
"summary": "Отозвать текущую сессию", "summary": "Отозвать текущую сессию",
"responses": { "responses": {
+25
View File
@@ -22,6 +22,26 @@ services:
retries: 10 retries: 10
start_period: 10s start_period: 10s
redis:
image: redis:7.4-alpine
container_name: messenger-redis
restart: unless-stopped
command: >
redis-server
--appendonly yes
--appendfsync everysec
--save ""
volumes:
- redisdata:/data
networks:
- messenger-net
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
api: api:
build: build:
context: . context: .
@@ -31,6 +51,8 @@ services:
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
redis:
condition: service_healthy
environment: environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger
SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user
@@ -38,6 +60,8 @@ services:
SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400}
SESSION_STORE: ${SESSION_STORE:-postgres} SESSION_STORE: ${SESSION_STORE:-postgres}
SPRING_DATA_REDIS_HOST: redis
SPRING_DATA_REDIS_PORT: 6379
ports: ports:
- "127.0.0.1:8080:8080" - "127.0.0.1:8080:8080"
secrets: secrets:
@@ -54,6 +78,7 @@ services:
volumes: volumes:
pgdata: pgdata:
redisdata:
networks: networks:
messenger-net: messenger-net:
+2
View File
@@ -0,0 +1,2 @@
@echo off
docker compose --env-file .env restart api db
+24
View File
@@ -0,0 +1,24 @@
-- создаём тестового юзера и чат
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed',
'$2a$10$abcdefghijklmnopqrstuv', now())
ON CONFLICT (username) DO NOTHING;
INSERT INTO chats (id, title, created_at)
VALUES ('22222222-2222-4222-8222-222222222222', 'seed_chat', now())
ON CONFLICT (id) DO NOTHING;
INSERT INTO chat_members (chat_id, user_id, role, joined_at)
VALUES ('22222222-2222-4222-8222-222222222222',
'11111111-1111-4111-8111-111111111111', 'owner', now())
ON CONFLICT DO NOTHING;
-- 10000 сообщений с разбросом created_at за последние 30 дней
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT
gen_random_uuid(),
'22222222-2222-4222-8222-222222222222',
'11111111-1111-4111-8111-111111111111',
'msg #' || g || ' ' || repeat('x', 1 + (random()*200)::int),
now() - (random() * interval '30 days')
FROM generate_series(1, 10000) g;
+75
View File
@@ -0,0 +1,75 @@
-- Пользователи
INSERT INTO users (id, username, display_name, password_hash, created_at)
SELECT
gen_random_uuid(),
'u_' || lpad(g::text, 4, '0'),
'User ' || g,
'$2a$10$abcdefghijklmnopqrstuv', -- фиктивный bcrypt-хеш, не для логина
now() - (random() * interval '60 days')
FROM generate_series(1, 20) g;
-- Один чат-гигант
INSERT INTO chats (id, title, created_at)
VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Huge chat', now() - interval '60 days');
INSERT INTO chat_members (chat_id, user_id)
SELECT 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', id FROM users LIMIT 5;
-- 50 000 сообщений в гиганта
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT
gen_random_uuid(),
'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
(SELECT id FROM users ORDER BY random() LIMIT 1),
'msg #' || g || ' ' || repeat('x', 1 + (random()*100)::int),
now() - (random() * interval '60 days')
FROM generate_series(1, 50000) g;
-- 5 чатов по 5000
DO $$
DECLARE
cid uuid;
i int;
BEGIN
FOR i IN 1..5 LOOP
cid := gen_random_uuid();
INSERT INTO chats (id, title, created_at)
VALUES (cid, 'Medium chat ' || i, now() - (random() * interval '60 days'));
INSERT INTO chat_members (chat_id, user_id)
SELECT cid, id FROM users LIMIT 3;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT
gen_random_uuid(), cid,
(SELECT id FROM users ORDER BY random() LIMIT 1),
'm-' || i || '-' || g || ' ' || repeat('x', 1 + (random()*100)::int),
now() - (random() * interval '60 days')
FROM generate_series(1, 5000) g;
END LOOP;
END $$;
-- 250 чатов по 100
DO $$
DECLARE
cid uuid;
i int;
BEGIN
FOR i IN 1..250 LOOP
cid := gen_random_uuid();
INSERT INTO chats (id, title, created_at)
VALUES (cid, 'Small chat ' || i, now() - (random() * interval '60 days'));
INSERT INTO chat_members (chat_id, user_id)
SELECT cid, id FROM users LIMIT 2;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT
gen_random_uuid(), cid,
(SELECT id FROM users ORDER BY random() LIMIT 1),
's-' || i || '-' || g,
now() - (random() * interval '60 days')
FROM generate_series(1, 100) g;
END LOOP;
END $$;
ANALYZE users;
ANALYZE chats;
ANALYZE chat_members;
ANALYZE messages;
@@ -0,0 +1,24 @@
package ru.mtusi.messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
public class ExecutorConfig {
@Bean(destroyMethod = "shutdown")
public ExecutorService cacheEvictExecutor() {
AtomicInteger counter = new AtomicInteger();
ThreadFactory factory = r -> {
Thread t = new Thread(r, "cache-evict-" + counter.incrementAndGet());
t.setDaemon(true);
return t;
};
return Executors.newSingleThreadExecutor(factory);
}
}
@@ -5,6 +5,7 @@ import io.github.bucket4j.Bucket;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import ru.mtusi.messenger.config.properties.RateLimitProperties;
import java.time.Duration; import java.time.Duration;
@@ -0,0 +1,102 @@
package ru.mtusi.messenger.config;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import io.lettuce.core.resource.DirContextDnsResolver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import ru.mtusi.messenger.config.properties.RedisProperties;
import ru.mtusi.messenger.config.properties.SessionProperties;
import ru.mtusi.messenger.service.SessionService;
@Slf4j
@Configuration
@EnableCaching
@EnableConfigurationProperties(RedisProperties.class)
@RequiredArgsConstructor
public class RedisConfig implements CachingConfigurer {
private final SessionProperties sessionProperties;
private final RedisProperties redisProperties;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration server =
new RedisStandaloneConfiguration(redisProperties.host(), redisProperties.port());
SocketOptions socketOptions = SocketOptions.builder()
.connectTimeout(redisProperties.connectTimeout())
.keepAlive(SocketOptions.KeepAliveOptions.builder()
.enable()
.idle(redisProperties.keepAliveIdle())
.interval(redisProperties.keepAliveInterval())
.count(3)
.build())
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
.tcpUserTimeout(redisProperties.tcpUserTimeout())
.enable()
.build())
.build();
ClientOptions clientOptions = ClientOptions.builder()
.socketOptions(socketOptions)
.autoReconnect(true)
.build();
LettuceClientConfiguration client = LettuceClientConfiguration.builder()
.commandTimeout(redisProperties.commandTimeout())
.shutdownTimeout(redisProperties.shutdownTimeout())
.clientOptions(clientOptions)
.build();
return new LettuceConnectionFactory(server, client);
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory cf) {
RedisCacheConfiguration cfg = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(sessionProperties.ttl())
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new JacksonJsonRedisSerializer<>(SessionService.SessionRecord.class)));
return RedisCacheManager.builder(cf).cacheDefaults(cfg).build();
}
@Override
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage());
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage());
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage());
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage());
}
};
}
}
@@ -1,4 +1,4 @@
package ru.mtusi.messenger.config; package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -1,4 +1,4 @@
package ru.mtusi.messenger.config; package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -0,0 +1,16 @@
package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
@ConfigurationProperties(prefix = "app.redis")
public record RedisProperties(
String host,
int port,
Duration commandTimeout,
Duration connectTimeout,
Duration shutdownTimeout,
Duration keepAliveIdle,
Duration keepAliveInterval,
Duration tcpUserTimeout
) {}
@@ -1,4 +1,4 @@
package ru.mtusi.messenger.config; package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -25,7 +25,7 @@ public class ChatController implements ChatsApi {
@Override @Override
public ResponseEntity<ChatDTO> getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) { public ResponseEntity<ChatDTO> getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.ok(chatService.getChat(principal.userId(), chatId)); return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId));
} }
@Override @Override
@@ -107,7 +107,7 @@ public interface ChatsApi {
* or Неожиданная ошибка без внутренних деталей (status code 500) * or Неожиданная ошибка без внутренних деталей (status code 500)
*/ */
@Operation( @Operation(
operationId = "getChat", operationId = "getChatDTO",
summary = "Получить доступный чат", summary = "Получить доступный чат",
tags = { "Chats" }, tags = { "Chats" },
responses = { responses = {
@@ -30,22 +30,22 @@ public interface HealthApi {
* or Неожиданная ошибка без внутренних деталей (status code 500) * or Неожиданная ошибка без внутренних деталей (status code 500)
*/ */
@Operation( @Operation(
operationId = "liveness", operationId = "liveness",
summary = "Процесс жив", summary = "Процесс жив",
tags = { "Health" }, tags = { "Health" },
responses = { responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = { @ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}), }),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
}) })
} }
) )
@RequestMapping( @RequestMapping(
method = RequestMethod.GET, method = RequestMethod.GET,
value = "/health/live", value = "/health/live",
produces = { "application/json" } produces = { "application/json" }
) )
ResponseEntity<HealthDTO> liveness( ResponseEntity<HealthDTO> liveness(
@@ -61,25 +61,25 @@ public interface HealthApi {
* or Неожиданная ошибка без внутренних деталей (status code 500) * or Неожиданная ошибка без внутренних деталей (status code 500)
*/ */
@Operation( @Operation(
operationId = "readiness", operationId = "readiness",
summary = "Готов принимать трафик", summary = "Готов принимать трафик",
tags = { "Health" }, tags = { "Health" },
responses = { responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = { @ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}), }),
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
}), }),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
}) })
} }
) )
@RequestMapping( @RequestMapping(
method = RequestMethod.GET, method = RequestMethod.GET,
value = "/health/ready", value = "/health/ready",
produces = { "application/json" } produces = { "application/json" }
) )
ResponseEntity<HealthDTO> readiness( ResponseEntity<HealthDTO> readiness(
@@ -1,26 +1,24 @@
package ru.mtusi.messenger.controller; package ru.mtusi.messenger.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.HealthDTO; import ru.mtusi.messenger.dto.HealthDTO;
import ru.mtusi.messenger.service.HealthService;
@RestController @RestController
@RequiredArgsConstructor
public class HealthController implements HealthApi { public class HealthController implements HealthApi {
private static final HealthDTO OK = createOk();
private final HealthService healthService;
@Override @Override
public ResponseEntity<HealthDTO> liveness() { public ResponseEntity<HealthDTO> liveness() {
return ResponseEntity.ok(OK); return ResponseEntity.ok(healthService.liveness());
} }
@Override @Override
public ResponseEntity<HealthDTO> readiness() { public ResponseEntity<HealthDTO> readiness() {
return ResponseEntity.ok(OK); return ResponseEntity.ok(healthService.readiness());
}
private static HealthDTO createOk() {
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
} }
} }
@@ -5,6 +5,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO; import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.MessagePageDTO; import ru.mtusi.messenger.dto.MessagePageDTO;
import ru.mtusi.messenger.security.SessionPrincipal; import ru.mtusi.messenger.security.SessionPrincipal;
@@ -18,8 +19,8 @@ public class MessageController implements MessagesApi {
private final MessageService messageService; private final MessageService messageService;
@Override @Override
public ResponseEntity<MessageDTO> createMessage(UUID chatId, MessageDTO messageDTO, @AuthenticationPrincipal SessionPrincipal principal) { public ResponseEntity<MessageDTO> createMessage(UUID chatId, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, messageDTO)); return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO));
} }
@Override @Override
@@ -6,6 +6,7 @@
package ru.mtusi.messenger.controller; package ru.mtusi.messenger.controller;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO; import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.ErrorDTO; import ru.mtusi.messenger.dto.ErrorDTO;
import ru.mtusi.messenger.dto.MessagePageDTO; import ru.mtusi.messenger.dto.MessagePageDTO;
@@ -77,8 +78,8 @@ public interface MessagesApi {
ResponseEntity<MessageDTO> createMessage( ResponseEntity<MessageDTO> createMessage(
@Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH)
@PathVariable("chat_id") UUID chatId, @PathVariable("chat_id") UUID chatId,
@Parameter(name = "MessageDTO", description = "", required = true) @Parameter(name = "CreateMessageDTO", description = "", required = true)
@Valid @RequestBody MessageDTO messageDTO, @Valid @RequestBody CreateMessageDTO createMessageDTO,
@AuthenticationPrincipal SessionPrincipal principal @AuthenticationPrincipal SessionPrincipal principal
); );
@@ -1,11 +1,14 @@
package ru.mtusi.messenger.exception; package ru.mtusi.messenger.controller.controllerAdvice;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
@@ -14,9 +17,10 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException; import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import ru.mtusi.messenger.config.RateLimitProperties; import ru.mtusi.messenger.config.properties.RateLimitProperties;
import ru.mtusi.messenger.dto.ErrorDTO; import ru.mtusi.messenger.dto.ErrorDTO;
import ru.mtusi.messenger.dto.ErrorErrorDTO; import ru.mtusi.messenger.dto.ErrorErrorDTO;
import ru.mtusi.messenger.exception.*;
@RestControllerAdvice @RestControllerAdvice
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -110,6 +114,30 @@ public class GlobalExceptionHandler {
"Internal error", req); "Internal error", req);
} }
@ExceptionHandler(ServiceUnavailableException.class)
public ResponseEntity<ErrorDTO> serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) {
return respond(HttpStatus.SERVICE_UNAVAILABLE,
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
e.getMessage(), req);
}
@ExceptionHandler({
CannotCreateTransactionException.class,
DataAccessResourceFailureException.class
})
public ResponseEntity<ErrorDTO> dependencyUnavailable(Exception e, HttpServletRequest req) {
return respond(HttpStatus.SERVICE_UNAVAILABLE,
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
"Dependency unavailable", req);
}
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<ErrorDTO> dataAccess(DataAccessException e, HttpServletRequest req) {
return respond(HttpStatus.INTERNAL_SERVER_ERROR,
ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
"Database error", req);
}
private ResponseEntity<ErrorDTO> respond(HttpStatus status, private ResponseEntity<ErrorDTO> respond(HttpStatus status,
ErrorErrorDTO.CodeEnum code, ErrorErrorDTO.CodeEnum code,
String message, String message,
@@ -1,6 +1,7 @@
package ru.mtusi.messenger.dto; package ru.mtusi.messenger.dto;
import java.util.Objects; import java.util.Objects;
import java.time.Instant;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
@@ -8,21 +9,23 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.constraints.*; import jakarta.validation.constraints.*;
import org.hibernate.validator.constraints.*;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import java.util.*; import java.util.*;
import jakarta.annotation.Generated; import jakarta.annotation.Generated;
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") @Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0")
public class ChatDTO { public class ChatDTO {
private UUID id;
private String title; private String title;
@Valid @Valid
private Set<UUID> memberIds = new LinkedHashSet<>(); private Set<UUID> memberIds = new LinkedHashSet<>();
private Instant createdAt;
public ChatDTO() { public ChatDTO() {
super(); super();
} }
@@ -35,15 +38,27 @@ public class ChatDTO {
this.memberIds = memberIds; this.memberIds = memberIds;
} }
public ChatDTO id(UUID id) {
this.id = id;
return this;
}
@Valid
@Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ChatDTO title(String title) { public ChatDTO title(String title) {
this.title = title; this.title = title;
return this; return this;
} }
/**
* Get title
* @return title
*/
@NotNull @Size(min = 1, max = 100) @NotNull @Size(min = 1, max = 100)
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("title") @JsonProperty("title")
@@ -68,10 +83,6 @@ public class ChatDTO {
return this; return this;
} }
/**
* Get memberIds
* @return memberIds
*/
@NotNull @Valid @Size(min = 1, max = 100) @NotNull @Valid @Size(min = 1, max = 100)
@Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("member_ids") @JsonProperty("member_ids")
@@ -84,6 +95,21 @@ public class ChatDTO {
this.memberIds = memberIds; this.memberIds = memberIds;
} }
public ChatDTO createdAt(Instant createdAt) {
this.createdAt = createdAt;
return this;
}
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("created_at")
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@@ -93,29 +119,29 @@ public class ChatDTO {
return false; return false;
} }
ChatDTO createChat = (ChatDTO) o; ChatDTO createChat = (ChatDTO) o;
return Objects.equals(this.title, createChat.title) && return Objects.equals(this.id, createChat.id) &&
Objects.equals(this.memberIds, createChat.memberIds); Objects.equals(this.title, createChat.title) &&
Objects.equals(this.memberIds, createChat.memberIds) &&
Objects.equals(this.createdAt, createChat.createdAt);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(title, memberIds); return Objects.hash(id, title, memberIds, createdAt);
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class CreateChat {\n"); sb.append("class ChatDTO {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n"); sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append("}"); sb.append("}");
return sb.toString(); return sb.toString();
} }
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) { private String toIndentedString(Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
@@ -123,4 +149,3 @@ public class ChatDTO {
return o.toString().replace("\n", "\n "); return o.toString().replace("\n", "\n ");
} }
} }
@@ -1,6 +1,8 @@
package ru.mtusi.messenger.dto; package ru.mtusi.messenger.dto;
import java.util.Objects; import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -70,6 +72,7 @@ public class ChatPageDTO {
* Get nextCursor * Get nextCursor
* @return nextCursor * @return nextCursor
*/ */
@JsonInclude(JsonInclude.Include.ALWAYS)
@Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@JsonProperty("next_cursor") @JsonProperty("next_cursor")
public String getNextCursor() { public String getNextCursor() {
@@ -1,6 +1,8 @@
package ru.mtusi.messenger.dto; package ru.mtusi.messenger.dto;
import java.util.Objects; import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -71,6 +73,7 @@ public class MessagePageDTO {
* Get nextCursor * Get nextCursor
* @return nextCursor * @return nextCursor
*/ */
@JsonInclude(JsonInclude.Include.ALWAYS)
@Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@JsonProperty("next_cursor") @JsonProperty("next_cursor")
public String getNextCursor() { public String getNextCursor() {
@@ -1,5 +1,6 @@
package ru.mtusi.messenger.dto; package ru.mtusi.messenger.dto;
import java.time.Instant;
import java.util.Objects; import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@@ -22,6 +23,8 @@ public class UserDTO {
private String password; private String password;
private Instant createdAt;
public UserDTO() { public UserDTO() {
super(); super();
} }
@@ -111,6 +114,25 @@ public class UserDTO {
this.password = password; this.password = password;
} }
public UserDTO createdAt(Instant createdAt) {
this.createdAt = createdAt;
return this;
}
/**
* Get createdAt
* @return createdAt
*/
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("created_at")
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@@ -123,12 +145,13 @@ public class UserDTO {
return Objects.equals(this.id, userDTO.id) && return Objects.equals(this.id, userDTO.id) &&
Objects.equals(this.username, userDTO.username) && Objects.equals(this.username, userDTO.username) &&
Objects.equals(this.displayName, userDTO.displayName) && Objects.equals(this.displayName, userDTO.displayName) &&
Objects.equals(this.password, userDTO.password); Objects.equals(this.password, userDTO.password) &&
Objects.equals(this.createdAt, userDTO.createdAt);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, username, displayName, password); return Objects.hash(id, username, displayName, password, createdAt);
} }
@Override @Override
@@ -139,6 +162,7 @@ public class UserDTO {
sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append("}"); sb.append("}");
return sb.toString(); return sb.toString();
} }
@@ -60,9 +60,12 @@ public class ApiErrorFactory {
} }
String mdc = MDC.get(REQUEST_ID_MDC); String mdc = MDC.get(REQUEST_ID_MDC);
if (mdc != null && !mdc.isBlank()) { if (mdc != null && !mdc.isBlank()) {
request.setAttribute(REQUEST_ID_ATTR, mdc);
return mdc; return mdc;
} }
return UUID.randomUUID().toString(); String generated = UUID.randomUUID().toString();
request.setAttribute(REQUEST_ID_ATTR, generated);
return generated;
} }
private String normalizeMessage(String message) { private String normalizeMessage(String message) {
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.exception;
public class ServiceUnavailableException extends RuntimeException {
public ServiceUnavailableException(String message) {
super(message);
}
}
@@ -10,8 +10,7 @@ import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import ru.mtusi.messenger.config.AppProperties; import ru.mtusi.messenger.config.properties.RateLimitProperties;
import ru.mtusi.messenger.config.RateLimitProperties;
import ru.mtusi.messenger.dto.ErrorErrorDTO; import ru.mtusi.messenger.dto.ErrorErrorDTO;
import ru.mtusi.messenger.exception.ApiErrorFactory; import ru.mtusi.messenger.exception.ApiErrorFactory;
@@ -2,6 +2,7 @@ package ru.mtusi.messenger.mapper;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.Mapping; import org.mapstruct.Mapping;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO; import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.model.Message; import ru.mtusi.messenger.model.Message;
@@ -17,4 +18,6 @@ public interface MessageMapper {
@Mapping(target = "chatId", source = "chat.id") @Mapping(target = "chatId", source = "chat.id")
@Mapping(target = "senderId", source = "sender.id") @Mapping(target = "senderId", source = "sender.id")
MessageDTO toMessageDTO(Message entity); MessageDTO toMessageDTO(Message entity);
Message toMessage(CreateMessageDTO dto);
} }
@@ -0,0 +1,17 @@
package ru.mtusi.messenger.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import ru.mtusi.messenger.dto.SessionDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.model.Session;
@Mapper(componentModel = "spring")
public interface SessionMapper {
@Mapping(target = "token", source = "tokenRaw")
@Mapping(target = "tokenType", expression = "java(ru.mtusi.messenger.dto.SessionDTO.TokenTypeEnum.BEARER)")
@Mapping(target = "expiresAt", source = "session.expiresAt")
@Mapping(target = "user", source = "userDTO")
SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO);
}
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
import lombok.*; import lombok.*;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@@ -47,6 +48,6 @@ public class Chat {
@PrePersist @PrePersist
private void onCreate() { private void onCreate() {
this.createdAt = Instant.now(); this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
} }
} }
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
import lombok.*; import lombok.*;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID; import java.util.UUID;
@Entity @Entity
@@ -34,6 +35,6 @@ public class Message {
@PrePersist @PrePersist
private void onCreate() { private void onCreate() {
this.createdAt = Instant.now(); this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
} }
} }
@@ -6,6 +6,7 @@ import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID; import java.util.UUID;
@Entity @Entity
@@ -35,7 +36,7 @@ public class Session {
@PrePersist @PrePersist
private void onCreate() { private void onCreate() {
this.createdAt = Instant.now(); this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
} }
} }
@@ -5,6 +5,7 @@ import lombok.*;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@@ -42,6 +43,6 @@ public class User{
@PrePersist @PrePersist
private void onCreate() { private void onCreate() {
this.createdAt = Instant.now(); this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
} }
} }
@@ -18,13 +18,22 @@ public interface ChatRepository extends JpaRepository<Chat, UUID> {
select distinct c from Chat c select distinct c from Chat c
join c.members m join c.members m
where m.id = :userId where m.id = :userId
and (:cursorCreated is null
or c.createdAt > :cursorCreated
or (c.createdAt = :cursorCreated and c.id > :cursorId))
order by c.createdAt asc, c.id asc order by c.createdAt asc, c.id asc
""") """)
List<Chat> findPageByMember(@Param("userId") UUID userId, List<Chat> findPageByMember(@Param("userId") UUID userId,
@Param("cursorCreated") Instant cursorCreated,
@Param("cursorId") UUID cursorId,
Pageable pageable); Pageable pageable);
@EntityGraph(attributePaths = "members")
@Query("""
select distinct c from Chat c
join c.members m
where m.id = :userId
and (c.createdAt > :cursorCreated
or (c.createdAt = :cursorCreated and c.id > :cursorId))
order by c.createdAt asc, c.id asc
""")
List<Chat> findPageByMemberAfterCursor(@Param("userId") UUID userId,
@Param("cursorCreated") Instant cursorCreated,
@Param("cursorId") UUID cursorId,
Pageable pageable);
} }
@@ -1,29 +1,39 @@
package ru.mtusi.messenger.repository; package ru.mtusi.messenger.repository;
import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import ru.mtusi.messenger.model.Message; import ru.mtusi.messenger.model.Message;
import org.springframework.data.domain.Pageable;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
public interface MessageRepository extends JpaRepository<Message, UUID> { public interface MessageRepository extends JpaRepository<Message, UUID> {
long countByChatId(UUID chatId);
@EntityGraph(attributePaths = "sender")
@Query(""" @Query("""
select m from Message m select m from Message m
where m.chat.id = :chatId where m.chat.id = :chatId
and (:cursorCreated is null
or m.createdAt > :cursorCreated
or (m.createdAt = :cursorCreated and m.id > :cursorId))
order by m.createdAt asc, m.id asc order by m.createdAt asc, m.id asc
""") """)
List<Message> findPageByChat(@Param("chatId") UUID chatId, List<Message> findPageByChat(@Param("chatId") UUID chatId,
@Param("cursorCreated") Instant cursorCreated,
@Param("cursorId") UUID cursorId,
Pageable pageable); Pageable pageable);
long countByChatId(UUID chatId); @EntityGraph(attributePaths = "sender")
@Query("""
select m from Message m
where m.chat.id = :chatId
and (m.createdAt > :cursorCreated
or (m.createdAt = :cursorCreated and m.id > :cursorId))
order by m.createdAt asc, m.id asc
""")
List<Message> findPageByChatAfterCursor(@Param("chatId") UUID chatId,
@Param("cursorCreated") Instant cursorCreated,
@Param("cursorId") UUID cursorId,
Pageable pageable);
} }
@@ -16,7 +16,6 @@ import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.ChatRepository; import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.util.CursorCodec; import ru.mtusi.messenger.util.CursorCodec;
import java.time.Instant;
import java.util.*; import java.util.*;
@Service @Service
@@ -54,7 +53,7 @@ public class ChatService {
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public ChatDTO getChat(UUID caller, UUID chatId) { public ChatDTO getChatDTO(UUID caller, UUID chatId) {
Chat chat = chatRepository.findById(chatId) Chat chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found")); .orElseThrow(() -> new NotFoundException("Chat not found"));
@@ -68,7 +67,8 @@ public class ChatService {
public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) {
int size = (limit == null) ? 50 : limit; int size = (limit == null) ? 50 : limit;
CursorCodec.Cursor decoded = parseChatsCursor(cursor); CursorCodec.Cursor decoded = parseChatsCursor(cursor);
List<Chat> rows = chatRepository.findPageByMember(userId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); List<Chat> rows = (decoded == null) ? chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1))
: chatRepository.findPageByMemberAfterCursor(userId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1));
return buildPage(rows, size); return buildPage(rows, size);
} }
@@ -83,14 +83,6 @@ public class ChatService {
return decoded; return decoded;
} }
private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) {
return cursor == null ? null : cursor.boundary().createdAt();
}
private UUID boundaryId(CursorCodec.Cursor cursor) {
return cursor == null ? null : cursor.boundary().id();
}
private ChatPageDTO buildPage(List<Chat> rows, int size) { private ChatPageDTO buildPage(List<Chat> rows, int size) {
List<ChatDTO> items = rows.stream() List<ChatDTO> items = rows.stream()
.limit(size) .limit(size)
@@ -114,4 +106,15 @@ public class ChatService {
private CursorCodec.PageBoundary boundaryOf(Chat chat) { private CursorCodec.PageBoundary boundaryOf(Chat chat) {
return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId());
} }
@Transactional(readOnly = true)
public Chat getChat(UUID caller, UUID chatId) {
Chat chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) {
throw new NotFoundException("Chat not found");
}
return chat;
}
} }
@@ -0,0 +1,31 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import ru.mtusi.messenger.dto.HealthDTO;
import ru.mtusi.messenger.exception.ServiceUnavailableException;
@Service
@RequiredArgsConstructor
public class HealthService {
private final JdbcTemplate jdbcTemplate;
public HealthDTO readiness() {
try {
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
} catch (Exception e) {
throw new ServiceUnavailableException("Database unavailable");
}
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
}
public HealthDTO liveness() {
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
}
}
@@ -6,8 +6,8 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.AppProperties; import ru.mtusi.messenger.config.properties.AppProperties;
import ru.mtusi.messenger.dto.ChatDTO; import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO; import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.MessagePageDTO; import ru.mtusi.messenger.dto.MessagePageDTO;
import ru.mtusi.messenger.exception.InvalidRequestException; import ru.mtusi.messenger.exception.InvalidRequestException;
@@ -19,10 +19,8 @@ import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.Message; import ru.mtusi.messenger.model.Message;
import ru.mtusi.messenger.model.User; import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.MessageRepository; import ru.mtusi.messenger.repository.MessageRepository;
import ru.mtusi.messenger.repository.UserRepository;
import ru.mtusi.messenger.util.CursorCodec; import ru.mtusi.messenger.util.CursorCodec;
import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -38,11 +36,11 @@ public class MessageService {
private final AppProperties appProperties; private final AppProperties appProperties;
@Transactional @Transactional
public MessageDTO createMessage(UUID senderId, UUID chatId, MessageDTO messageDTO) { public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO createMessageDTO) {
ChatDTO chatDTO = chatService.getChat(senderId, chatId); Chat chat = chatService.getChat(senderId, chatId);;
validateCreate(chatId, messageDTO); validateCreate(chatId, createMessageDTO);
User sender = userService.getReferenceUserById(senderId); User sender = userService.getReferenceUserById(senderId);
Message message = buildMessage(messageDTO, sender, chatDTO); Message message = buildMessage(createMessageDTO, sender, chat);
try { try {
message = messageRepository.saveAndFlush(message); message = messageRepository.saveAndFlush(message);
} catch (DataIntegrityViolationException e) { } catch (DataIntegrityViolationException e) {
@@ -53,7 +51,7 @@ public class MessageService {
return messageMapper.toMessageDTO(message); return messageMapper.toMessageDTO(message);
} }
private void validateCreate(UUID chatId, MessageDTO dto) { private void validateCreate(UUID chatId, CreateMessageDTO dto) {
if (dto.getText() == null || dto.getText().isBlank()) { if (dto.getText() == null || dto.getText().isBlank()) {
throw new InvalidRequestException("Empty text"); throw new InvalidRequestException("Empty text");
} }
@@ -62,9 +60,9 @@ public class MessageService {
} }
} }
private Message buildMessage(MessageDTO messageDTO, User sender, ChatDTO chatDTO) { private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) {
Message message = messageMapper.toMessage(messageDTO); Message message = messageMapper.toMessage(createMessageDTO);
message.setChat(chatMapper.toChat(chatDTO)); message.setChat(chat);
message.setSender(sender); message.setSender(sender);
return message; return message;
} }
@@ -72,9 +70,10 @@ public class MessageService {
@Transactional(readOnly = true) @Transactional(readOnly = true)
public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) { public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) {
int size = (limit == null) ? 50 : limit; int size = (limit == null) ? 50 : limit;
chatService.getChat(userId, chatId); chatService.getChatDTO(userId, chatId);
CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId); CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId);
List<Message> rows = messageRepository.findPageByChat(chatId, boundaryCreatedAt(decoded), boundaryId(decoded), Pageable.ofSize(size + 1)); List<Message> rows = (decoded == null) ? messageRepository.findPageByChat(chatId, Pageable.ofSize(size + 1))
: messageRepository.findPageByChatAfterCursor(chatId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1));
return buildPage(rows, size, chatId); return buildPage(rows, size, chatId);
} }
@@ -89,14 +88,6 @@ public class MessageService {
return decoded; return decoded;
} }
private Instant boundaryCreatedAt(CursorCodec.Cursor cursor) {
return cursor == null ? null : cursor.boundary().createdAt();
}
private UUID boundaryId(CursorCodec.Cursor cursor) {
return cursor == null ? null : cursor.boundary().id();
}
private MessagePageDTO buildPage(List<Message> rows, int size, UUID chatId) { private MessagePageDTO buildPage(List<Message> rows, int size, UUID chatId) {
List<MessageDTO> items = rows.stream() List<MessageDTO> items = rows.stream()
.limit(size) .limit(size)
@@ -2,40 +2,52 @@ package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.SessionProperties; import ru.mtusi.messenger.config.properties.SessionProperties;
import ru.mtusi.messenger.dto.SessionDTO; import ru.mtusi.messenger.dto.SessionDTO;
import ru.mtusi.messenger.dto.UserDTO; import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.UnauthorizedException; import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.mapper.SessionMapper;
import ru.mtusi.messenger.model.Session; import ru.mtusi.messenger.model.Session;
import ru.mtusi.messenger.repository.SessionRepository; import ru.mtusi.messenger.repository.SessionRepository;
import ru.mtusi.messenger.util.TokenGenerator; import ru.mtusi.messenger.util.TokenGenerator;
import ru.mtusi.messenger.util.TokenHasher;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutorService;
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
@Service @Service
public class SessionService { public class SessionService {
private static final String SESSIONS = "sessions";
private final TokenGenerator tokenGenerator; private final TokenGenerator tokenGenerator;
private final TokenHasher tokenHasher;
private final SessionProperties sessionProperties; private final SessionProperties sessionProperties;
private final SessionRepository sessionRepository; private final SessionRepository sessionRepository;
private final SessionMapper sessionMapper;
private final CacheManager cacheManager;
private final ExecutorService cacheEvictExecutor;
@Transactional @Transactional
public SessionDTO createSession(UserDTO userDTO) { public SessionDTO createSession(UserDTO userDTO) {
String token = tokenGenerator.generate(); String token = tokenGenerator.generate();
Session session = sessionRepository.save(buildSession(userDTO,token)); Session session = sessionRepository.save(buildSession(userDTO,token));
return toSessionDTO(session, token, userDTO); return sessionMapper.toSessionDTO(session, token, userDTO);
} }
@Cacheable(value = SESSIONS, key = "@tokenHasher.hash(#token)")
@Transactional(readOnly = true) @Transactional(readOnly = true)
public SessionRecord requireActive(String token) { public SessionRecord requireActive(String token) {
Session s = sessionRepository.findByTokenHash(sha256(token)) Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token))
.filter(x -> x.getRevokedAt() == null) .filter(x -> x.getRevokedAt() == null)
.filter(x -> x.getExpiresAt().isAfter(Instant.now())) .filter(x -> x.getExpiresAt().isAfter(Instant.now()))
.orElseThrow(() -> new UnauthorizedException("Invalid or expired session")); .orElseThrow(() -> new UnauthorizedException("Invalid or expired session"));
@@ -46,35 +58,29 @@ public class SessionService {
public void revoke(UUID sessionId) { public void revoke(UUID sessionId) {
sessionRepository.findById(sessionId).ifPresent(s -> { sessionRepository.findById(sessionId).ifPresent(s -> {
if (s.getRevokedAt() == null) { if (s.getRevokedAt() == null) {
s.setRevokedAt(Instant.now()); s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
} }
String key = tokenHasher.hash(s.getTokenHash());
cacheEvictExecutor.submit(() -> {
try {
Cache cache = cacheManager.getCache(SESSIONS);
if (cache != null) {
cache.evict(key);
}
} catch (RuntimeException e) {
log.warn("Cache EVICT failed (sessions): {}", e.getMessage());
}
});
}); });
} }
private static byte[] sha256(String token) {
try {
return MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 not available", e);
}
}
private Session buildSession(UserDTO userDTO, String token) { private Session buildSession(UserDTO userDTO, String token) {
Session session = new Session(); Session session = new Session();
session.setUserId(userDTO.getId()); session.setUserId(userDTO.getId());
session.setTokenHash(sha256(token)); session.setTokenHash(tokenHasher.sha256(token));
session.setExpiresAt(Instant.now().plus(sessionProperties.ttl())); session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS));
return session; return session;
} }
private SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO) {
return new SessionDTO()
.token(tokenRaw)
.tokenType(SessionDTO.TokenTypeEnum.BEARER)
.expiresAt(session.getExpiresAt())
.user(userDTO);
}
public record SessionRecord(UUID sessionId, UUID userId) {} public record SessionRecord(UUID sessionId, UUID userId) {}
} }
@@ -0,0 +1,37 @@
package ru.mtusi.messenger.util;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Component("tokenHasher")
public class TokenHasher {
public byte[] sha256(String token) {
try {
return MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 not available", e);
}
}
public String hash(String token) {
return toHex(sha256(token));
}
public String hash(byte[] bytes) {
return toHex(bytes);
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
sb.append(Character.forDigit(b & 0xF, 16));
}
return sb.toString();
}
}
+22
View File
@@ -14,6 +14,13 @@ spring:
url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger} url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger}
username: ${SPRING_DATASOURCE_USERNAME:messenger} username: ${SPRING_DATASOURCE_USERNAME:messenger}
password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only} password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only}
hikari:
connection-timeout: 2000
validation-timeout: 1000
maximum-pool-size: 10
minimum-idle: 2
idle-timeout: 60000
max-lifetime: 1800000
jpa: jpa:
hibernate: hibernate:
ddl-auto: validate ddl-auto: validate
@@ -26,6 +33,12 @@ spring:
flyway: flyway:
enabled: true enabled: true
locations: classpath:db/migration locations: classpath:db/migration
data:
redis:
host: ${SPRING_DATA_REDIS_HOST:localhost}
port: ${SPRING_DATA_REDIS_PORT:6379}
cache:
type: redis
server: server:
address: ${APP_HOST:0.0.0.0} address: ${APP_HOST:0.0.0.0}
@@ -51,6 +64,15 @@ app:
retry-after-seconds: ${RETRY_AFTER_SECONDS:60} retry-after-seconds: ${RETRY_AFTER_SECONDS:60}
session: session:
ttl: ${SESSION_TTL_SECONDS:400}s ttl: ${SESSION_TTL_SECONDS:400}s
redis:
host: ${SPRING_DATA_REDIS_HOST:localhost}
port: ${SPRING_DATA_REDIS_PORT:6379}
command-timeout: ${REDIS_COMMAND_TIMEOUT:500ms}
connect-timeout: ${REDIS_CONNECT_TIMEOUT:500ms}
shutdown-timeout: ${REDIS_SHUTDOWN_TIMEOUT:100ms}
keep-alive-idle: ${REDIS_KEEP_ALIVE_IDLE:30s}
keep-alive-interval: ${REDIS_KEEP_ALIVE_INTERVAL:10s}
tcp-user-timeout: ${REDIS_TCP_USER_TIMEOUT:10s}
logging: logging:
pattern: pattern: