Миграции балансировка запросов идемпотентность graceful shutdown readines

This commit is contained in:
Dmitry
2026-10-27 21:33:13 +03:00
parent 6ddf0602ae
commit 36cbd70d37
13 changed files with 199 additions and 12 deletions
@@ -6,8 +6,11 @@ import org.example.dto.create.CreateMessageDto;
import org.example.dto.update.UpdateMessageDto;
import org.example.exception.ForbiddenException;
import org.example.exception.NotFoundException;
import org.example.model.IdempotencyKey;
import org.example.model.Message;
import org.example.repository.IdempotencyKeyRepository;
import org.example.repository.MessageRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@@ -15,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
@@ -22,23 +26,54 @@ import java.util.UUID;
public class MessageService {
private final MessageRepository messageRepository;
private final IdempotencyKeyRepository idempotencyKeyRepository;
private final ChatService chatService;
@Transactional
public Message sendMessage(UUID chatId, UUID senderId, CreateMessageDto messageObject) {
public Message sendMessage(
UUID chatId,
UUID senderId,
CreateMessageDto messageObject,
String idempotencyKey){
chatService.requireMember(chatId);
if (!chatService.isMember(chatId, senderId)){
throw new ForbiddenException("Пользователь не является участником чата");
}
String key = idempotencyKey.trim();
Optional<IdempotencyKey> exists = idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
if (exists.isPresent()){
return messageRepository.findById(exists.get().getMessageId())
.orElseThrow(() -> new IllegalArgumentException("Сообщения нет"));
}
Message message = Message.builder()
.chatId(chatId)
.senderId(senderId)
.text(messageObject.getText())
.createdAt(Instant.now())
.build();
message = messageRepository.save(message);
return messageRepository.save(message);
try {
idempotencyKeyRepository.saveAndFlush(
IdempotencyKey.builder()
.userId(senderId)
.chatId(chatId)
.idempotencyKey(key)
.messageId(message.getId())
.build()
);
} catch (DataIntegrityViolationException e){
IdempotencyKey rec = idempotencyKeyRepository
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
.orElseThrow(() -> e);
return messageRepository.findById(rec.getUserId())
.orElseThrow(()-> e);
}
return message;
}