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