Исправление валидации и обеспечение консинстентности кэша после падения редис
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Исправление security context утечки
This commit is contained in:
@@ -0,0 +1,19 @@
|
|||||||
|
package ru.mtusi.messenger.cache;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CacheHealthTracker {
|
||||||
|
|
||||||
|
private final AtomicBoolean stale = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
public void markStale() {
|
||||||
|
stale.set(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean consumeStale() {
|
||||||
|
return stale.getAndSet(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,9 +2,6 @@ package ru.mtusi.messenger.config;
|
|||||||
|
|
||||||
import io.lettuce.core.ClientOptions;
|
import io.lettuce.core.ClientOptions;
|
||||||
import io.lettuce.core.SocketOptions;
|
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.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
@@ -22,6 +19,7 @@ import org.springframework.data.redis.connection.lettuce.LettuceClientConfigurat
|
|||||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||||
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
|
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
|
||||||
import org.springframework.data.redis.serializer.RedisSerializationContext;
|
import org.springframework.data.redis.serializer.RedisSerializationContext;
|
||||||
|
import ru.mtusi.messenger.cache.CacheHealthTracker;
|
||||||
import ru.mtusi.messenger.config.properties.RedisProperties;
|
import ru.mtusi.messenger.config.properties.RedisProperties;
|
||||||
import ru.mtusi.messenger.config.properties.SessionProperties;
|
import ru.mtusi.messenger.config.properties.SessionProperties;
|
||||||
import ru.mtusi.messenger.service.SessionService;
|
import ru.mtusi.messenger.service.SessionService;
|
||||||
@@ -34,6 +32,7 @@ import ru.mtusi.messenger.service.SessionService;
|
|||||||
public class RedisConfig implements CachingConfigurer {
|
public class RedisConfig implements CachingConfigurer {
|
||||||
private final SessionProperties sessionProperties;
|
private final SessionProperties sessionProperties;
|
||||||
private final RedisProperties redisProperties;
|
private final RedisProperties redisProperties;
|
||||||
|
private final CacheHealthTracker cacheHealthTracker;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public RedisConnectionFactory redisConnectionFactory() {
|
public RedisConnectionFactory redisConnectionFactory() {
|
||||||
@@ -83,19 +82,23 @@ public class RedisConfig implements CachingConfigurer {
|
|||||||
return new CacheErrorHandler() {
|
return new CacheErrorHandler() {
|
||||||
@Override
|
@Override
|
||||||
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
|
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
|
||||||
log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage(), e);
|
cacheHealthTracker.markStale();
|
||||||
|
log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
@Override
|
@Override
|
||||||
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
|
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
|
||||||
log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage(), e);
|
cacheHealthTracker.markStale();
|
||||||
|
log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
@Override
|
@Override
|
||||||
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
|
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
|
||||||
log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage(), e);
|
cacheHealthTracker.markStale();
|
||||||
|
log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
@Override
|
@Override
|
||||||
public void handleCacheClearError(RuntimeException e, Cache cache) {
|
public void handleCacheClearError(RuntimeException e, Cache cache) {
|
||||||
log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage(), e);
|
cacheHealthTracker.markStale();
|
||||||
|
log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
@@ -29,7 +29,7 @@ public class SecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PasswordEncoder passwordEncoder() {
|
public PasswordEncoder passwordEncoder() {
|
||||||
return new BCryptPasswordEncoder();
|
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
@@ -3,9 +3,6 @@ package ru.mtusi.messenger.dto;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
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.*;
|
||||||
@@ -13,6 +10,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
|||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import jakarta.annotation.Generated;
|
import jakarta.annotation.Generated;
|
||||||
|
import org.hibernate.validator.constraints.CodePointLength;
|
||||||
|
|
||||||
@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 {
|
||||||
@@ -22,7 +20,7 @@ public class ChatDTO {
|
|||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@Valid
|
@Valid
|
||||||
private Set<UUID> memberIds = new LinkedHashSet<>();
|
private List<UUID> memberIds = new ArrayList<>();
|
||||||
|
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
|
|
||||||
@@ -33,7 +31,7 @@ public class ChatDTO {
|
|||||||
/**
|
/**
|
||||||
* Constructor with only required parameters
|
* Constructor with only required parameters
|
||||||
*/
|
*/
|
||||||
public ChatDTO(String title, Set<UUID> memberIds) {
|
public ChatDTO(String title, List<UUID> memberIds) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
this.memberIds = memberIds;
|
this.memberIds = memberIds;
|
||||||
}
|
}
|
||||||
@@ -59,7 +57,8 @@ public class ChatDTO {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull @Size(min = 1, max = 100)
|
@NotNull
|
||||||
|
@CodePointLength(min = 1, max = 100)
|
||||||
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
@JsonProperty("title")
|
@JsonProperty("title")
|
||||||
public String getTitle() {
|
public String getTitle() {
|
||||||
@@ -70,14 +69,14 @@ public class ChatDTO {
|
|||||||
this.title = title;
|
this.title = title;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChatDTO memberIds(Set<UUID> memberIds) {
|
public ChatDTO memberIds(List<UUID> memberIds) {
|
||||||
this.memberIds = memberIds;
|
this.memberIds = memberIds;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChatDTO addMemberIdsItem(UUID memberIdsItem) {
|
public ChatDTO addMemberIdsItem(UUID memberIdsItem) {
|
||||||
if (this.memberIds == null) {
|
if (this.memberIds == null) {
|
||||||
this.memberIds = new LinkedHashSet<>();
|
this.memberIds = new ArrayList<>();
|
||||||
}
|
}
|
||||||
this.memberIds.add(memberIdsItem);
|
this.memberIds.add(memberIdsItem);
|
||||||
return this;
|
return this;
|
||||||
@@ -86,12 +85,11 @@ public class ChatDTO {
|
|||||||
@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")
|
||||||
public Set<UUID> getMemberIds() {
|
public List<UUID> getMemberIds() {
|
||||||
return memberIds;
|
return memberIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonDeserialize(as = LinkedHashSet.class)
|
public void setMemberIds(List<UUID> memberIds) {
|
||||||
public void setMemberIds(Set<UUID> memberIds) {
|
|
||||||
this.memberIds = memberIds;
|
this.memberIds = memberIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
|||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
|
import org.hibernate.validator.constraints.CodePointLength;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@@ -19,7 +20,8 @@ public class CreateMessageDTO {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull @Size(min = 1, max = 4000)
|
@NotNull
|
||||||
|
@CodePointLength(min = 1, max = 4000)
|
||||||
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
@JsonProperty("text")
|
@JsonProperty("text")
|
||||||
public String getText() { return text; }
|
public String getText() { return text; }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
|||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.*;
|
import jakarta.validation.constraints.*;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import org.hibernate.validator.constraints.CodePointLength;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -109,7 +110,8 @@ public class MessageDTO {
|
|||||||
* Get text
|
* Get text
|
||||||
* @return text
|
* @return text
|
||||||
*/
|
*/
|
||||||
@NotNull @Size(min = 1, max = 4000)
|
@NotNull
|
||||||
|
@CodePointLength(min = 1, max = 4000)
|
||||||
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
@JsonProperty("text")
|
@JsonProperty("text")
|
||||||
public String getText() {
|
public String getText() {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
|||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.*;
|
import jakarta.validation.constraints.*;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import org.hibernate.validator.constraints.CodePointLength;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@@ -83,7 +84,8 @@ public class UserDTO {
|
|||||||
* Get displayName
|
* Get displayName
|
||||||
* @return displayName
|
* @return displayName
|
||||||
*/
|
*/
|
||||||
@NotNull @Size(min = 1, max = 100)
|
@NotNull
|
||||||
|
@CodePointLength(min = 1, max = 100)
|
||||||
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
@JsonProperty("display_name")
|
@JsonProperty("display_name")
|
||||||
public String getDisplayName() {
|
public String getDisplayName() {
|
||||||
@@ -103,7 +105,8 @@ public class UserDTO {
|
|||||||
* Get password
|
* Get password
|
||||||
* @return password
|
* @return password
|
||||||
*/
|
*/
|
||||||
@NotNull @Size(min = 12, max = 128)
|
@NotNull
|
||||||
|
@CodePointLength(min = 1, max = 100)
|
||||||
@Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED)
|
@Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
@JsonProperty("password")
|
@JsonProperty("password")
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
|
|||||||
@@ -7,17 +7,17 @@ import ru.mtusi.messenger.dto.ChatDTO;
|
|||||||
import ru.mtusi.messenger.model.Chat;
|
import ru.mtusi.messenger.model.Chat;
|
||||||
import ru.mtusi.messenger.model.User;
|
import ru.mtusi.messenger.model.User;
|
||||||
|
|
||||||
import java.util.LinkedHashSet;
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Mapper(componentModel = "spring")
|
@Mapper(componentModel = "spring")
|
||||||
public interface ChatMapper {
|
public interface ChatMapper {
|
||||||
|
|
||||||
@Mapping(target = "id", ignore = true)
|
@Mapping(target = "id", ignore = true)
|
||||||
@Mapping(target = "createdAt", ignore = true)
|
@Mapping(target = "createdAt", ignore = true)
|
||||||
@Mapping(target = "members", ignore = true) // ← заполнит ChatService
|
@Mapping(target = "members", ignore = true)
|
||||||
@Mapping(target = "messages", ignore = true)
|
@Mapping(target = "messages", ignore = true)
|
||||||
Chat toChat(ChatDTO dto);
|
Chat toChat(ChatDTO dto);
|
||||||
|
|
||||||
@@ -25,10 +25,10 @@ public interface ChatMapper {
|
|||||||
ChatDTO toChatDto(Chat chat);
|
ChatDTO toChatDto(Chat chat);
|
||||||
|
|
||||||
@Named("usersToIds")
|
@Named("usersToIds")
|
||||||
default Set<UUID> usersToIds(Set<User> users) {
|
default List<UUID> usersToIds(Set<User> users) {
|
||||||
if (users == null) return new LinkedHashSet<>();
|
if (users == null) return new ArrayList<>();
|
||||||
return users.stream()
|
List<UUID> ids = new ArrayList<>(users.size());
|
||||||
.map(User::getId)
|
for (User u : users) ids.add(u.getId());
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
return ids;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,10 @@ import jakarta.servlet.ServletException;
|
|||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
|
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
@@ -24,16 +24,22 @@ public class SessionAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
protected void doFilterInternal(HttpServletRequest request,
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain chain) throws ServletException, IOException {
|
FilterChain chain) throws ServletException, IOException {
|
||||||
String token = bearerTokenResolver.resolve(request);
|
try {
|
||||||
|
String token = bearerTokenResolver.resolve(request);
|
||||||
if (token != null && !token.isBlank()) {
|
if (token != null && !token.isBlank()) {
|
||||||
try {
|
try {
|
||||||
Authentication auth = authenticationManager.authenticate(
|
Authentication auth = authenticationManager.authenticate(
|
||||||
new SessionAuthenticationToken(token));
|
new SessionAuthenticationToken(token));
|
||||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||||
|
context.setAuthentication(auth);
|
||||||
|
SecurityContextHolder.setContext(context);
|
||||||
} catch (AuthenticationException e) {
|
} catch (AuthenticationException e) {
|
||||||
SecurityContextHolder.clearContext();
|
SecurityContextHolder.clearContext();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
chain.doFilter(request, response);
|
chain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,7 @@ import ru.mtusi.messenger.mapper.ChatMapper;
|
|||||||
import ru.mtusi.messenger.model.Chat;
|
import ru.mtusi.messenger.model.Chat;
|
||||||
import ru.mtusi.messenger.model.User;
|
import ru.mtusi.messenger.model.User;
|
||||||
import ru.mtusi.messenger.repository.ChatRepository;
|
import ru.mtusi.messenger.repository.ChatRepository;
|
||||||
|
import ru.mtusi.messenger.validation.ChatValidator;
|
||||||
import ru.mtusi.messenger.util.CursorCodec;
|
import ru.mtusi.messenger.util.CursorCodec;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -23,55 +24,74 @@ import java.util.*;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ChatService {
|
public class ChatService {
|
||||||
private final ChatMapper chatMapper;
|
private final ChatMapper chatMapper;
|
||||||
private final UserService userService;
|
private final ChatValidator chatValidator;
|
||||||
private final ChatRepository chatRepository;
|
private final ChatRepository chatRepository;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public ChatDTO createChat(UUID caller , ChatDTO chatDTO) {
|
public ChatDTO createChat(UUID caller, ChatDTO chatDTO) {
|
||||||
Set<User> members = validateCreate(caller, chatDTO);
|
Set<User> members = chatValidator.validateCreate(caller, chatDTO);
|
||||||
Chat chat = buildChat(chatDTO, members);
|
Chat chat = buildChat(chatDTO, members);
|
||||||
try {
|
chat = persistChat(chat);
|
||||||
chat = chatRepository.saveAndFlush(chat);
|
|
||||||
} catch (DataIntegrityViolationException e) {
|
|
||||||
throw new NotFoundException("Cannot create chat: referenced entity is missing");
|
|
||||||
}
|
|
||||||
return chatMapper.toChatDto(chat);
|
return chatMapper.toChatDto(chat);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<User> validateCreate(UUID caller, ChatDTO chatDTO) {
|
|
||||||
Set<UUID> memberIds = chatDTO.getMemberIds();
|
|
||||||
if (!memberIds.contains(caller)) {
|
|
||||||
throw new InvalidRequestException("Вызывающий должен быть участником");
|
|
||||||
}
|
|
||||||
return userService.requireUsers(memberIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Chat buildChat(ChatDTO chatDTO, Set<User> members) {
|
private Chat buildChat(ChatDTO chatDTO, Set<User> members) {
|
||||||
Chat chat = chatMapper.toChat(chatDTO);
|
Chat chat = chatMapper.toChat(chatDTO);
|
||||||
chat.setMembers(members);
|
chat.setMembers(members);
|
||||||
return chat;
|
return chat;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Chat persistChat(Chat chat) {
|
||||||
|
try {
|
||||||
|
return chatRepository.saveAndFlush(chat);
|
||||||
|
} catch (DataIntegrityViolationException e) {
|
||||||
|
throw new InvalidRequestException("Cannot create chat: invalid data");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public ChatDTO getChatDTO(UUID caller, UUID chatId) {
|
public ChatDTO getChatDTO(UUID caller, UUID chatId) {
|
||||||
Chat chat = chatRepository.findById(chatId)
|
Chat chat = requireChatForMember(caller, chatId);
|
||||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
|
||||||
|
|
||||||
if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) {
|
|
||||||
throw new NotFoundException("Chat not found");
|
|
||||||
}
|
|
||||||
return chatMapper.toChatDto(chat);
|
return chatMapper.toChatDto(chat);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Chat getChat(UUID caller, UUID chatId) {
|
||||||
|
return requireChatForMember(caller, chatId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Chat requireChatForMember(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;
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
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 = resolveSize(limit);
|
||||||
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
|
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
|
||||||
List<Chat> rows = (decoded == null) ? chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1))
|
List<Chat> rows = loadChatPage(userId, decoded, size);
|
||||||
: chatRepository.findPageByMemberAfterCursor(userId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1));
|
|
||||||
return buildPage(rows, size);
|
return buildPage(rows, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int resolveSize(Integer limit) {
|
||||||
|
return (limit == null) ? 50 : limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Chat> loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) {
|
||||||
|
if (cursor == null) {
|
||||||
|
return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1));
|
||||||
|
}
|
||||||
|
return chatRepository.findPageByMemberAfterCursor(
|
||||||
|
userId,
|
||||||
|
cursor.boundary().createdAt(),
|
||||||
|
cursor.boundary().id(),
|
||||||
|
Pageable.ofSize(size + 1));
|
||||||
|
}
|
||||||
|
|
||||||
private CursorCodec.Cursor parseChatsCursor(String cursor) {
|
private CursorCodec.Cursor parseChatsCursor(String cursor) {
|
||||||
if (cursor == null || cursor.isBlank()) {
|
if (cursor == null || cursor.isBlank()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -106,15 +126,4 @@ 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,65 @@
|
|||||||
|
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.CacheEvict;
|
||||||
|
import org.springframework.cache.annotation.Cacheable;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import ru.mtusi.messenger.cache.CacheHealthTracker;
|
||||||
|
import ru.mtusi.messenger.repository.SessionRepository;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SessionCacheService {
|
||||||
|
|
||||||
|
public static final String SESSIONS = "sessions";
|
||||||
|
|
||||||
|
private final SessionRepository sessionRepository;
|
||||||
|
private final CacheManager cacheManager;
|
||||||
|
private final CacheHealthTracker cacheHealthTracker;
|
||||||
|
|
||||||
|
@Cacheable(value = SESSIONS, key = "#hex", unless = "#result == null")
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public SessionService.SessionRecord lookupByHash(String hex) {
|
||||||
|
byte[] hash = hexToBytes(hex);
|
||||||
|
return sessionRepository.findByTokenHash(hash)
|
||||||
|
.filter(s -> s.getRevokedAt() == null)
|
||||||
|
.map(s -> new SessionService.SessionRecord(
|
||||||
|
s.getId(), s.getUserId(), s.getExpiresAt()))
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@CacheEvict(value = SESSIONS, key = "#hex")
|
||||||
|
public void evict(String hex) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public void dropCacheIfStale() {
|
||||||
|
if (!cacheHealthTracker.consumeStale()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Cache cache = cacheManager.getCache(SESSIONS);
|
||||||
|
if (cache != null) {
|
||||||
|
cache.clear();
|
||||||
|
}
|
||||||
|
log.info("Cache '{}' cleared after stale flag", SESSIONS);
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
log.warn("Cache clear failed: {}", e.getMessage());
|
||||||
|
cacheHealthTracker.markStale();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] hexToBytes(String hex) {
|
||||||
|
int len = hex.length();
|
||||||
|
byte[] out = new byte[len / 2];
|
||||||
|
for (int i = 0; i < len; i += 2) {
|
||||||
|
out[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
|
||||||
|
+ Character.digit(hex.charAt(i + 1), 16));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,7 @@ 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.stereotype.Service;
|
||||||
import org.springframework.cache.CacheManager;
|
|
||||||
import org.springframework.cache.annotation.Cacheable;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import ru.mtusi.messenger.config.properties.SessionProperties;
|
import ru.mtusi.messenger.config.properties.SessionProperties;
|
||||||
import ru.mtusi.messenger.dto.SessionDTO;
|
import ru.mtusi.messenger.dto.SessionDTO;
|
||||||
@@ -20,22 +17,17 @@ import ru.mtusi.messenger.util.TokenHasher;
|
|||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.temporal.ChronoUnit;
|
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 TokenHasher tokenHasher;
|
||||||
private final SessionProperties sessionProperties;
|
private final SessionProperties sessionProperties;
|
||||||
private final SessionRepository sessionRepository;
|
private final SessionRepository sessionRepository;
|
||||||
private final SessionMapper sessionMapper;
|
private final SessionMapper sessionMapper;
|
||||||
private final CacheManager cacheManager;
|
private final SessionCacheService sessionCacheService;
|
||||||
private final ExecutorService cacheEvictExecutor;
|
|
||||||
|
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public SessionDTO createSession(UserDTO userDTO) {
|
public SessionDTO createSession(UserDTO userDTO) {
|
||||||
@@ -44,43 +36,46 @@ public class SessionService {
|
|||||||
return sessionMapper.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) {
|
public SessionRecord requireActive(String token) {
|
||||||
Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token))
|
sessionCacheService.dropCacheIfStale();
|
||||||
.filter(x -> x.getRevokedAt() == null)
|
String hex = tokenHasher.hash(token);
|
||||||
.filter(x -> x.getExpiresAt().isAfter(Instant.now()))
|
SessionRecord record = sessionCacheService.lookupByHash(hex);
|
||||||
.orElseThrow(() -> new UnauthorizedException("Invalid or expired session"));
|
requireNotExpired(record, hex);
|
||||||
return new SessionRecord(s.getId(), s.getUserId());
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireNotExpired(SessionRecord record, String hex) {
|
||||||
|
if (record == null || isExpired(record)) {
|
||||||
|
sessionCacheService.evict(hex);
|
||||||
|
throw new UnauthorizedException("Invalid or expired session");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isExpired(SessionRecord record) {
|
||||||
|
return record.expiresAt().isBefore(Instant.now());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void revoke(UUID sessionId) {
|
public void revoke(UUID sessionId) {
|
||||||
sessionRepository.findById(sessionId).ifPresent(s -> {
|
sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict);
|
||||||
if (s.getRevokedAt() == null) {
|
}
|
||||||
s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
|
||||||
}
|
private void markRevokedAndEvict(Session session) {
|
||||||
String key = tokenHasher.hash(s.getTokenHash());
|
if (session.getRevokedAt() == null) {
|
||||||
cacheEvictExecutor.submit(() -> {
|
session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
||||||
try {
|
}
|
||||||
Cache cache = cacheManager.getCache(SESSIONS);
|
sessionCacheService.evict(tokenHasher.hash(session.getTokenHash()));
|
||||||
if (cache != null) {
|
|
||||||
cache.evict(key);
|
|
||||||
}
|
|
||||||
} catch (RuntimeException e) {
|
|
||||||
log.warn("Cache EVICT failed (sessions): {}", e.getMessage());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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(tokenHasher.sha256(token));
|
session.setTokenHash(tokenHasher.sha256(token));
|
||||||
session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS));
|
session.setExpiresAt(Instant.now()
|
||||||
|
.plus(sessionProperties.ttl())
|
||||||
|
.truncatedTo(ChronoUnit.MILLIS));
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
public record SessionRecord(UUID sessionId, UUID userId) {}
|
public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {}
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,7 @@ import ru.mtusi.messenger.mapper.UserMapper;
|
|||||||
import ru.mtusi.messenger.model.User;
|
import ru.mtusi.messenger.model.User;
|
||||||
import ru.mtusi.messenger.repository.UserRepository;
|
import ru.mtusi.messenger.repository.UserRepository;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -28,10 +29,11 @@ public class UserService {
|
|||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Set<User> requireUsers(Set<UUID> ids) {
|
public Set<User> requireUsers(Collection<UUID> ids) {
|
||||||
Set<User> users = userRepository.findAllByIdForShare(ids);
|
Set<UUID> uniqueIds = new HashSet<>(ids);
|
||||||
if (users.size() != ids.size()) {
|
Set<User> users = userRepository.findAllByIdForShare(uniqueIds);
|
||||||
throw new NotFoundException("Users not found: " + findMissing(ids, users));
|
if (users.size() != uniqueIds.size()) {
|
||||||
|
throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users));
|
||||||
}
|
}
|
||||||
return users;
|
return users;
|
||||||
}
|
}
|
||||||
@@ -78,4 +80,4 @@ public class UserService {
|
|||||||
public User getReferenceUserById(UUID senderId) {
|
public User getReferenceUserById(UUID senderId) {
|
||||||
return userRepository.getReferenceById(senderId);
|
return userRepository.getReferenceById(senderId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package ru.mtusi.messenger.validation;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import ru.mtusi.messenger.dto.ChatDTO;
|
||||||
|
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||||
|
import ru.mtusi.messenger.exception.NotFoundException;
|
||||||
|
import ru.mtusi.messenger.model.User;
|
||||||
|
import ru.mtusi.messenger.service.UserService;
|
||||||
|
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChatValidator {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public Set<User> validateCreate(UUID caller, ChatDTO chatDTO) {
|
||||||
|
List<UUID> memberIds = chatDTO.getMemberIds();
|
||||||
|
String title = chatDTO.getTitle();
|
||||||
|
|
||||||
|
requireNotBlank(title, "Title must not be blank");
|
||||||
|
requireNonEmpty(memberIds, "member_ids must not be empty");
|
||||||
|
requireNoDuplicates(memberIds, "member_ids contains duplicates");
|
||||||
|
requireContains(memberIds, caller, "Вызывающий должен быть участником");
|
||||||
|
|
||||||
|
return requireAllUsersExist(memberIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireNotBlank(String value, String message) {
|
||||||
|
if (value == null || value.trim().isEmpty()) {
|
||||||
|
throw new InvalidRequestException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireNonEmpty(List<UUID> ids, String message) {
|
||||||
|
if (ids == null || ids.isEmpty()) {
|
||||||
|
throw new InvalidRequestException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireNoDuplicates(List<UUID> ids, String message) {
|
||||||
|
Set<UUID> unique = new HashSet<>(ids);
|
||||||
|
if (unique.size() != ids.size()) {
|
||||||
|
throw new InvalidRequestException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireContains(List<UUID> ids, UUID value, String message) {
|
||||||
|
if (!ids.contains(value)) {
|
||||||
|
throw new InvalidRequestException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<User> requireAllUsersExist(List<UUID> ids) {
|
||||||
|
try {
|
||||||
|
return userService.requireUsers(ids);
|
||||||
|
} catch (NotFoundException e) {
|
||||||
|
throw new InvalidRequestException(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user