Build the chat list with batch queries instead of five queries per chat

Interlocutors, posts, last messages (one subquery by max id) and unread counts
(one GROUP BY) are loaded per list. The last message is now picked by id:
createdAt is written in the sender's time zone and is not monotonic between
users in different zones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 01:38:33 +03:00
parent 2f52e6df70
commit 85a2773f60
3 changed files with 106 additions and 30 deletions

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.repository;
import com.krylov.refound.entity.Message;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
@@ -14,7 +15,18 @@ public interface MessageRepository extends JpaRepository<Message, Long> {
Page<Message> findByChatIdOrderByCreatedAtDesc(Long chatId, Pageable pageable);
Optional<Message> findFirstByChatIdOrderByCreatedAtDesc(Long chatId);
/**
* Последнее сообщение каждого чата. «Последнее» — по id: createdAt пишется в
* часовом поясе отправителя, и у собеседников из разных поясов не монотонен.
*/
@Query("SELECT m FROM Message m WHERE m.id IN "
+ "(SELECT MAX(m2.id) FROM Message m2 WHERE m2.chatId IN :chatIds GROUP BY m2.chatId)")
List<Message> findLastMessages(@Param("chatIds") Collection<Long> chatIds);
/** Непрочитанные сообщения от собеседника по каждому чату: строки (chatId, count). */
@Query("SELECT m.chatId, COUNT(m) FROM Message m WHERE m.chatId IN :chatIds "
+ "AND m.isRead = false AND m.senderId <> :userId GROUP BY m.chatId")
List<Object[]> countUnreadByChat(@Param("chatIds") Collection<Long> chatIds, @Param("userId") Long userId);
long countByChatIdAndIsReadFalseAndSenderIdNot(Long chatId, Long userId);

View File

@@ -8,6 +8,7 @@ import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Image;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.ChatRepository;
@@ -18,7 +19,10 @@ import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -104,10 +108,12 @@ public class ChatService {
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
}
return chatRepository.findAllByUserId(userId).stream()
.map(c -> {
ChatDto dto = toDto(c, userId);
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
List<Chat> chats = chatRepository.findAllByUserId(userId);
Map<Long, Chat> byId = chats.stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
return toDtos(chats, userId).stream()
.map(dto -> {
LocalDateTime created = byId.get(dto.getId()).getCreatedAt();
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : created);
})
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
.map(ChatWithActivity::dto)
@@ -224,40 +230,65 @@ public class ChatService {
}
private ChatDto toDto(Chat chat, Long currentUserId) {
Long otherUserId = chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
return toDtos(List.of(chat), currentUserId).get(0);
}
ChatDto dto = new ChatDto();
dto.setId(chat.getId());
dto.setOtherUserId(otherUserId);
dto.setPostId(chat.getPostId());
/**
* Собирает ChatDto для списка чатов фиксированным числом запросов (собеседники,
* объявления, последние сообщения, непрочитанные), а не пятью запросами на чат.
*/
private List<ChatDto> toDtos(List<Chat> chats, Long currentUserId) {
if (chats.isEmpty()) {
return List.of();
}
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
Map<Long, User> users = userRepository.findAllById(chats.stream()
.map(chat -> otherUserId(chat, currentUserId)).distinct().toList()).stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
Map<Long, Post> posts = postRepository.findAllById(chats.stream()
.map(Chat::getPostId).filter(Objects::nonNull).distinct().toList()).stream()
.collect(Collectors.toMap(Post::getId, Function.identity()));
Map<Long, Message> lastMessages = messageRepository.findLastMessages(chatIds).stream()
.collect(Collectors.toMap(Message::getChatId, Function.identity()));
Map<Long, Long> unread = new HashMap<>();
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
}
userRepository.findById(otherUserId).ifPresent(user -> {
dto.setOtherUserName(user.getName() + " " + user.getLastName());
dto.setOtherUserAvatar(user.getAvatarUrl());
});
return chats.stream().map(chat -> {
Long otherUserId = otherUserId(chat, currentUserId);
ChatDto dto = new ChatDto();
dto.setId(chat.getId());
dto.setOtherUserId(otherUserId);
dto.setPostId(chat.getPostId());
if (chat.getPostId() != null) {
postRepository.findById(chat.getPostId()).ifPresent(post -> {
User other = users.get(otherUserId);
if (other != null) {
dto.setOtherUserName(other.getName() + " " + other.getLastName());
dto.setOtherUserAvatar(other.getAvatarUrl());
}
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
if (post != null) {
ChatPostDto postDto = new ChatPostDto();
postDto.setId(post.getId());
postDto.setTitle(post.getTitle());
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
dto.setPost(postDto);
});
}
}
// без N+1: берём только последнее сообщение, а не всю историю
messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId())
.ifPresent(last -> {
dto.setLastMessage(last.getContent());
dto.setLastMessageAt(last.getCreatedAt());
});
Message last = lastMessages.get(chat.getId());
if (last != null) {
dto.setLastMessage(last.getContent());
dto.setLastMessageAt(last.getCreatedAt());
}
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
return dto;
}).toList();
}
dto.setUnreadCount(
messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId)
);
return dto;
private static Long otherUserId(Chat chat, Long currentUserId) {
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
}
private MessageDto toMessageDto(Message m) {

View File

@@ -45,7 +45,6 @@ class ChatServiceTest {
userRepository, postRepository);
when(userRepository.existsById(anyLong())).thenReturn(true);
when(messageRepository.findFirstByChatIdOrderByCreatedAtDesc(any())).thenReturn(Optional.empty());
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
Chat chat = inv.getArgument(0);
@@ -112,4 +111,38 @@ class ChatServiceTest {
.isInstanceOf(ApiException.class)
.hasMessageContaining("самим собой");
}
@Test
void chatListIsBuiltWithBatchQueries() {
Chat first = new Chat();
first.setId(1L);
first.setUserOneId(14L);
first.setUserTwoId(19L);
Chat second = new Chat();
second.setId(2L);
second.setUserOneId(14L);
second.setUserTwoId(20L);
when(chatRepository.findAllByUserId(14L)).thenReturn(List.of(first, second));
User bob = new User();
bob.setId(19L);
bob.setName("Боб");
bob.setLastName("Иванов");
when(userRepository.findAllById(any())).thenReturn(List.of(bob));
Message last = new Message();
last.setChatId(2L);
last.setContent("последнее");
last.setCreatedAt(java.time.LocalDateTime.now());
when(messageRepository.findLastMessages(any())).thenReturn(List.of(last));
when(messageRepository.countUnreadByChat(any(), org.mockito.ArgumentMatchers.eq(14L)))
.thenReturn(List.<Object[]>of(new Object[] {2L, 3L}));
List<ChatDto> chats = chatService.getUserChats(14L);
// Чат со свежим сообщением — первым
assertThat(chats).extracting(ChatDto::getId).containsExactly(2L, 1L);
assertThat(chats.get(0).getLastMessage()).isEqualTo("последнее");
assertThat(chats.get(0).getUnreadCount()).isEqualTo(3L);
assertThat(chats.get(1).getOtherUserName()).isEqualTo("Боб Иванов");
org.mockito.Mockito.verify(userRepository, org.mockito.Mockito.times(1)).findAllById(any());
}
}