From 96a4cd90ce21999ac26276607480376bc285c4b0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:28:11 -0800 Subject: [PATCH 01/10] Reactions: keys, table and repository --- .../open/spring/mvc/reactions/ChatType.java | 7 +++ .../spring/mvc/reactions/MessageReaction.java | 57 +++++++++++++++++++ .../MessageReactionJpaRepository.java | 18 ++++++ .../MessageReactionTableInitializer.java | 45 +++++++++++++++ .../open/spring/mvc/reactions/Reaction.java | 34 +++++++++++ .../MessageReactionTableInitializerTest.java | 53 +++++++++++++++++ .../spring/mvc/reactions/ReactionTest.java | 34 +++++++++++ 7 files changed, 248 insertions(+) create mode 100644 src/main/java/com/open/spring/mvc/reactions/ChatType.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReaction.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/Reaction.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/ReactionTest.java diff --git a/src/main/java/com/open/spring/mvc/reactions/ChatType.java b/src/main/java/com/open/spring/mvc/reactions/ChatType.java new file mode 100644 index 00000000..9e8583ed --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/ChatType.java @@ -0,0 +1,7 @@ +package com.open.spring.mvc.reactions; + +/** The kind of chat a reacted-to message is in: a DM conversation or a group chat. */ +public enum ChatType { + DM, + GROUP +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java new file mode 100644 index 00000000..13cdfc27 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java @@ -0,0 +1,57 @@ +package com.open.spring.mvc.reactions; + +import java.io.Serializable; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * One person's reaction to one message. The whole row is its key, so a person leaves each + * reaction at most once on a message. DM messages are rows and group messages live in S3, + * so a message is named by its chat and its id as text. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "message_reaction") +public class MessageReaction { + + @EmbeddedId + private Key key; + + /** Which chat, which message, who, and which emoji. */ + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Key implements Serializable { + + @Enumerated(EnumType.STRING) + @Column(name = "chat_type", length = 8) + private ChatType chatType; + + /** The DM conversation's id or the group's id. */ + @Column(name = "chat_id") + private Long chatId; + + /** A DM message's numeric id as text, or a group message's UUID. */ + @Column(name = "message_id", length = 64) + private String messageId; + + @Column(name = "person_id") + private Long personId; + + @Enumerated(EnumType.STRING) + @Column(name = "reaction", length = 16) + private Reaction reaction; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java new file mode 100644 index 00000000..0a8fb8c7 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -0,0 +1,18 @@ +package com.open.spring.mvc.reactions; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +/** Reactions, read by chat or by message. */ +public interface MessageReactionJpaRepository extends JpaRepository { + + /** Every reaction in one chat. */ + List findByKeyChatTypeAndKeyChatId(ChatType chatType, Long chatId); + + /** Every reaction on one message. */ + List findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + + /** Removes every reaction on one message, as when the message is deleted. */ + void deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java new file mode 100644 index 00000000..ba70d3e5 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -0,0 +1,45 @@ +package com.open.spring.mvc.reactions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; + +/** + * Creates message_reaction for databases run with ddl-auto=none, and leaves an existing one + * as it is. The primary key is all five columns: that keeps a person to one of each reaction + * on a message, and it needs no auto-increment, so one statement in unquoted lowercase with + * plain types runs on both SQLite and MySQL. + */ +@Component +@RequiredArgsConstructor +public class MessageReactionTableInitializer { + + static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS message_reaction (" + + "chat_type varchar(8) NOT NULL, " + + "chat_id bigint NOT NULL, " + + "message_id varchar(64) NOT NULL, " + + "person_id bigint NOT NULL, " + + "reaction varchar(16) NOT NULL, " + + "PRIMARY KEY (chat_type, chat_id, message_id, person_id, reaction))"; + + private static final Logger logger = LoggerFactory.getLogger(MessageReactionTableInitializer.class); + + private final JdbcTemplate jdbcTemplate; + + @Bean + public ApplicationRunner migrateMessageReaction() { + return args -> { + try { + jdbcTemplate.execute(CREATE_TABLE); + } catch (DataAccessException e) { + logger.warn("Could not create the message_reaction table: {}", e.getMessage()); + } + }; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/Reaction.java b/src/main/java/com/open/spring/mvc/reactions/Reaction.java new file mode 100644 index 00000000..bb778d61 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/Reaction.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import java.util.Arrays; +import java.util.Optional; + +/** + * The emoji a message can get. A row stores the enum name; routes and JSON use the lowercase + * key. Pages' Messages reactions.js lists the same keys in the same order, so change both + * together. + */ +public enum Reaction { + LIKE("like"), + LOVE("love"), + HAHA("haha"), + WOW("wow"), + SAD("sad"), + CELEBRATE("celebrate"); + + private final String key; + + Reaction(String key) { + this.key = key; + } + + /** The lowercase name a route and the page use, such as "like". */ + public String key() { + return key; + } + + /** The reaction with exactly this key, or empty for anything else, "LIKE" included. */ + public static Optional fromKey(String key) { + return Arrays.stream(values()).filter(reaction -> reaction.key.equals(key)).findFirst(); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java new file mode 100644 index 00000000..c34acaef --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -0,0 +1,53 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +/** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ +class MessageReactionTableInitializerTest { + + private static final String INSERT = "INSERT INTO message_reaction " + + "(chat_type, chat_id, message_id, person_id, reaction) VALUES (?, ?, ?, ?, ?)"; + + private SingleConnectionDataSource dataSource; + private JdbcTemplate jdbc; + + @BeforeEach + void setUp() { + dataSource = new SingleConnectionDataSource("jdbc:sqlite::memory:", true); + jdbc = new JdbcTemplate(dataSource); + } + + @AfterEach + void tearDown() { + dataSource.destroy(); + } + + @Test + void createsTheTableAndCanRunTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + @Test + void rejectsTheSameReactionTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertThrows(DataAccessException.class, () -> jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE")); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LOVE"); + + assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java new file mode 100644 index 00000000..26f259e9 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +/** + * The reaction keys are a contract with the Pages client: Messages' reactions.js lists the + * same keys in the same order, and a route's {reaction} is read with fromKey. + */ +class ReactionTest { + + @Test + void everyKeyRoundTrips() { + for (Reaction reaction : Reaction.values()) { + assertEquals(Optional.of(reaction), Reaction.fromKey(reaction.key())); + } + List keys = Arrays.stream(Reaction.values()).map(Reaction::key).toList(); + assertEquals(List.of("like", "love", "haha", "wow", "sad", "celebrate"), keys); + } + + @Test + void unknownKeysAreRefused() { + assertTrue(Reaction.fromKey(null).isEmpty()); + assertTrue(Reaction.fromKey("").isEmpty()); + assertTrue(Reaction.fromKey("LIKE").isEmpty()); + assertTrue(Reaction.fromKey("thumbsup").isEmpty()); + } +} From 8f749e9cb28e20b1202e528a154e677bc56f2ccf Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:31:18 -0800 Subject: [PATCH 02/10] Reactions: a service that saves and summarizes them --- .../mvc/reactions/MessageReactionService.java | 123 ++++++++++++++++ .../reactions/MessageReactionServiceTest.java | 133 ++++++++++++++++++ 2 files changed, 256 insertions(+) create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java new file mode 100644 index 00000000..806229c9 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -0,0 +1,123 @@ +package com.open.spring.mvc.reactions; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import lombok.RequiredArgsConstructor; + +/** + * Saves and summarizes the reactions on DM and group messages. It doesn't decide who may react + * or whether a message exists: each chat's own service checks that before calling here. + */ +@Service +@RequiredArgsConstructor +public class MessageReactionService { + + private static final Comparator BY_NAME = Comparator + .comparing((Reactor reactor) -> reactor.name() == null ? "" : reactor.name(), String.CASE_INSENSITIVE_ORDER) + .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); + + private final MessageReactionJpaRepository repository; + private final PersonJpaRepository personRepository; + + /** Someone who reacted, as the page shows them. */ + public record Reactor(String uid, String name) { + } + + /** One emoji on a message, by its lowercase key, and everyone who left it. */ + public record ReactionSummary(String reaction, List people) { + } + + /** A message's reactions after a change: the body PUT and DELETE answer with. */ + public record MessageReactions(String messageId, List reactions) { + } + + /** Adds this person's reaction. Adding one that is already there changes nothing. */ + @Transactional + public void add(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (!repository.existsById(key)) { + repository.save(new MessageReaction(key)); + } + } + + /** Removes this person's reaction. Removing one that isn't there changes nothing. */ + @Transactional + public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (repository.existsById(key)) { + repository.deleteById(key); + } + } + + /** One message's reactions, in the enum's order. */ + @Transactional(readOnly = true) + public List forMessage(ChatType type, Long chatId, String messageId) { + List rows = repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + return summarize(rows, reactorsFor(rows)); + } + + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ + @Transactional(readOnly = true) + public Map> forChat(ChatType type, Long chatId) { + List rows = repository.findByKeyChatTypeAndKeyChatId(type, chatId); + Map reactors = reactorsFor(rows); + Map> byMessage = rows.stream().collect( + Collectors.groupingBy(row -> row.getKey().getMessageId(), LinkedHashMap::new, Collectors.toList())); + Map> result = new LinkedHashMap<>(); + byMessage.forEach((messageId, messageRows) -> { + List summaries = summarize(messageRows, reactors); + if (!summaries.isEmpty()) { + result.put(messageId, summaries); + } + }); + return result; + } + + /** Removes every reaction on a message, as when the message is deleted. */ + @Transactional + public void removeAllFor(ChatType type, Long chatId, String messageId) { + repository.deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + } + + // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. + private Map reactorsFor(List rows) { + List ids = rows.stream().map(row -> row.getKey().getPersonId()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + Map reactors = new HashMap<>(); + for (Person person : personRepository.findAllById(ids)) { + reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); + } + return reactors; + } + + private List summarize(List rows, Map reactors) { + List summaries = new ArrayList<>(); + for (Reaction reaction : Reaction.values()) { + List people = rows.stream() + .filter(row -> row.getKey().getReaction() == reaction) + .map(row -> reactors.get(row.getKey().getPersonId())) + .filter(Objects::nonNull) + .sorted(BY_NAME) + .toList(); + if (!people.isEmpty()) { + summaries.add(new ReactionSummary(reaction.key(), people)); + } + } + return summaries; + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java new file mode 100644 index 00000000..ad00a6c1 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -0,0 +1,133 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; + +/** + * Saving a reaction once, removing it safely, and the summaries both chats send: reactions in + * the enum's order, people by name, and nobody listed who no longer has an account. + */ +class MessageReactionServiceTest { + + private MessageReactionJpaRepository repository; + private PersonJpaRepository people; + private MessageReactionService service; + // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. + private Person ada; + private Person ana; + private Person ben; + + @BeforeEach + void setUp() { + repository = mock(MessageReactionJpaRepository.class); + people = mock(PersonJpaRepository.class); + service = new MessageReactionService(repository, people); + ada = person(1L, "ada", "ada"); + ana = person(2L, "ana", "Ana"); + ben = person(3L, "ben", "Ben"); + } + + @Test + void addSavesANewReactionOnce() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(true); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).save(any()); + + when(repository.existsById(key)).thenReturn(false); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).save(new MessageReaction(key)); + } + + @Test + void removeIsFineWhenNothingIsThere() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(false); + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).deleteById(any()); + + when(repository.existsById(key)).thenReturn(true); + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).deleteById(key); + } + + @Test + void summariesFollowTheTableOrderAndSortPeople() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(people.findAllById(any())).thenReturn(List.of(ben, ana, ada)); + + List summaries = service.forMessage(ChatType.DM, 7L, "42"); + + assertEquals(List.of( + new ReactionSummary("like", List.of(new Reactor("ada", "ada"), new Reactor("ana", "Ana"))), + new ReactionSummary("wow", List.of(new Reactor("ben", "Ben")))), summaries); + } + + @Test + void aPersonWhoIsGoneIsLeftOut() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); + // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. + when(people.findAllById(any())).thenReturn(List.of(ada)); + + assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + service.forMessage(ChatType.DM, 7L, "42")); + } + + @Test + void forChatKeysByMessageId() { + when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( + row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), + row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), + row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); + when(people.findAllById(any())).thenReturn(List.of(ada, ben)); + + Map> byMessage = service.forChat(ChatType.GROUP, 3L); + + // "60" is left out: its only reaction is from someone whose account is gone. + assertEquals(Map.of( + "42", List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + "57", List.of(new ReactionSummary("haha", List.of(new Reactor("ben", "Ben"))))), byMessage); + } + + @Test + void removeAllForDeletesThatMessagesReactions() { + service.removeAllFor(ChatType.GROUP, 3L, "abc"); + + verify(repository).deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.GROUP, 3L, "abc"); + } + + private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { + return new MessageReaction(new MessageReaction.Key(type, chatId, messageId, personId, reaction)); + } + + private static Person person(long id, String uid, String name) { + Person person = new Person(); + // Submitter has no id setter; the DM tests set it the same way. + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(name); + return person; + } +} From 363242fc12ee6b2da20623fda6978e00644d6321 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:34:23 -0800 Subject: [PATCH 03/10] Reactions: react to a direct message --- .../DirectMessageApiController.java | 81 +++++++ .../directmessages/DirectMessageEvent.java | 13 +- .../directmessages/DirectMessageService.java | 41 ++++ .../DirectMessageReactionTest.java | 206 ++++++++++++++++++ .../DirectMessageServiceTest.java | 4 +- 5 files changed, 343 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java index 9dab2859..889c9ed5 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java @@ -17,6 +17,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -24,6 +25,10 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,6 +51,7 @@ public class DirectMessageApiController { private final DirectMessageConversationJpaRepository conversationRepository; private final DirectMessageJpaRepository messageRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; @Data @NoArgsConstructor @@ -295,6 +301,81 @@ public ResponseEntity deleteMessage( } } + /** Every reaction in the conversation, by message id: what the page draws when it opens it. */ + @GetMapping("/conversations/{id}/reactions") + @Transactional(readOnly = true) + public ResponseEntity getReactions( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + if (!directMessageService.isParticipant(conversationOpt.get(), person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + return new ResponseEntity<>(reactionService.forChat(ChatType.DM, id), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity addReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity removeReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, false); + } + + private ResponseEntity setReaction(UserDetails userDetails, Long id, Long messageId, String key, boolean on) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + DirectMessageConversation conversation = conversationOpt.get(); + if (!directMessageService.isParticipant(conversation, person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST); + } + + try { + return new ResponseEntity<>(new MessageReactions(String.valueOf(messageId), + directMessageService.setReaction(conversation, person, messageId, reaction.get(), on)), HttpStatus.OK); + } catch (NoSuchElementException ex) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (IllegalStateException ex) { + return new ResponseEntity<>(Map.of("error", ex.getMessage()), HttpStatus.CONFLICT); + } + } + @PostMapping("/conversations/{id}/read") @Transactional public ResponseEntity markRead( diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java index b68c9c46..09b7b42f 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java @@ -1,5 +1,10 @@ package com.open.spring.mvc.directmessages; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -16,7 +21,7 @@ public class DirectMessageEvent { private Long id; private Long conversationId; - private String type; // "message" for new posts, "edited" for edits + private String type; // "message", "edited", "deleted", or "reactions" private String senderUid; private String senderName; private String senderPfp; @@ -26,4 +31,10 @@ public class DirectMessageEvent { private String sentAt; private boolean deleted; private boolean edited; + /** + * On a "reactions" frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5c910139..5abc745e 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -15,6 +15,9 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; @@ -41,6 +44,7 @@ public class DirectMessageService { private final DirectMessageReadStateJpaRepository readStateRepository; private final SimpMessagingTemplate messagingTemplate; private final PushNotificationService pushNotificationService; + private final MessageReactionService reactionService; public record UnreadSender(String uid, String name) { } @@ -222,6 +226,8 @@ public void deleteMessage(DirectMessageConversation conversation, Person request message.setDeleted(true); message.setBody(""); messageRepository.save(message); + // A tombstone shows no reactions, so none are kept for it. + reactionService.removeAllFor(ChatType.DM, conversation.getId(), String.valueOf(messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -235,6 +241,41 @@ public void deleteMessage(DirectMessageConversation conversation, Person request messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * conversation's topic with a "reactions" frame. A reaction isn't a message: nobody gets a + * phone notification and nothing becomes unread. Throws {@link NoSuchElementException} if + * the message isn't in this conversation and {@link IllegalStateException} if it was + * deleted; {@code noRollbackFor} for the reason given on {@link #editMessage}. + */ + @Transactional(noRollbackFor = {NoSuchElementException.class, IllegalStateException.class}) + public List setReaction(DirectMessageConversation conversation, + Person person, Long messageId, Reaction reaction, boolean on) { + DirectMessage message = messageRepository.findByIdAndConversation(messageId, conversation) + .orElseThrow(() -> new NoSuchElementException("Message not found")); + if (message.isDeleted()) { + throw new IllegalStateException("Message was deleted"); + } + + String key = String.valueOf(messageId); + if (on) { + reactionService.add(ChatType.DM, conversation.getId(), key, person, reaction); + } else { + reactionService.remove(ChatType.DM, conversation.getId(), key, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.DM, conversation.getId(), key); + + DirectMessageEvent event = DirectMessageEvent.builder() + .id(messageId) + .conversationId(conversation.getId()) + .type("reactions") + .reactions(reactions) + .build(); + messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); + return reactions; + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java new file mode 100644 index 00000000..a3a81b48 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -0,0 +1,206 @@ +package com.open.spring.mvc.directmessages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a direct message: only participants, never on a deleted message, broadcast as a + * "reactions" frame, and never a phone notification or a change to what is unread. + */ +class DirectMessageReactionTest { + + private DirectMessageConversationJpaRepository conversationRepository; + private DirectMessageJpaRepository messageRepository; + private DirectMessageReadStateJpaRepository readStateRepository; + private SimpMessagingTemplate messagingTemplate; + private PushNotificationService pushNotificationService; + private MessageReactionService reactionService; + private PersonJpaRepository personRepository; + private DirectMessageService service; + private DirectMessageApiController controller; + private Person alice; + private Person bob; + private DirectMessageConversation conversation; + private DirectMessage message; + private List summaries; + + @BeforeEach + void setUp() { + conversationRepository = mock(DirectMessageConversationJpaRepository.class); + messageRepository = mock(DirectMessageJpaRepository.class); + readStateRepository = mock(DirectMessageReadStateJpaRepository.class); + messagingTemplate = mock(SimpMessagingTemplate.class); + pushNotificationService = mock(PushNotificationService.class); + reactionService = mock(MessageReactionService.class); + personRepository = mock(PersonJpaRepository.class); + service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, + messagingTemplate, pushNotificationService, reactionService); + controller = new DirectMessageApiController(service, conversationRepository, messageRepository, + personRepository, reactionService); + + alice = person(1L, "alice"); + bob = person(2L, "bob"); + Person carol = person(3L, "carol"); + when(personRepository.findByUid("alice")).thenReturn(alice); + when(personRepository.findByUid("carol")).thenReturn(carol); + + conversation = new DirectMessageConversation(List.of(alice, bob)); + ReflectionTestUtils.setField(conversation, "id", 7L); + when(conversationRepository.findById(7L)).thenReturn(Optional.of(conversation)); + + message = new DirectMessage(conversation, bob, "did anyone finish the FRQ?"); + ReflectionTestUtils.setField(message, "id", 42L); + when(messageRepository.findByIdAndConversation(42L, conversation)).thenReturn(Optional.of(message)); + + summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); + when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + } + + @Test + void aReactionGoesOutAsAReactionsFrame() { + List result = service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verify(reactionService).add(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("reactions", frame.getValue().getType()); + assertEquals(42L, frame.getValue().getId()); + assertEquals(7L, frame.getValue().getConversationId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void takingAReactionBackRemovesIt() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); + + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aReactionSendsNoPushAndLeavesReadStateAlone() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verifyNoInteractions(pushNotificationService, readStateRepository); + } + + @Test + void aDeletedMessageCannotBeReactedTo() { + message.setDeleted(true); + + assertThrows(IllegalStateException.class, + () -> service.setReaction(conversation, alice, 42L, Reaction.LIKE, true)); + assertEquals(HttpStatus.CONFLICT, controller.addReaction(signedIn("alice"), 7L, 42L, "like").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aMessageFromAnotherConversationIsNotFound() { + when(messageRepository.findByIdAndConversation(99L, conversation)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, + () -> service.setReaction(conversation, alice, 99L, Reaction.LIKE, true)); + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(signedIn("alice"), 7L, 99L, "like").getStatusCode()); + } + + @Test + void anUnknownReactionIs400() { + ResponseEntity response = controller.addReaction(signedIn("alice"), 7L, 42L, "thumbsup"); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void onlyASignedInParticipantMayReactOrList() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(null, 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removeReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.getReactions(signedIn("carol"), 7L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void theRoutesAnswerWithTheMessagesReactions() { + ResponseEntity added = controller.addReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions("42", summaries), added.getBody()); + + ResponseEntity removed = controller.removeReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + + Map> byMessage = Map.of("42", summaries); + when(reactionService.forChat(ChatType.DM, 7L)).thenReturn(byMessage); + ResponseEntity listed = controller.getReactions(signedIn("alice"), 7L); + assertEquals(HttpStatus.OK, listed.getStatusCode()); + assertEquals(byMessage, listed.getBody()); + } + + @Test + void deletingAMessageRemovesItsReactions() { + service.deleteMessage(conversation, bob, 42L); + + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("message").id(1L).conversationId(7L).body("hi").build()); + String reactionsFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("reactions").id(1L).conversationId(7L).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private static UserDetails signedIn(String uid) { + return User.withUsername(uid).password("unused").build(); + } + + private static Person person(Long id, String uid) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(uid); + return person; + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java index dbde1e3e..2845cfed 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.push.PushNotificationService; import com.open.spring.mvc.push.PushSubscriptionJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; @@ -144,7 +145,8 @@ void setUp() { }), new ObjectMapper(), "", "", ""); service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, - new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService); + new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService, + org.mockito.Mockito.mock(MessageReactionService.class)); } @Test From adb17e1864cb326afea1a404b343856f507ee308 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:37:37 -0800 Subject: [PATCH 04/10] Reactions: react to a group chat message --- .../mvc/groups/GroupChatApiController.java | 70 ++++++- .../spring/mvc/groups/GroupChatEvent.java | 9 + .../mvc/groups/GroupChatRealtimeService.java | 35 ++++ .../spring/mvc/groups/GroupChatFilesTest.java | 5 +- .../mvc/groups/GroupChatReactionTest.java | 181 ++++++++++++++++++ .../mvc/groups/GroupChatRegressionTest.java | 5 +- 6 files changed, 300 insertions(+), 5 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java index 60eaaf80..c99381c1 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.regex.Pattern; import java.nio.charset.StandardCharsets; @@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -28,6 +30,10 @@ import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -42,23 +48,31 @@ public class GroupChatApiController { // short outage clears in seconds. private static final int SHARE_RETRY_AFTER_SECONDS = 5; + // A saved group message's id is a UUID (GroupChatMessage). Reactions don't read the group's + // S3 file to check that the message exists, so the id at least has to look like one. + static final Pattern MESSAGE_ID = + Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; private final GroupChatReadService readService; private final GroupsJpaRepository groupsRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; public GroupChatApiController( GroupChatService groupChatService, GroupChatRealtimeService realtimeService, GroupChatReadService readService, GroupsJpaRepository groupsRepository, - PersonJpaRepository personRepository) { + PersonJpaRepository personRepository, + MessageReactionService reactionService) { this.groupChatService = groupChatService; this.realtimeService = realtimeService; this.readService = readService; this.groupsRepository = groupsRepository; this.personRepository = personRepository; + this.reactionService = reactionService; } @Data @@ -262,6 +276,60 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.OK); } + /** + * Every reaction in the group's chat, by message id: what the page draws when it opens the + * chat. Like posting, it needs a signed-in person but not membership. + */ + @GetMapping("/{groupId}/reactions") + public ResponseEntity getReactions(@PathVariable Long groupId) { + if (currentPerson() == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(reactionService.forChat(ChatType.GROUP, groupId), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity addReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity removeReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, false); + } + + private ResponseEntity setReaction(Long groupId, String messageId, String key, boolean on) { + Person person = currentPerson(); + if (person == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>("unknown reaction", HttpStatus.BAD_REQUEST); + } + if (messageId == null || !MESSAGE_ID.matcher(messageId).matches()) { + return new ResponseEntity<>("messageId is not a message id", HttpStatus.BAD_REQUEST); + } + + List reactions = + realtimeService.setReaction(groupId, person, messageId, reaction.get(), on); + return new ResponseEntity<>(new MessageReactions(messageId, reactions), HttpStatus.OK); + } + /** * Unread counts for the signed-in member's own groups, keyed by group id. Groups * with nothing unread are left out, so an empty map means nothing is waiting. diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java index acedc9fd..00f671a3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java @@ -2,6 +2,9 @@ import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -29,4 +32,10 @@ public class GroupChatEvent { private String error; private List participants; private boolean edited; + /** + * On a reactionsServer frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d69..e29a1819 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,12 +1,17 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; @@ -23,6 +28,7 @@ public class GroupChatRealtimeService { private final GroupChatService groupChatService; private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; + private final MessageReactionService reactionService; public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); @@ -78,6 +84,7 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St public void deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -89,6 +96,34 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { broadcastToGroup(groupId, event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * group's topic with a reactionsServer frame. Reactions are kept in the database, never in + * the group's S3 message file, so a reaction can't change or drop a message. + */ + public List setReaction( + Long groupId, Person person, String messageId, Reaction reaction, boolean on) { + getGroupOrThrow(groupId); + if (on) { + reactionService.add(ChatType.GROUP, groupId, messageId, person, reaction); + } else { + reactionService.remove(ChatType.GROUP, groupId, messageId, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.GROUP, groupId, messageId); + + GroupChatEvent event = GroupChatEvent.builder() + .context("reactionsServer") + .groupId(groupId) + .messageId(messageId) + .reactions(reactions) + .date(Instant.now().toString()) + .build(); + + broadcastToGroup(groupId, event); + return reactions; + } + /** * Stores a shared file and tells the group's topic about it. The frame names the file and * its size but carries no bytes: a big file sent to every member's socket could overflow diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1f..e4f83259 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -40,6 +40,7 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -104,10 +105,10 @@ private void useStorage(InMemoryStorage store) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); + GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging, mock(MessageReactionService.class)); GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = new Groups(); group.setName("CSA"); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java new file mode 100644 index 00000000..e32cfd6f --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -0,0 +1,181 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a group chat message: signed in, a real message id, broadcast as a + * reactionsServer frame, and never a read or write of the group's S3 message file. + */ +class GroupChatReactionTest { + + private static final String MESSAGE_ID = "3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10"; + + private S3FileHandler storage; + private GroupChatService chat; + private SimpMessagingTemplate messaging; + private MessageReactionService reactionService; + private GroupChatRealtimeService realtime; + private GroupChatApiController controller; + private Person ada; + private List summaries; + + @BeforeEach + void setUp() { + storage = mock(S3FileHandler.class); + chat = spy(new GroupChatService(storage, new ObjectMapper())); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + reactionService = mock(MessageReactionService.class); + realtime = new GroupChatRealtimeService(chat, groups, messaging, reactionService); + PersonJpaRepository people = mock(PersonJpaRepository.class); + GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, reactionService); + + Groups group = spy(new Groups()); + when(group.getId()).thenReturn(3L); + group.setName("Team Three"); + when(groups.findById(3L)).thenReturn(Optional.of(group)); + + ada = new Person(); + ReflectionTestUtils.setField(ada, "id", 1L); + ada.setUid("ada"); + ada.setName("Ada"); + when(people.findByUid("ada")).thenReturn(ada); + + summaries = List.of(new ReactionSummary("love", List.of(new Reactor("ada", "Ada")))); + when(reactionService.forMessage(ChatType.GROUP, 3L, MESSAGE_ID)).thenReturn(summaries); + } + + @AfterEach + void clearAuthentication() { + SecurityContextHolder.clearContext(); + } + + @Test + void aReactionGoesOutAsAReactionsServerFrame() { + List result = realtime.setReaction(3L, ada, MESSAGE_ID, Reaction.LOVE, true); + + verify(reactionService).add(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("reactionsServer", frame.getValue().getContext()); + assertEquals(3L, frame.getValue().getGroupId()); + assertEquals(MESSAGE_ID, frame.getValue().getMessageId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void aReactionNeverTouchesTheGroupsFile() { + signIn("ada"); + + ResponseEntity added = controller.addReaction(3L, MESSAGE_ID, "love"); + ResponseEntity removed = controller.removeReaction(3L, MESSAGE_ID, "love"); + when(reactionService.forChat(ChatType.GROUP, 3L)).thenReturn(java.util.Map.of(MESSAGE_ID, summaries)); + ResponseEntity listed = controller.getReactions(3L); + + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions(MESSAGE_ID, summaries), added.getBody()); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + assertEquals(java.util.Map.of(MESSAGE_ID, summaries), listed.getBody()); + verifyNoInteractions(storage); + } + + @Test + void signedOutIs401() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.removeReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.getReactions(3L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void aBadMessageIdIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownReactionIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID, "thumbsup").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownGroupIs404() { + signIn("ada"); + + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(99L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, controller.getReactions(99L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void deletingAMessageRemovesItsReactions() { + GroupChatMessage saved = new GroupChatMessage("Ada", "ada", "hello", "2026-11-21T00:00:00Z", null); + doReturn(new ArrayList<>(List.of(saved))).when(chat).getMessages("Team Three"); + + realtime.deleteMessage(3L, saved.getId(), "ada"); + + verify(reactionService).removeAllFor(ChatType.GROUP, 3L, saved.getId()); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("sendMessageServer").groupId(3L).messageId(MESSAGE_ID).message("hi").build()); + String reactionsFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("reactionsServer").groupId(3L).messageId(MESSAGE_ID).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private void signIn(String uid) { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(uid, null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java index c310e301..021a96c7 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -30,6 +30,7 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; class GroupChatRegressionTest { private S3FileHandler storage; @@ -50,9 +51,9 @@ void setUp() { groups = mock(GroupsJpaRepository.class); readStates = mock(GroupChatReadStateJpaRepository.class); reads = new GroupChatReadService(readStates, groups, chat); - realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class)); + realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class), mock(MessageReactionService.class)); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = spy(new Groups()); when(group.getId()).thenReturn(7L); From 7eb0e3580b94729309d52d8f1db2d3e86cabe017 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:52:18 -0800 Subject: [PATCH 05/10] Reactions: document the routes and frames --- api/groups.http | 16 ++++++++++++++++ docs/group-chat-architecture.md | 18 +++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/api/groups.http b/api/groups.http index c047fa49..e888e8be 100644 --- a/api/groups.http +++ b/api/groups.http @@ -133,6 +133,22 @@ Content-Type: application/json {"filename": "notes/hello.txt", "base64Data": "Z29vZGJ5ZQ=="} +### 13g. React to a message with a Like -> 200 with {messageId, reactions}, and a reactionsServer frame on /topic/group/{id} +# Any UUID is accepted: Spring doesn't read the S3 file to check the message, and a reaction +# on a message that doesn't exist is never shown. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13h. List the chat's reactions -> 200 with {"3f2c8a8e-...": [{"reaction": "like", "people": [{uid, name}]}]} +GET {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/reactions + +### 13i. Take the Like back -> 200 with an empty reactions list +DELETE {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13j. A key that isn't one of the six is refused -> 400 +# Direct messages have the same three routes under /api/dm/conversations/{id}: GET .../reactions, +# and PUT or DELETE .../messages/{messageId}/reactions/{reaction}, for participants only. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/thumbsup + ### 14. Remove yourself from the test group -> 200 DELETE {{baseUrl}}/api/groups/{{createGroup.response.body.$.id}}/members/{{me.response.body.$.id}} diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..a961ee81 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -104,7 +104,7 @@ The client sends a `GroupChatEvent` JSON object whose `context` names the event. | `heartbeat` | `heartbeatServer` with `participants` | | | anything else | `errorServer` | `Unsupported context`. | -Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. +Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. So are reactions, as `reactionsServer` with the `messageId` and the message's `reactions` after the change (see Reactions). ## REST operations @@ -135,6 +135,9 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. | | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | +| GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a UUID | Any signed-in account | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | @@ -149,6 +152,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) |---|---|---| | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | +| Reactions | SQL: `message_reaction` (`chat_type`, `chat_id`, `message_id`, `person_id`, `reaction`), created at startup by `MessageReactionTableInitializer` | Shared with direct messages (`chat_type` is `DM` or `GROUP`). All five columns are the primary key, so a person leaves each reaction once on a message. Never stored in the group's S3 file. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | | Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | @@ -158,11 +162,22 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **Every new message rewrites the whole file**, read then write, with no lock. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +## Reactions + +People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. + +- A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a UUID, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. +- Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. +- A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. +- `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. + ## Testing - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. +- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, and the table's primary key on SQLite. ## Known issues @@ -180,5 +195,6 @@ These were each reproduced against a local server built from `master` on 2026-10 - Keep routes, event `context` names and JSON field names stable: the course site's chat pages depend on them. Change them together with the Pages client. - New tables need a `CREATE TABLE IF NOT EXISTS` that runs at startup, because Hibernate runs with `ddl-auto=none`. +- Reaction keys change in `Reaction` and in Pages' Messages `reactions.js` together. - Anything that needs to know who is sending must work over both REST and the WebSocket, or send through REST. - Update this guide and `api/groups.http` when routes, events or storage change. `README.md` and `AGENTS.md` link here. From 1b7fb8da5cc1f53fa9f9d8937c80c5d0db58c9a1 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:03:10 -0800 Subject: [PATCH 06/10] Reactions: say who may make the six reaction requests PermissionsPolicyTest checks permissions.json against every request the controllers answer. The reaction routes for direct messages and group chats go with the other /api/dm and /api/groups/chat requests: any signed-in admin, student, teacher or user, as the filter chain answers today. --- src/main/resources/data/permissions.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/resources/data/permissions.json b/src/main/resources/data/permissions.json index 579ed3f9..607f05ef 100644 --- a/src/main/resources/data/permissions.json +++ b/src/main/resources/data/permissions.json @@ -476,6 +476,9 @@ "POST /api/dm/conversations/{id}/messages", "DELETE /api/dm/conversations/{id}/messages/{messageId}", "PATCH /api/dm/conversations/{id}/messages/{messageId}", + "DELETE /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "PUT /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "GET /api/dm/conversations/{id}/reactions", "POST /api/dm/conversations/{id}/read", "GET /api/dm/search", "GET /api/dm/unread", @@ -531,6 +534,9 @@ "POST /api/groups/chat/{groupId}/messages", "DELETE /api/groups/chat/{groupId}/messages/{messageId}", "PATCH /api/groups/chat/{groupId}/messages/{messageId}", + "DELETE /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "PUT /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "GET /api/groups/chat/{groupId}/reactions", "POST /api/groups/chat/{groupId}/read", "PUT /api/groups/class-memberships", "GET /api/groups/person/{personId}", From 5e000006b0411cd629b98c40c004516b771862a0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:34:46 -0800 Subject: [PATCH 07/10] Reactions: one-statement deletes, reactor names in one query, lowercase group ids A remove read the row and then deleted it, so a second remove at the same moment could fail. Removing one reaction and clearing a deleted message's reactions are now single delete statements. The names of the people who reacted come from one query for id, uid and name, instead of whole Person rows that also loaded each person's eager links. A group message id has to be a lowercase UUID, like the ids Spring saves, so an uppercase copy can't match some lookups and miss others on MySQL. --- docs/group-chat-architecture.md | 4 +- .../mvc/groups/GroupChatApiController.java | 7 +-- .../MessageReactionJpaRepository.java | 38 ++++++++++++++- .../mvc/reactions/MessageReactionService.java | 11 ++--- .../mvc/groups/GroupChatReactionTest.java | 2 + .../reactions/MessageReactionServiceTest.java | 47 ++++++++++++------- 6 files changed, 78 insertions(+), 31 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a961ee81..9e6be786 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -136,7 +136,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | | GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | -| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a UUID | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a lowercase UUID | Any signed-in account | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | @@ -167,7 +167,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. - A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. -- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a UUID, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. - Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. - A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. - `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java index c99381c1..5ef0f6fb 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -48,10 +48,11 @@ public class GroupChatApiController { // short outage clears in seconds. private static final int SHARE_RETRY_AFTER_SECONDS = 5; - // A saved group message's id is a UUID (GroupChatMessage). Reactions don't read the group's - // S3 file to check that the message exists, so the id at least has to look like one. + // A saved group message's id is a UUID (GroupChatMessage), written in lowercase. Reactions + // don't read the group's S3 file to check that the message exists, so the id at least has to + // look like one; an uppercase copy would match some lookups and not others on MySQL. static final Pattern MESSAGE_ID = - Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java index 0a8fb8c7..b920148d 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -1,8 +1,12 @@ package com.open.spring.mvc.reactions; +import java.util.Collection; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; /** Reactions, read by chat or by message. */ public interface MessageReactionJpaRepository extends JpaRepository { @@ -13,6 +17,36 @@ public interface MessageReactionJpaRepository extends JpaRepository findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); - /** Removes every reaction on one message, as when the message is deleted. */ - void deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + /** + * Removes one person's reaction in one statement. Reading the row first and then deleting it + * let a second remove at the same moment fail; a statement that deletes 0 rows doesn't. + */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId and r.key.personId = :personId and r.key.reaction = :reaction") + int deleteOne(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, @Param("messageId") String messageId, + @Param("personId") Long personId, @Param("reaction") Reaction reaction); + + /** Removes every reaction on one message in one statement, as when the message is deleted. */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId") + int deleteAllOnMessage(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, + @Param("messageId") String messageId); + + /** + * The uid and name of each person who reacted, in one query. Loading whole Person rows + * would also load each one's eager links, several queries per person. + */ + @Query("select p.id as id, p.uid as uid, p.name as name from Person p where p.id in :ids") + List findReactorNames(@Param("ids") Collection ids); + + /** A person who reacted, as far as a reaction needs to know them. */ + interface ReactorName { + Long getId(); + + String getUid(); + + String getName(); + } } diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java index 806229c9..68224e38 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -13,7 +13,6 @@ import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; -import com.open.spring.mvc.person.PersonJpaRepository; import lombok.RequiredArgsConstructor; @@ -30,7 +29,6 @@ public class MessageReactionService { .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); private final MessageReactionJpaRepository repository; - private final PersonJpaRepository personRepository; /** Someone who reacted, as the page shows them. */ public record Reactor(String uid, String name) { @@ -56,10 +54,7 @@ public void add(ChatType type, Long chatId, String messageId, Person person, Rea /** Removes this person's reaction. Removing one that isn't there changes nothing. */ @Transactional public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { - MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); - if (repository.existsById(key)) { - repository.deleteById(key); - } + repository.deleteOne(type, chatId, messageId, person.getId(), reaction); } /** One message's reactions, in the enum's order. */ @@ -89,7 +84,7 @@ public Map> forChat(ChatType type, Long chatId) { /** Removes every reaction on a message, as when the message is deleted. */ @Transactional public void removeAllFor(ChatType type, Long chatId, String messageId) { - repository.deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + repository.deleteAllOnMessage(type, chatId, messageId); } // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. @@ -99,7 +94,7 @@ private Map reactorsFor(List rows) { return Map.of(); } Map reactors = new HashMap<>(); - for (Person person : personRepository.findAllById(ids)) { + for (MessageReactionJpaRepository.ReactorName person : repository.findReactorNames(ids)) { reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); } return reactors; diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java index e32cfd6f..912fb128 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -133,6 +133,8 @@ void aBadMessageIdIs400() { assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + // Saved ids are lowercase; an uppercase one would match some lookups and not others on MySQL. + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID.toUpperCase(), "love").getStatusCode()); verify(reactionService, never()).add(any(), any(), any(), any(), any()); } diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java index ad00a6c1..4f35ec82 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -15,7 +15,6 @@ import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; -import com.open.spring.mvc.person.PersonJpaRepository; import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; import com.open.spring.mvc.reactions.MessageReactionService.Reactor; @@ -26,7 +25,6 @@ class MessageReactionServiceTest { private MessageReactionJpaRepository repository; - private PersonJpaRepository people; private MessageReactionService service; // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. private Person ada; @@ -36,8 +34,7 @@ class MessageReactionServiceTest { @BeforeEach void setUp() { repository = mock(MessageReactionJpaRepository.class); - people = mock(PersonJpaRepository.class); - service = new MessageReactionService(repository, people); + service = new MessageReactionService(repository); ada = person(1L, "ada", "ada"); ana = person(2L, "ana", "Ana"); ben = person(3L, "ben", "Ben"); @@ -56,15 +53,13 @@ void addSavesANewReactionOnce() { } @Test - void removeIsFineWhenNothingIsThere() { - MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); - when(repository.existsById(key)).thenReturn(false); + void removeIsOneDeleteStatement() { + // Read-then-delete let two removes at once fail the second; one statement just deletes 0 rows. service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); - verify(repository, never()).deleteById(any()); - when(repository.existsById(key)).thenReturn(true); - service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); - verify(repository).deleteById(key); + verify(repository).deleteOne(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + verify(repository, never()).existsById(any()); + verify(repository, never()).deleteById(any()); } @Test @@ -73,7 +68,7 @@ void summariesFollowTheTableOrderAndSortPeople() { row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); - when(people.findAllById(any())).thenReturn(List.of(ben, ana, ada)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ben), name(ana), name(ada))); List summaries = service.forMessage(ChatType.DM, 7L, "42"); @@ -89,7 +84,7 @@ void aPersonWhoIsGoneIsLeftOut() { row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. - when(people.findAllById(any())).thenReturn(List.of(ada)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), service.forMessage(ChatType.DM, 7L, "42")); @@ -101,7 +96,7 @@ void forChatKeysByMessageId() { row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); - when(people.findAllById(any())).thenReturn(List.of(ada, ben)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada), name(ben))); Map> byMessage = service.forChat(ChatType.GROUP, 3L); @@ -112,10 +107,30 @@ void forChatKeysByMessageId() { } @Test - void removeAllForDeletesThatMessagesReactions() { + void removeAllForDeletesThatMessagesReactionsInOneStatement() { service.removeAllFor(ChatType.GROUP, 3L, "abc"); - verify(repository).deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.GROUP, 3L, "abc"); + verify(repository).deleteAllOnMessage(ChatType.GROUP, 3L, "abc"); + } + + // Reactors are read as id, uid and name only, never as whole accounts with their links. + private static MessageReactionJpaRepository.ReactorName name(Person person) { + return new MessageReactionJpaRepository.ReactorName() { + @Override + public Long getId() { + return person.getId(); + } + + @Override + public String getUid() { + return person.getUid(); + } + + @Override + public String getName() { + return person.getName(); + } + }; } private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { From c791798c610f0190b4f308cf9e2505f5e733bc7d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:59:30 -0800 Subject: [PATCH 08/10] Reactions: a DM's reactions frame goes out after the commit, read again then The frame was sent inside the change's transaction with the reactions read there, so two people reacting at the same moment could each send a list missing the other's reaction, and everyone in the chat would keep one of them. It is now sent once the transaction commits, with the reactions read in a transaction of their own. A group's reactions were already read after their change had committed. --- .../directmessages/DirectMessageService.java | 29 +++++++++++++++---- .../mvc/reactions/MessageReactionService.java | 10 +++++++ .../DirectMessageReactionTest.java | 24 +++++++++++++++ .../reactions/MessageReactionServiceTest.java | 9 ++++++ 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5abc745e..3ab1b53b 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -12,6 +12,8 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; @@ -266,16 +268,33 @@ public List setReaction(DirectMessageCon List reactions = reactionService.forMessage(ChatType.DM, conversation.getId(), key); - DirectMessageEvent event = DirectMessageEvent.builder() + // The frame goes out once this commits, with the reactions read again then. Read here, + // inside this transaction, they could miss a reaction someone else saved at the same time, + // and that person's frame would miss this one. + Long conversationId = conversation.getId(); + afterCommit(() -> messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversationId, DirectMessageEvent.builder() .id(messageId) - .conversationId(conversation.getId()) + .conversationId(conversationId) .type("reactions") - .reactions(reactions) - .build(); - messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); + .reactions(reactionService.forMessageNow(ChatType.DM, conversationId, key)) + .build())); return reactions; } + // Runs once the current transaction commits, or right away outside one. + private static void afterCommit(Runnable action) { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + action.run(); + } + }); + } else { + action.run(); + } + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java index 68224e38..f498f897 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -10,6 +10,7 @@ import java.util.stream.Collectors; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; @@ -64,6 +65,15 @@ public List forMessage(ChatType type, Long chatId, String messa return summarize(rows, reactorsFor(rows)); } + /** + * One message's reactions, read in a transaction of its own: for the frame a DM sends once its + * change has committed, so the read sees what everyone else committed by then. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public List forMessageNow(ChatType type, Long chatId, String messageId) { + return forMessage(type, chatId, messageId); + } + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ @Transactional(readOnly = true) public Map> forChat(ChatType type, Long chatId) { diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java index a3a81b48..01fcc894 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -26,6 +26,8 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.person.Person; @@ -89,6 +91,7 @@ void setUp() { summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(summaries); } @Test @@ -105,6 +108,27 @@ void aReactionGoesOutAsAReactionsFrame() { assertEquals(summaries, result); } + @Test + void theFrameGoesOutAfterTheCommitWithReactionsReadThen() { + // Read after the commit, the list has a reaction someone else committed at the same time. + List fresh = List.of(new ReactionSummary("like", + List.of(new Reactor("alice", "alice"), new Reactor("bob", "bob")))); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(fresh); + TransactionSynchronizationManager.initSynchronization(); + try { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + verify(messagingTemplate, never()).convertAndSend(eq("/topic/dm/7"), any(Object.class)); + + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals(fresh, frame.getValue().getReactions()); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + @Test void takingAReactionBackRemovesIt() { service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java index 4f35ec82..d14b7a4b 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -90,6 +90,15 @@ void aPersonWhoIsGoneIsLeftOut() { service.forMessage(ChatType.DM, 7L, "42")); } + @Test + void forMessageNowReadsTheSameSummary() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(service.forMessage(ChatType.DM, 7L, "42"), service.forMessageNow(ChatType.DM, 7L, "42")); + } + @Test void forChatKeysByMessageId() { when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( From 3e388494231a6519b2b215264cbcc690dadacadb Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:06:24 -0800 Subject: [PATCH 09/10] Reactions: a table that can't be made is logged as an error Spring still starts, as it does when the calls or calendar tables can't be made, but the log now says reactions won't work instead of a warning that is easy to miss. --- .../MessageReactionTableInitializer.java | 4 +- .../MessageReactionTableInitializerTest.java | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java index ba70d3e5..a2cbdfad 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -38,7 +38,9 @@ public ApplicationRunner migrateMessageReaction() { try { jdbcTemplate.execute(CREATE_TABLE); } catch (DataAccessException e) { - logger.warn("Could not create the message_reaction table: {}", e.getMessage()); + // The rest of Spring keeps running, as it does when another table can't be made; + // only the reaction routes fail, until the table exists. + logger.error("Could not create the message_reaction table, so reactions won't work: {}", e.getMessage()); } }; } diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java index c34acaef..27093fe6 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -1,15 +1,26 @@ package com.open.spring.mvc.reactions; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.DefaultApplicationArguments; import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + /** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ class MessageReactionTableInitializerTest { @@ -50,4 +61,36 @@ void rejectsTheSameReactionTwice() { assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); } + + // Startup goes on, as it does for the other tables (calls, calendar), but the log says plainly + // that reactions are broken: a warning was easy to miss. + @Test + void aFailedCreateIsLoggedAsAnErrorAndStartupGoesOn() { + JdbcTemplate failing = new JdbcTemplate(dataSource) { + @Override + public void execute(String sql) { + throw new DataAccessResourceFailureException("the database is read-only"); + } + }; + ApplicationRunner runner = new MessageReactionTableInitializer(failing).migrateMessageReaction(); + Logger logger = (Logger) LoggerFactory.getLogger(MessageReactionTableInitializer.class); + Level previous = logger.getLevel(); + ListAppender logs = new ListAppender<>(); + logs.start(); + logger.addAppender(logs); + logger.setLevel(Level.INFO); + try { + assertDoesNotThrow(() -> runner.run(new DefaultApplicationArguments())); + } finally { + logger.detachAppender(logs); + logger.setLevel(previous); + logs.stop(); + } + + assertEquals(1, logs.list.size()); + ILoggingEvent event = logs.list.get(0); + assertEquals(Level.ERROR, event.getLevel()); + assertTrue(event.getFormattedMessage().contains("reactions won't work"), event.getFormattedMessage()); + assertTrue(event.getFormattedMessage().contains("the database is read-only"), event.getFormattedMessage()); + } } From d6c2bfe9002b780325c5b51294efa4ddaf00138e Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:11:15 -0800 Subject: [PATCH 10/10] Docs: list the reaction tests before the chat regression tests The group chat fixes (#296 to #299) each add a line after the chat regression tests, so the reactions line goes above it and the two change different places. --- docs/group-chat-architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 9e6be786..19a45f7e 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -176,8 +176,8 @@ People react to a message in a group chat or a direct message with one of six em - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. -- Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. - Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, and the table's primary key on SQLite. +- Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. ## Known issues