Исправление валидации и обеспечение консинстентности кэша после падения редис
Skeleton contracts / contracts (pull_request) Canceled after 0s

Исправление security context утечки
This commit is contained in:
2026-10-10 08:33:01 +03:00
parent 30cf79907b
commit d496190646
15 changed files with 283 additions and 137 deletions
@@ -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.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;
@@ -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.serializer.JacksonJsonRedisSerializer;
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.SessionProperties;
import ru.mtusi.messenger.service.SessionService;
@@ -34,6 +32,7 @@ import ru.mtusi.messenger.service.SessionService;
public class RedisConfig implements CachingConfigurer {
private final SessionProperties sessionProperties;
private final RedisProperties redisProperties;
private final CacheHealthTracker cacheHealthTracker;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
@@ -83,19 +82,23 @@ public class RedisConfig implements CachingConfigurer {
return new CacheErrorHandler() {
@Override
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
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
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
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.configurers.AbstractHttpConfigurer;
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.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@@ -29,7 +29,7 @@ public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
@Bean
@@ -3,9 +3,6 @@ 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;
import java.util.Set;
import java.util.UUID;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
@@ -13,6 +10,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import java.util.*;
import jakarta.annotation.Generated;
import org.hibernate.validator.constraints.CodePointLength;
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0")
public class ChatDTO {
@@ -22,7 +20,7 @@ public class ChatDTO {
private String title;
@Valid
private Set<UUID> memberIds = new LinkedHashSet<>();
private List<UUID> memberIds = new ArrayList<>();
private Instant createdAt;
@@ -33,7 +31,7 @@ public class ChatDTO {
/**
* Constructor with only required parameters
*/
public ChatDTO(String title, Set<UUID> memberIds) {
public ChatDTO(String title, List<UUID> memberIds) {
this.title = title;
this.memberIds = memberIds;
}
@@ -59,7 +57,8 @@ public class ChatDTO {
return this;
}
@NotNull @Size(min = 1, max = 100)
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("title")
public String getTitle() {
@@ -70,14 +69,14 @@ public class ChatDTO {
this.title = title;
}
public ChatDTO memberIds(Set<UUID> memberIds) {
public ChatDTO memberIds(List<UUID> memberIds) {
this.memberIds = memberIds;
return this;
}
public ChatDTO addMemberIdsItem(UUID memberIdsItem) {
if (this.memberIds == null) {
this.memberIds = new LinkedHashSet<>();
this.memberIds = new ArrayList<>();
}
this.memberIds.add(memberIdsItem);
return this;
@@ -86,12 +85,11 @@ public class ChatDTO {
@NotNull @Valid @Size(min = 1, max = 100)
@Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("member_ids")
public Set<UUID> getMemberIds() {
public List<UUID> getMemberIds() {
return memberIds;
}
@JsonDeserialize(as = LinkedHashSet.class)
public void setMemberIds(Set<UUID> memberIds) {
public void setMemberIds(List<UUID> memberIds) {
this.memberIds = memberIds;
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.CodePointLength;
import java.util.Objects;
@@ -19,7 +20,8 @@ public class CreateMessageDTO {
return this;
}
@NotNull @Size(min = 1, max = 4000)
@NotNull
@CodePointLength(min = 1, max = 4000)
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("text")
public String getText() { return text; }
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import io.swagger.v3.oas.annotations.media.Schema;
import org.hibernate.validator.constraints.CodePointLength;
import java.time.Instant;
import java.util.UUID;
@@ -109,7 +110,8 @@ public class MessageDTO {
* Get text
* @return text
*/
@NotNull @Size(min = 1, max = 4000)
@NotNull
@CodePointLength(min = 1, max = 4000)
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("text")
public String getText() {
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import io.swagger.v3.oas.annotations.media.Schema;
import org.hibernate.validator.constraints.CodePointLength;
import java.util.*;
@@ -83,7 +84,8 @@ public class UserDTO {
* Get displayName
* @return displayName
*/
@NotNull @Size(min = 1, max = 100)
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("display_name")
public String getDisplayName() {
@@ -103,7 +105,8 @@ public class UserDTO {
* Get password
* @return password
*/
@NotNull @Size(min = 12, max = 128)
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("password")
public String getPassword() {
@@ -7,17 +7,17 @@ import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.model.Chat;
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.UUID;
import java.util.stream.Collectors;
@Mapper(componentModel = "spring")
public interface ChatMapper {
@Mapping(target = "id", ignore = true)
@Mapping(target = "createdAt", ignore = true)
@Mapping(target = "members", ignore = true) // ← заполнит ChatService
@Mapping(target = "members", ignore = true)
@Mapping(target = "messages", ignore = true)
Chat toChat(ChatDTO dto);
@@ -25,10 +25,10 @@ public interface ChatMapper {
ChatDTO toChatDto(Chat chat);
@Named("usersToIds")
default Set<UUID> usersToIds(Set<User> users) {
if (users == null) return new LinkedHashSet<>();
return users.stream()
.map(User::getId)
.collect(Collectors.toCollection(LinkedHashSet::new));
default List<UUID> usersToIds(Set<User> users) {
if (users == null) return new ArrayList<>();
List<UUID> ids = new ArrayList<>(users.size());
for (User u : users) ids.add(u.getId());
return ids;
}
}
@@ -5,10 +5,10 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.web.filter.OncePerRequestFilter;
@@ -24,16 +24,22 @@ public class SessionAuthenticationFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String token = bearerTokenResolver.resolve(request);
try {
String token = bearerTokenResolver.resolve(request);
if (token != null && !token.isBlank()) {
try {
Authentication auth = authenticationManager.authenticate(
new SessionAuthenticationToken(token));
SecurityContextHolder.getContext().setAuthentication(auth);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
} catch (AuthenticationException e) {
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.User;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.validation.ChatValidator;
import ru.mtusi.messenger.util.CursorCodec;
import java.util.*;
@@ -23,55 +24,74 @@ import java.util.*;
@RequiredArgsConstructor
public class ChatService {
private final ChatMapper chatMapper;
private final UserService userService;
private final ChatValidator chatValidator;
private final ChatRepository chatRepository;
@Transactional
public ChatDTO createChat(UUID caller , ChatDTO chatDTO) {
Set<User> members = validateCreate(caller, chatDTO);
public ChatDTO createChat(UUID caller, ChatDTO chatDTO) {
Set<User> members = chatValidator.validateCreate(caller, chatDTO);
Chat chat = buildChat(chatDTO, members);
try {
chat = chatRepository.saveAndFlush(chat);
} catch (DataIntegrityViolationException e) {
throw new NotFoundException("Cannot create chat: referenced entity is missing");
}
chat = persistChat(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) {
Chat chat = chatMapper.toChat(chatDTO);
chat.setMembers(members);
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)
public ChatDTO getChatDTO(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");
}
Chat chat = requireChatForMember(caller, chatId);
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)
public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) {
int size = (limit == null) ? 50 : limit;
int size = resolveSize(limit);
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
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));
List<Chat> rows = loadChatPage(userId, decoded, 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) {
if (cursor == null || cursor.isBlank()) {
return null;
@@ -106,15 +126,4 @@ 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,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.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.properties.SessionProperties;
import ru.mtusi.messenger.dto.SessionDTO;
@@ -20,22 +17,17 @@ import ru.mtusi.messenger.util.TokenHasher;
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;
private final SessionCacheService sessionCacheService;
@Transactional
public SessionDTO createSession(UserDTO userDTO) {
@@ -44,43 +36,46 @@ public class SessionService {
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(tokenHasher.sha256(token))
.filter(x -> x.getRevokedAt() == null)
.filter(x -> x.getExpiresAt().isAfter(Instant.now()))
.orElseThrow(() -> new UnauthorizedException("Invalid or expired session"));
return new SessionRecord(s.getId(), s.getUserId());
sessionCacheService.dropCacheIfStale();
String hex = tokenHasher.hash(token);
SessionRecord record = sessionCacheService.lookupByHash(hex);
requireNotExpired(record, hex);
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
public void revoke(UUID sessionId) {
sessionRepository.findById(sessionId).ifPresent(s -> {
if (s.getRevokedAt() == null) {
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());
}
});
});
sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict);
}
private void markRevokedAndEvict(Session session) {
if (session.getRevokedAt() == null) {
session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
}
sessionCacheService.evict(tokenHasher.hash(session.getTokenHash()));
}
private Session buildSession(UserDTO userDTO, String token) {
Session session = new Session();
session.setUserId(userDTO.getId());
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;
}
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.repository.UserRepository;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@@ -28,10 +29,11 @@ public class UserService {
private final UserRepository userRepository;
@Transactional
public Set<User> requireUsers(Set<UUID> ids) {
Set<User> users = userRepository.findAllByIdForShare(ids);
if (users.size() != ids.size()) {
throw new NotFoundException("Users not found: " + findMissing(ids, users));
public Set<User> requireUsers(Collection<UUID> ids) {
Set<UUID> uniqueIds = new HashSet<>(ids);
Set<User> users = userRepository.findAllByIdForShare(uniqueIds);
if (users.size() != uniqueIds.size()) {
throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users));
}
return users;
}
@@ -78,4 +80,4 @@ public class UserService {
public User getReferenceUserById(UUID 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());
}
}
}