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
@@ -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();
}
}