Files
mtusi2026lab7/src/main/java/ru/mtusi/messenger/service/MessageService.java
T

166 lines
6.8 KiB
Java

package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.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.ConflictException;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.exception.PayloadTooLargeException;
import ru.mtusi.messenger.mapper.MessageMapper;
import ru.mtusi.messenger.model.AttachmentStatus;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.Message;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.AttachmentRepository;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.repository.MessageRepository;
import ru.mtusi.messenger.repository.UserRepository;
import ru.mtusi.messenger.util.CursorCodec;
import java.util.List;
import java.util.UUID;
@Service
@Slf4j
@RequiredArgsConstructor
public class MessageService {
private final AttachmentRepository attachments;
private final IdempotencyService idempotencyService;
private final MessageRepository messageRepository;
private final ChatRepository chatRepository;
private final ChatService chatService;
private final UserRepository userRepository;
private final MessageMapper messageMapper;
private final AppProperties appProperties;
@Transactional
public MessageDTO createMessage(
UUID senderId, UUID chatId, CreateMessageDTO dto, String idempotencyKey) {
Chat chat = chatService.getChat(senderId, chatId);
return idempotencyService.execute(
senderId,
"POST",
chatId,
idempotencyKey,
dto,
MessageDTO.class,
() -> doCreate(senderId, chatId, dto, chat));
}
private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) {
validateCreate(chatId, dto);
requireHistoryCapacity(chatId);
User sender = userRepository.getReferenceById(senderId);
Message message = buildMessage(dto, sender, chat);
try {
message = messageRepository.saveAndFlush(message);
} catch (DataIntegrityViolationException e) {
throw new NotFoundException("Cannot create message: referenced entity is missing");
}
log.info("Created message id={} in chat={}", message.getId(), chatId);
return messageMapper.toMessageDTO(message);
}
private void validateCreate(UUID chatId, CreateMessageDTO dto) {
if (dto.getText() == null
|| (dto.getText().isBlank()
&& (dto.getAttachmentIds() == null || dto.getAttachmentIds().isEmpty()))) {
throw new InvalidRequestException("Empty text");
}
var ids = dto.getAttachmentIds();
if (ids == null
|| ids.size() > 10
|| ids.contains(null)
|| new java.util.HashSet<>(ids).size() != ids.size()
|| dto.getText().codePointCount(0, dto.getText().length()) > 4000) {
throw new InvalidRequestException("Invalid message");
}
validateAttachments(chatId, ids);
}
private void validateAttachments(UUID chatId, List<UUID> ids) {
for (UUID id : ids.stream().sorted().toList()) {
var attachment =
attachments
.findForMessage(id)
.filter(a -> a.getChat().getId().equals(chatId))
.orElseThrow(() -> new NotFoundException("Attachment not found"));
if ((attachment.getStatus() == AttachmentStatus.FAILED
|| attachment.getStatus() == AttachmentStatus.BROKEN)) {
throw new ConflictException("Attachment not ready");
}
}
}
private void requireHistoryCapacity(UUID chatId) {
chatRepository
.findForMessageCreation(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
if (messageRepository.countByChatId(chatId) >= appProperties.maxMessagesPerChat()) {
throw new PayloadTooLargeException("Chat history limit reached");
}
}
private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) {
Message message = messageMapper.toMessage(createMessageDTO);
message.setChat(chat);
message.setSender(sender);
return message;
}
@Transactional(readOnly = true)
public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) {
int size = (limit == null) ? 50 : limit;
chatService.getChatDTO(userId, chatId);
CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId);
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);
}
private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) {
if (cursor == null) return null;
if (cursor.isEmpty()) throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId))
throw new InvalidRequestException("Cursor from another chat");
return decoded;
}
private MessagePageDTO buildPage(List<Message> rows, int size, UUID chatId) {
List<MessageDTO> items =
rows.stream().limit(size).map(messageMapper::toMessageDTO).toList();
MessagePageDTO page = new MessagePageDTO();
page.setItems(items);
page.setNextCursor(buildNextCursor(rows, size, chatId));
return page;
}
private String buildNextCursor(List<Message> rows, int size, UUID chatId) {
if (rows.size() <= size) {
return null;
}
Message last = rows.get(size - 1);
return CursorCodec.encode(
chatId, new CursorCodec.PageBoundary(last.getCreatedAt(), last.getId()));
}
}