From 96a4cd90ce21999ac26276607480376bc285c4b0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:28:11 -0800 Subject: [PATCH 01/32] 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/32] 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/32] 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/32] 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 bc79ac5997ad97cd3dfe98a328646b7c21713e96 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 05/32] Group chat: a send keeps the history when S3 can't read it A send reads the group's whole messages file, adds the message and writes the file back. decodeFile answers null for any failure, not only a missing file, so when S3 timed out, was throttled or answered a 5xx, the send took the chat for empty and wrote the one new message over the whole history. It still answered 200 and broadcast the message. The send now reads with a strict decodeFileOrThrow, like fileExistsOrThrow: only S3's 404 means no messages yet. A timeout, no connection or a 5xx throws MessagesReadFailedException, nothing is saved or broadcast, and POST /api/groups/chat/{id}/messages answers 503 with Retry-After, the same as a shared-file check that fails. S3 refusing the read (a 4xx) or a bug here also writes nothing and gets the route's usual 400, since waiting won't fix it. S3 failures to read are logged with their cause. Without S3 settings a send still broadcasts live, as before. decodeFile, edits and deletes are unchanged. Tests send through the controller to a real S3FileHandler over a stand-in S3 client: a 503 and a timeout keep the stored file byte for byte and answer 503, a 403 and a bug write nothing and get no retry, a missing file starts the history, and a server without S3 still broadcasts. The two older tests that stub S3 now stub the strict read a send makes. --- .../spring/mvc/S3uploads/S3FileHandler.java | 25 +++ .../mvc/groups/GroupChatApiController.java | 14 +- .../spring/mvc/groups/GroupChatService.java | 30 ++- .../groups/MessagesReadFailedException.java | 14 ++ .../S3uploads/S3FileHandlerDecodeTest.java | 72 +++++++ .../mvc/groups/GroupChatMessageJsonTest.java | 2 +- .../spring/mvc/groups/GroupChatSendTest.java | 201 ++++++++++++++++++ .../mvc/groups/GroupChatServiceTest.java | 6 + 8 files changed, 357 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java create mode 100644 src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index fafef205..62865a8f 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -264,6 +264,31 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + /** + * Like decodeFile, but only "not found" (404) reads as nothing stored: any other failure to + * read (a throttle, a 5xx, no connection) throws. For a caller that writes back what it read, + * a read that failed is not an empty file. With no S3 client there is nothing to read and + * nothing can be written, so that reads as nothing stored, as in decodeFile. + */ + public String decodeFileOrThrow(String uid, String filename) { + if (s3Client == null) { + log.warn("S3 download attempted but S3 client is not configured."); + return null; + } + try { + ResponseBytes objectBytes = s3Client.getObjectAsBytes(GetObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build()); + return Base64.getEncoder().encodeToString(objectBytes.asByteArray()); + } catch (S3Exception e) { + if (e.statusCode() == 404) { + return null; + } + throw e; + } + } + private String generateKey(String uid, String filename) { return uid + "/" + filename; } 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..56db34d1 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -38,9 +38,9 @@ @CrossOrigin public class GroupChatApiController { - // How long to wait before sharing again when S3 couldn't check a path: a throttle or a - // short outage clears in seconds. - private static final int SHARE_RETRY_AFTER_SECONDS = 5; + // How long to wait before trying again when S3 couldn't check a shared path or read a + // group's messages: a throttle or a short outage clears in seconds. + private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; @@ -192,6 +192,12 @@ public ResponseEntity postMessage( try { realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + } catch (MessagesReadFailedException ex) { + // S3 couldn't read the history, so nothing was saved or broadcast: saving would have + // replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when. + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -406,7 +412,7 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .header(HttpHeaders.RETRY_AFTER, String.valueOf(SHARE_RETRY_AFTER_SECONDS)) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) .body(response); } catch (RuntimeException ex) { return new ResponseEntity<>("Upload failed", HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index d6189355..5f902092 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -80,7 +80,33 @@ public void ensureGroupStorageExists(String groupName) { } public List getMessages(String groupName) { - String base64Data = s3FileHandler.decodeFile(groupName, MESSAGES_FILE); + return parseMessages(groupName, s3FileHandler.decodeFile(groupName, MESSAGES_FILE)); + } + + /** + * The group's messages for a send, which writes the whole file back. Strict: a read that + * failed throws rather than reading as an empty chat, which the send would save over the + * history. Only S3's 404 means no messages yet. S3 out of reach or answering a 5xx is + * something to wait out, so that throws MessagesReadFailedException; anything else goes up + * as it is. + */ + private List readMessagesOrThrow(String groupName) { + String base64Data; + try { + base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); + } catch (SdkClientException | S3Exception e) { + // Logged for every failure: the route answers a refused read without logging it. + log.warn("Could not read the messages of group {}", groupName, e); + if (e instanceof S3Exception answered && answered.statusCode() < 500) { + // S3 refused the request (no permission, a bad key): waiting won't fix that. + throw e; + } + throw new MessagesReadFailedException(e); + } + return parseMessages(groupName, base64Data); + } + + private List parseMessages(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -119,7 +145,7 @@ public List getMessages(String groupName) { public List addMessage(String groupName, GroupChatMessage message) { synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); messages.add(message); String jsonl = messages.stream() diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java new file mode 100644 index 00000000..f74fcda8 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java @@ -0,0 +1,14 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read a group's messages for now: it timed out, couldn't be reached or answered + * with a 5xx (a throttle, an outage). A send writes the whole messages file back, so it's refused + * rather than save the new message over the history, and the API answers 503 with Retry-After, + * since S3 being unavailable for a moment isn't a bug in this server. + */ +public class MessagesReadFailedException extends RuntimeException { + + public MessagesReadFailedException(Throwable cause) { + super("Could not read this group's messages, so the message was not sent. Try again in a moment.", cause); + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java new file mode 100644 index 00000000..181d4527 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java @@ -0,0 +1,72 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * decodeFileOrThrow tells "nothing stored" apart from "couldn't read": a caller that writes + * back what it read must not take a read that failed for an empty file. + */ +class S3FileHandlerDecodeTest { + + private static final String MESSAGES = "messages-images/messages.jsonl"; + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + } + + @Test + void aStoredFileComesBackAsBase64() { + doReturn(ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), "hello".getBytes(StandardCharsets.UTF_8))) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertEquals("aGVsbG8=", handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void notFoundMeansNothingIsStored() { + doThrow(NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build()) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertNull(handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void anyOtherFailureThrowsInsteadOfReadingAsNothingStored() { + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out")); + for (RuntimeException failure : failures) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertSame(failure, assertThrows(RuntimeException.class, () -> handler.decodeFileOrThrow("CSA", MESSAGES))); + // decodeFile keeps answering null, as its other callers expect. + assertNull(handler.decodeFile("CSA", MESSAGES)); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java index 175540a0..943a977e 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,7 +54,7 @@ void messageIsWrittenWithAuthorNotName() throws Exception { @Test void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { S3FileHandler s3 = mock(S3FileHandler.class); - when(s3.decodeFile("CSA", "messages-images/messages.jsonl")).thenReturn( + when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java new file mode 100644 index 00000000..b6c3b718 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,201 @@ +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +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.doThrow; +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.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +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.HttpHeaders; +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 software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * Sending a message reads the group's whole messages file, adds the message and writes the + * file back. A read that failed must not count as an empty chat: writing that back would + * replace the whole history with the one new message. + */ +class GroupChatSendTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** An empty bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404 NoSuchKey. */ + private void useFreshStorage() { + objects.clear(); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + + /** The send route over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); + GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = new GroupChatApiController(chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity send(String text) { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage(text); + return controller.postMessage(7L, request); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + @Test + void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { + // S3 throttled (503 Slow Down) or out of reach: failures that clear if you wait. + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out")); + for (RuntimeException failure : failures) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // The group isn't told about a message that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { + // No permission, a bad key, or a fault in this server: waiting won't fix these. + List faults = List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + for (RuntimeException fault : faults) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List lines = storedMessages().lines().toList(); + assertEquals(1, lines.size(), storedMessages()); + GroupChatMessage saved = new ObjectMapper().readValue(lines.get(0), GroupChatMessage.class); + assertEquals("Works for me", saved.getMessage()); + assertEquals("grace", saved.getAuthor_uid()); + } + + @Test + void withoutS3SettingsASendIsStillBroadcastLive() { + // A local server without S3 saves nothing, but its chats keep working live. + wire(new S3FileHandler()); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + ArgumentCaptor frame = ArgumentCaptor.forClass(Object.class); + verify(messaging).convertAndSend(eq("/topic/group/7"), frame.capture()); + assertEquals("Works for me", ((GroupChatEvent) frame.getValue()).getMessage()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java index b1d40b62..97ce7cc1 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -57,6 +57,12 @@ public String decodeFile(String uid, String filename) { } return copy; } + + // Its reads never fail, so a send's strict read is the same read. + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } } private final ObjectMapper json = new ObjectMapper(); From 5b9931674d7ca23967842a7fad54c2f23bd4af2b Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:00:05 -0800 Subject: [PATCH 06/32] Group chat: two message writes at once keep both changes Sending, editing and deleting a message each read the group's whole messages file from S3, change it and write the file back, with no lock. Two at once both read the same old copy, so the later write dropped the other's change: two people sending at the same moment lost a message, and an edit or delete during a send lost the edit or the new message. They now take one lock per group, the same pattern as the shared-files metadata lock. Reads don't wait, and other groups don't wait on each other. The lock only works within one server. Several servers writing the same file would need S3's conditional writes instead. Tests run two sends, an edit and a send, and a delete and a send at once against an S3 stub that holds each read until the other one has started. --- .../spring/mvc/groups/GroupChatService.java | 104 +++++++------ .../mvc/groups/GroupChatServiceTest.java | 146 ++++++++++++++++++ 2 files changed, 204 insertions(+), 46 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 790db7d3..d6189355 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -35,6 +35,12 @@ public class GroupChatService { private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; + // One lock per group for its messages file. Sending, editing and deleting each read the + // whole file, change it and write it back, so two at once would both change the same old + // copy and the later write would drop the other's change. This keeps them apart within + // this server only; several servers would need S3's conditional writes instead. + private final Map messageLocks = new ConcurrentHashMap<>(); + // One lock per group for the "shared by" sidecar, which is read, changed and written // back on every upload: a folder shared from the page uploads several files at once, // and without this the last write would drop the others' attribution. @@ -112,18 +118,20 @@ public List getMessages(String groupName) { } public List addMessage(String groupName, GroupChatMessage message) { - List messages = getMessages(groupName); - messages.add(message); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); + messages.add(message); - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - return messages; + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + return messages; + } } /** @@ -133,58 +141,62 @@ public List addMessage(String groupName, GroupChatMessage mess */ public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return false; - List messages = getMessages(groupName); - boolean found = false; - for (GroupChatMessage m : messages) { - if (messageId.equals(m.getId())) { - if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); + boolean found = false; + for (GroupChatMessage m : messages) { + if (messageId.equals(m.getId())) { + if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + m.setMessage(newMessage); + m.setEdited(true); + found = true; + break; } - m.setMessage(newMessage); - m.setEdited(true); - found = true; - break; } - } - if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + if (found) { + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + } + return found; } - return found; } /** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */ public void deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return; - List messages = getMessages(groupName); - - GroupChatMessage target = messages.stream() - .filter(m -> messageId.equals(m.getId())) - .findFirst() - .orElse(null); - if (target == null) return; - if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); - boolean removed = messages.remove(target); + GroupChatMessage target = messages.stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + if (target == null) return; + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } - if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + boolean removed = messages.remove(target); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + if (removed) { + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + } } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java new file mode 100644 index 00000000..b1d40b62 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -0,0 +1,146 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * Two changes to one group's messages at the same time. Sending, editing and deleting each + * read the group's whole messages file, change it and write it back, and neither change may + * be lost. + */ +class GroupChatServiceTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + + /** + * S3 kept in a map, keyed the way S3FileHandler keys objects: "group/filename". A read + * takes its copy, then waits until a second read has started (or half a second passes), + * so two writes that are not kept apart both change the same old copy of the file. + */ + static class OverlappingReads extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + final CountDownLatch bothReading = new CountDownLatch(2); + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + + @Override + public String decodeFile(String uid, String filename) { + String copy = objects.get(uid + "/" + filename); + bothReading.countDown(); + try { + bothReading.await(500, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return copy; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private OverlappingReads storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new OverlappingReads(); + chat = new GroupChatService(storage, json); + } + + @Test + void twoMessagesSentAtOnceAreBothKept() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3?"); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.addMessage("CSA", ada), () -> chat.addMessage("CSA", grace)); + + // Either send may get there first, so compare them in alphabetical order. + List saved = texts(chat.getMessages("CSA")).stream().sorted().collect(Collectors.toList()); + assertEquals(List.of("Meeting at 3?", "Works for me"), saved); + } + + @Test + void anEditWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3"); + store(ada); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.editMessage("CSA", ada.getId(), "Meeting at 4", "ada"), + () -> chat.addMessage("CSA", grace)); + + List saved = chat.getMessages("CSA"); + assertEquals(List.of("Meeting at 4", "Works for me"), texts(saved)); + assertTrue(saved.get(0).isEdited()); + } + + @Test + void aDeleteWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage plan = message("Ada Lovelace", "ada", "Meeting at 3"); + GroupChatMessage typo = message("Ada Lovelace", "ada", "Meetign at 3"); + store(plan, typo); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.deleteMessage("CSA", typo.getId(), "ada"), + () -> chat.addMessage("CSA", grace)); + + assertEquals(List.of("Meeting at 3", "Works for me"), texts(chat.getMessages("CSA"))); + } + + /** Starts both together on their own threads and waits for both, failing if either threw. */ + private static void atOnce(Runnable first, Runnable second) throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + List> done = new ArrayList<>(); + for (Runnable task : List.of(first, second)) { + done.add(pool.submit(() -> { + start.await(); + task.run(); + return null; + })); + } + start.countDown(); + try { + for (Future future : done) future.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + } + + private static GroupChatMessage message(String author, String uid, String text) { + return new GroupChatMessage(author, uid, text, "2026-11-21T10:00:00Z", null); + } + + /** Saves messages straight to the group's file, one JSON object per line, as the chat does. */ + private void store(GroupChatMessage... messages) throws Exception { + List lines = new ArrayList<>(); + for (GroupChatMessage message : messages) lines.add(json.writeValueAsString(message)); + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private static List texts(List messages) { + return messages.stream().map(GroupChatMessage::getMessage).collect(Collectors.toList()); + } +} From 7eb0e3580b94729309d52d8f1db2d3e86cabe017 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:52:18 -0800 Subject: [PATCH 07/32] 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 9a3bf22ba93a64a637c6a338d779d0a1bb38871c Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 08/32] Group chat docs: a send reads its messages strictly The send route and the storage notes now say a send reads the messages file with decodeFileOrThrow: S3 being unavailable answers 503 with Retry-After and nothing is saved or broadcast, S3 refusing the read or a bug gets the route's usual 400, and edits and deletes still read with decodeFile. The testing list gets a bullet for GroupChatSendTest and S3FileHandlerDecodeTest, with the command that runs the S3 handler tests. --- docs/group-chat-architecture.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 23be2235..2ed3e467 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,7 +132,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| 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. | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | 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/unread` | `{total, unreadByGroup}` across your groups | You | @@ -155,7 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **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. ## Testing @@ -164,6 +164,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **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. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. +- `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. ## Known issues From af1dba22dec69a108b29bbca6215629d6eba0378 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:01:17 -0800 Subject: [PATCH 09/32] Group chat docs: message writes take a lock per group The storage notes said every send rewrites the file with no lock, and Known issues listed two sends at once losing one. The note now says sending, editing and deleting take one lock per group, within one server only. The testing list names GroupChatServiceTest, and the known issue is gone. --- docs/group-chat-architecture.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..23be2235 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -155,7 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. -- **Every new message rewrites the whole file**, read then write, with no lock. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. - **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. ## Testing @@ -163,6 +163,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `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. +- `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. ## Known issues @@ -173,7 +174,6 @@ These were each reproduced against a local server built from `master` on 2026-10 - **The client chooses the name for presence and typing.** `joinGroup`, `typingStart` and `heartbeat` use the `sender` field the client sends, even from a socket that isn't signed in. - **No membership checks.** Any signed-in account can read and send in any group, list and upload its files, and manage any group, its members and its grades. The membership checks in `GroupChatApiController` are commented out. - **Edit and delete require the stored author uid.** The REST controller passes the authenticated account's uid through the realtime service; display names never establish ownership. Legacy messages without `author_uid` cannot be edited or deleted through these routes. Teachers cannot delete another account's message. -- **Two sends at once can lose one.** Each send reads the group's S3 file, adds a line and writes the file back, without a lock. - **The first group created after a restart fails on SQLite.** `POST /api/groups` returns 500 with `SQLITE_BUSY_SNAPSHOT` the first time after the server starts; the next attempt works. This is the `GenerationType.AUTO` lock problem described under Assignment grading in `AGENTS.md`, here on `submitter_seq`. Not checked on MySQL. ## Change checklist From 457eb003eceb261b9467665e16a0df6cb50288fb Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 23:16:14 -0800 Subject: [PATCH 10/32] Push: a DM's notification shows its words, not the page's markers or HTML MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The push text was the stored body with its whitespace collapsed, so a phone showed what the page reads: [[reply:…]], [[files:…]], [[code:…]] and [[pin:…]] markers, and the rich composer's HTML (,  ). Now the markers are left out, the HTML becomes the text a reader sees, and a message that was only a marker says what it did ("pinned a message", "sent code", "shared files"). A marker's payload can't hold a bracket, so a body full of unclosed "[[" is still matched in linear time. notifyPerson runs inside the message's transaction and never throws, so if the text can't be made from a body, the notification goes out without text and the DM is still sent. --- .../mvc/push/PushNotificationService.java | 66 +++++++++++++++++-- .../mvc/push/PushNotificationSnippetTest.java | 64 ++++++++++++++++++ 2 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java diff --git a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java index 08f63862..1ba9a0c3 100644 --- a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java +++ b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java @@ -4,14 +4,19 @@ import java.security.Security; import java.time.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -49,6 +54,13 @@ public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class); private static final int TTL_SECONDS = 60 * 60 * 24; // keep undelivered pushes for a day private static final int MAX_BODY_CHARS = 140; + // The markers Messages puts in a body for the page to read: a reply's quote, shared files, + // a code block, a pin, and the course chats' events and lessons. A phone shouldn't show them. + // Pages lists the same names in ANY_MARKER_PATTERN (assets/js/chat/chat-reply.js), so a + // marker added there needs adding here too, or its raw text shows up in DM notifications. + // No marker Pages writes has a bracket inside it (it escapes or URL-encodes them), so the + // payload leaves out "[" as well: that keeps matching linear when a body is full of "[[". + private static final Pattern CHAT_MARKER = Pattern.compile("\\[\\[(reply|event|lesson|files|code|pin|unpin):[^\\[\\]]*\\]\\]"); /** How long an unchanged subscription goes before a re-send refreshes last_used_at. */ private static final Duration RESEEN_AFTER = Duration.ofDays(1); @@ -174,7 +186,7 @@ public void notifyPerson(Person person, String title, String body, String url, S } Map payload = Map.of( "title", title == null ? "New message" : title, - "body", snippet(body), + "body", pushText(body), "url", url == null ? "/dm" : url, "tag", tag == null ? "ocs" : tag); Long personId = person.getId(); @@ -191,6 +203,17 @@ public void afterCommit() { } } + // notifyPerson never throws, and it runs inside the message's transaction, so a body the + // text can't be made from still sends the message and its notification, without text. + private static String pushText(String body) { + try { + return snippet(body); + } catch (RuntimeException ex) { + log.warn("Web push: could not make the notification's text ({})", ex.getMessage()); + return ""; + } + } + /** Runs on the sender thread: loads the person's subscriptions and pushes to each. */ private void sendToPerson(Long personId, Map payload) { List subscriptions; @@ -236,12 +259,47 @@ private void send(PushSubscriptionEntity subscription, String json) { } } + /** + * The notification's text: the message as a reader sees it in the chat, cut to + * {@value #MAX_BODY_CHARS} characters. The chat's markers are left out, and the rich + * composer's HTML becomes plain text (tags gone, entities decoded, {@code  } a space). + * If no words are left, the text says what the message did instead, such as "pinned a + * message", or just "sent a message". + */ static String snippet(String body) { - if (body == null) { + if (body == null || body.isBlank()) { return ""; } - String oneLine = body.replaceAll("\\s+", " ").trim(); - return oneLine.length() <= MAX_BODY_CHARS ? oneLine : oneLine.substring(0, MAX_BODY_CHARS - 1) + "…"; + Set markers = new HashSet<>(); + Matcher marker = CHAT_MARKER.matcher(body); + StringBuilder words = new StringBuilder(); + while (marker.find()) { + markers.add(marker.group(1)); + marker.appendReplacement(words, " "); + } + marker.appendTail(words); + String text = Jsoup.parse(words.toString()).text().replace('\u00A0', ' ').replaceAll("\\s+", " ").trim(); + if (text.isEmpty()) { + text = onlyMarkers(markers); + } + return text.length() <= MAX_BODY_CHARS ? text : text.substring(0, MAX_BODY_CHARS - 1) + "…"; + } + + // What a message that was only markers did, said after the sender's name (the title). + private static String onlyMarkers(Set markers) { + if (markers.contains("pin")) { + return "pinned a message"; + } + if (markers.contains("unpin")) { + return "unpinned a message"; + } + if (markers.contains("code")) { + return "sent code"; + } + if (markers.contains("files")) { + return "shared files"; + } + return "sent a message"; } @PreDestroy diff --git a/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java new file mode 100644 index 00000000..6b45dca8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java @@ -0,0 +1,64 @@ +package com.open.spring.mvc.push; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +/** + * The text a phone shows for a direct message: the words a reader sees in the chat, without + * the markers the page reads ([[reply:…]], [[files:…]], [[code:…]], [[pin:…]]) or the rich + * composer's HTML. + */ +class PushNotificationSnippetTest { + + @Test + void chatMarkersAreLeftOut() { + assertEquals("thanks!", PushNotificationService.snippet("[[reply:9|Bob|hey%20there]] thanks!")); + assertEquals("look", PushNotificationService.snippet("[[files:f~shots%2Fa.png~5]] look")); + // Pages escapes brackets, "|", "%", "<", ">" and "&" in code, but keeps quotes, tabs and newlines. + assertEquals("try this", PushNotificationService.snippet( + "[[code:python|print(\"hi\")\nfor i in range(3):\n\tprint(i)]] try this")); + assertEquals("see this", PushNotificationService.snippet( + "[[reply:9|Bob|hey]] [[files:f~a.txt~1]] [[code:java|int x;]] see this")); + } + + @Test + void aMessageThatIsOnlyAMarkerSaysWhatItDid() { + assertEquals("pinned a message", PushNotificationService.snippet("[[pin:401]]")); + assertEquals("unpinned a message", PushNotificationService.snippet("[[unpin:401]]")); + assertEquals("sent code", PushNotificationService.snippet("[[code:python|print(1)]]")); + assertEquals("shared files", PushNotificationService.snippet("[[files:f~a.png~5]]")); + // A reply that only attaches an image has nothing but its reply marker in the body. + assertEquals("sent a message", PushNotificationService.snippet("[[reply:9|Bob|hey]]")); + } + + @Test + void theComposersHtmlBecomesPlainText() { + assertEquals("check https://github.com/o/r/pull/3", PushNotificationService.snippet( + "check " + + "https://github.com/o/r/pull/3 ")); + assertEquals("Fish & chips tonight", PushNotificationService.snippet("Fish & chips
tonight")); + assertEquals("a < b", PushNotificationService.snippet("a < b")); + } + + @Test + void longTextIsCutAndBlankStaysBlank() { + String cut = PushNotificationService.snippet("x".repeat(200)); + assertEquals(140, cut.length()); + assertEquals('…', cut.charAt(139)); + assertEquals("", PushNotificationService.snippet(null)); + assertEquals("", PushNotificationService.snippet(" ")); + } + + @Test + void markerOpeningsThatNeverCloseStayFast() { + // None of these markers closes, so a pattern that rescans the rest of the body at each + // "[[" takes seconds here; matching has to stay linear. + String body = "[[code:".repeat(20_000); + String text = assertTimeoutPreemptively(Duration.ofSeconds(1), () -> PushNotificationService.snippet(body)); + assertEquals(140, text.length()); + } +} From 1b7fb8da5cc1f53fa9f9d8937c80c5d0db58c9a1 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:03:10 -0800 Subject: [PATCH 11/32] 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 4b746342c3607da907d953bd5d9b9472c260a0c3 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Mon, 23 Nov 2026 02:27:21 -0800 Subject: [PATCH 12/32] Chat socket: drop client SENDs to every /topic destination DirectMessageTopicGuard already dropped a client's SEND to a DM topic. It now drops a client's SEND to any destination the simple broker handles (WebSocketBrokerConfig.BROKER_PREFIX, "/topic"), so group chat topics get the same rule. Only the server publishes to topics: pages send group messages over REST, and Spring's group page sends to /app/groups.chat. The tests cover SENDs to DM, group and other topic destinations being dropped, and the server's own group broadcast still reaching its subscribers. --- AGENTS.md | 1 + docs/group-chat-architecture.md | 2 +- .../DirectMessageTopicGuard.java | 10 ++++--- .../mvc/groups/WebSocketBrokerConfig.java | 7 +++-- .../DirectMessageTopicBrokerTest.java | 29 +++++++++++++++++++ .../DirectMessageTopicGuardTest.java | 10 ++++--- 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279..4818603d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Entity-removal helpers (run before any large cleanup): - Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate. - Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter. - [docs/group-chat-architecture.md](docs/group-chat-architecture.md) covers every groups and chat route, the WebSocket event contexts, S3 message storage (keyed by group name, not id) and the known issues. Over the WebSocket there is no Spring Security context, so a service that needs the signed-in account (like `GroupChatIdentityService`) only works from REST. The socket does read the `jwt_java_spring` cookie when it opens (`ChatSocketIdentityInterceptor`, same checks as `JwtRequestFilter`, and only when the request's `Origin` is in the REST CORS list, since a cross-site GET carries the cookie but no Origin), but only for `DirectMessageTopicGuard`: only a conversation's participants can subscribe to `/topic/dm/{id}`, and wildcard subscriptions, `/user/...` destinations and client SENDs to DM topics are dropped. It sets no Principal, on purpose, so `GroupChatWebSocketController` still ignores events. HTTP: `api/groups.http`. +- A client's SEND to any `/topic/...` destination is dropped too, group topics included, because the simple broker relays it to every subscriber. Only the server publishes there (the prefix is `WebSocketBrokerConfig.BROKER_PREFIX`). ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..3d8840bc 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -161,7 +161,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) ## 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'`. +- **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 any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. 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. ## Known issues diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java index ac52e689..88776100 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java @@ -13,6 +13,7 @@ import org.springframework.util.PathMatcher; import com.open.spring.mvc.groups.ChatSocketIdentityInterceptor; +import com.open.spring.mvc.groups.WebSocketBrokerConfig; import lombok.extern.slf4j.Slf4j; @@ -26,8 +27,9 @@ *
  • No wildcard SUBSCRIBE on any topic. The broker matches {@code *}, {@code **}, {@code ?} * and {@code {name}} as patterns, so {@code /topic/**} would get every DM with no id at all. * No client uses one.
  • - *
  • No client SEND to a DM topic. The broker relays a client's SEND to every subscriber, so it - * would show up in someone's thread as a real message. Only the server posts there.
  • + *
  • No client SEND to any topic, DM or group ({@code /topic...}). The broker relays a client's + * SEND to every subscriber, so it would show up in someone's chat as a real message. Only the + * server posts there; pages send through REST or {@code /app/groups.chat}.
  • *
  • No SUBSCRIBE or SEND to a user destination ({@code /user/...}). Nothing on this socket uses * them, and Spring rewrites a {@code /user/X} subscription to X plus "-user" plus the session id * after this check. A SockJS client picks its own session id, so the two halves together can make @@ -102,8 +104,8 @@ private String whySubscribeIsRefused(String destination, Map ses /** Why a client's SEND is refused, or null to let it through. */ private static String whySendIsRefused(String destination) { - if (isDirectMessageTopic(destination)) { - return "only the server sends to direct message topics"; + if (destination != null && destination.startsWith(WebSocketBrokerConfig.BROKER_PREFIX)) { + return "only the server sends to topics"; } if (isUserDestination(destination)) { return NO_USER_DESTINATIONS; diff --git a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java index 84ab9f48..590f56a5 100644 --- a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java +++ b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java @@ -20,12 +20,15 @@ *

    * When a socket opens, {@link ChatSocketIdentityInterceptor} reads the login cookie. Every frame a * client sends then passes {@link DirectMessageTopicGuard}, which lets only a conversation's - * participants subscribe to its /topic/dm/{id}. + * participants subscribe to its /topic/dm/{id} and keeps clients from sending to any topic. */ @Configuration @EnableWebSocketMessageBroker public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer { + /** The simple broker handles every destination that starts with this, so only the server may send there. */ + public static final String BROKER_PREFIX = "/topic"; + private final ChatSocketIdentityInterceptor identityInterceptor; private final DirectMessageTopicGuard directMessageTopicGuard; @@ -53,7 +56,7 @@ public void configureClientInboundChannel(ChannelRegistration registration) { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.enableSimpleBroker("/topic"); + registry.enableSimpleBroker(BROKER_PREFIX); registry.setApplicationDestinationPrefixes("/app"); } } diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java index d2f192fc..3d3e00ae 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java @@ -65,6 +65,35 @@ void tearDown() { broker.stop(); } + /** A group chat reader, signed out like a course chat visitor, must not get a frame a client made up. */ + @Test + void aClientSendToAGroupTopicReachesNobody() { + connect("reader-socket"); + connect("outsider-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + StompHeaderAccessor send = StompHeaderAccessor.create(StompCommand.SEND); + send.setSessionId("outsider-socket"); + send.setSessionAttributes(Map.of()); + send.setDestination("/topic/group/7"); + clientInbound.send(MessageBuilder.createMessage( + "{\"context\":\"sendMessageServer\",\"groupId\":7,\"sender\":\"Thomas Edison\",\"message\":\"FAKE: click this link\"}" + .getBytes(StandardCharsets.UTF_8), + send.getMessageHeaders())); + + assertEquals(List.of(), socketsThatReceivedSomething()); + } + + @Test + void theServersGroupBroadcastStillReachesSignedOutReaders() { + connect("reader-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + serverBroadcast("/topic/group/7", "{\"context\":\"sendMessageServer\",\"message\":\"hello class\"}"); + + assertEquals(List.of("reader-socket"), socketsThatReceivedSomething()); + } + /** * Spring turns SUBSCRIBE /user/X into a subscription to X + "-user" + the session id, which a * SockJS client picks itself. Session id "}" closes the brace this destination opens, so the diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java index e2fd0814..834b7d24 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java @@ -91,10 +91,12 @@ void userDestinationsAreRefused() { assertNull(guard.preSend(frame(StompCommand.SEND, "/user/hop/queue/messages", SIGNED_OUT), channel)); } - @Test - void clientCannotSendToADmTopic() { - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", HOP), channel)); - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", SIGNED_OUT), channel)); + /** The broker relays a client's SEND to every subscriber of any destination starting with /topic. */ + @ParameterizedTest + @ValueSource(strings = {"/topic/dm/1", "/topic/group/7", "/topic/anything", "/topicx"}) + void clientCannotSendToAnyTopic(String destination) { + assertNull(guard.preSend(frame(StompCommand.SEND, destination, HOP), channel)); + assertNull(guard.preSend(frame(StompCommand.SEND, destination, SIGNED_OUT), channel)); } @Test From 5e000006b0411cd629b98c40c004516b771862a0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:34:46 -0800 Subject: [PATCH 13/32] 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 14/32] 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 15/32] 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 16/32] 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 From d9a74b42b7839aa292d0d4201a9c0ffc946ff5c7 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:21:35 -0800 Subject: [PATCH 17/32] Group chat tests: build the send test's controller from its constructor's types GroupChatSendTest built GroupChatApiController, GroupChatRealtimeService and GroupChatReadService by naming their constructors. Open PRs add constructor dependencies to the controller and the realtime service (#302 a MessageReactionService, #303 a MentorAccess), so once one of them and this test were both on master, the tests would stop compiling, with no merge conflict to show it. TestBeans builds a class through its biggest constructor: each parameter gets the first object the test passes that fits it, and a Mockito mock otherwise. The test then keeps compiling and running whatever dependencies those classes gain. --- .../spring/mvc/groups/GroupChatSendTest.java | 8 ++-- .../com/open/spring/mvc/groups/TestBeans.java | 37 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/TestBeans.java diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index b6c3b718..05c32271 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -103,10 +103,12 @@ private void wire(S3FileHandler storage) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); - GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); Groups group = new Groups(); group.setName("CSA"); diff --git a/src/test/java/com/open/spring/mvc/groups/TestBeans.java b/src/test/java/com/open/spring/mvc/groups/TestBeans.java new file mode 100644 index 00000000..2191bd37 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/TestBeans.java @@ -0,0 +1,37 @@ +package com.open.spring.mvc.groups; + +import java.lang.reflect.Constructor; +import java.util.Arrays; +import java.util.Comparator; + +import org.mockito.Mockito; + +/** + * Builds a class through its constructor without naming the constructor's parameters. Each + * parameter gets the first object the test passes that fits it, and any other parameter gets a + * Mockito mock. So a test keeps compiling, and keeps running, when another change gives the + * class a dependency the test doesn't care about. + */ +final class TestBeans { + + private TestBeans() { + } + + static T build(Class type, Object... given) { + Constructor constructor = Arrays.stream(type.getDeclaredConstructors()) + .max(Comparator.comparingInt(Constructor::getParameterCount)) + .orElseThrow(); + Object[] args = Arrays.stream(constructor.getParameterTypes()) + .map(parameter -> Arrays.stream(given) + .filter(parameter::isInstance) + .findFirst() + .orElseGet(() -> Mockito.mock(parameter))) + .toArray(); + try { + constructor.setAccessible(true); + return type.cast(constructor.newInstance(args)); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not build " + type.getSimpleName(), e); + } + } +} From 62179360095b51c0ca60400ff7409303a5d7ab20 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 22:11:22 -0800 Subject: [PATCH 18/32] Group files: answer 503 when S3 can't take the write After the path check, the upload wrote the file with S3FileHandler.uploadFile, which catches every failure and answers null. So when S3 throttled the write, timed out or couldn't be reached, the upload got a 500 "Upload failed", which reads as a bug in this server. Shared files now write with uploadFileOrThrow, a strict version beside it, the way fileExistsOrThrow sits beside fileExists. uploadFile is unchanged for the other S3 features. A timeout, no connection or a 5xx on the write now answers 503 with a try-again message and Retry-After, like a failed check, and the file isn't shared: no "shared by" record and no socket frame. S3 refusing the write (a 4xx such as no permission) or a bug here is still a 500 "Upload failed", and every failed write is still logged. S3's RequestTimeout counts as a timeout too, for the check and the write: S3 sends it as a 400, but it means the connection was too slow, and the AWS SDK retries it like a 5xx. SharedFileCheckFailedException is now SharedFileStorageUnavailableException, since a failed write throws it too, so the 503 is still answered in one place. One check (isUnavailable) decides what counts as S3 being unavailable for both the check and the write. The architecture doc says the same. Tests cover a throttle, a timeout and a RequestTimeout on the write (503), an S3 403, an S3 400 and a bug (500), sharing again once S3 is back, and uploadFileOrThrow itself. --- docs/group-chat-architecture.md | 5 +- .../spring/mvc/S3uploads/S3FileHandler.java | 17 ++++ .../mvc/groups/GroupChatApiController.java | 11 ++- .../mvc/groups/GroupChatRealtimeService.java | 5 +- .../spring/mvc/groups/GroupChatService.java | 54 ++++++++-- .../SharedFileCheckFailedException.java | 21 ---- ...SharedFileStorageUnavailableException.java | 22 +++++ .../S3uploads/S3FileHandlerUploadTest.java | 79 +++++++++++++++ .../spring/mvc/groups/GroupChatFilesTest.java | 98 +++++++++++++++++++ 9 files changed, 270 insertions(+), 42 deletions(-) delete mode 100644 src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java create mode 100644 src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java create mode 100644 src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 67f977ad..a02faa71 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -140,7 +140,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/index` | Shared files as `[{path, size, uploadedBy, uploadedAt}]`, sorted by path, without bytes | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/content?path=` | One shared file's bytes (`application/octet-stream`, named by the last part of its path); 400 for a path that isn't valid, 404 when there is no such file | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 can't say for now whether the path is taken. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | +| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 is unavailable for a moment, checking the path or writing the file. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | | GET | `/api/groups/chat/analytics/{personId}` | Message and file counts across a person's groups | Any signed-in account | ## Persistence @@ -150,7 +150,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. | | 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. | +| 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. The write is strict too (`S3FileHandler.uploadFileOrThrow`): a failed write throws instead of answering null. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx (a throttle, an outage), checking or writing, that's a 503 with `Retry-After` (`SharedFileStorageUnavailableException`); S3 refusing the request (any other 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. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. @@ -167,6 +167,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. +- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. ## Known issues diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index fa2c9b82..8f1f4dab 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -110,6 +110,23 @@ public String uploadFile(String base64Data, String filename, String uid) { } } + /** + * Like uploadFile, but a write that fails throws instead of answering null, so a caller can + * tell S3 being unavailable for a moment (a throttle, a 5xx, no connection) from a request + * S3 refused. + */ + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (s3Client == null) { + throw new IllegalStateException("S3 client is not configured"); + } + s3Client.putObject(PutObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build(), + RequestBody.fromBytes(Base64.getDecoder().decode(base64Data))); + return filename; + } + @Override public String decodeFile(String uid, String filename) { if (s3Client == null) { 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 56db34d1..fcc528e3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -38,8 +38,9 @@ @CrossOrigin public class GroupChatApiController { - // How long to wait before trying again when S3 couldn't check a shared path or read a - // group's messages: a throttle or a short outage clears in seconds. + // How long to wait before trying again when S3 was unavailable for a moment, checking or + // writing a shared file or reading a group's messages: a throttle or a short outage clears + // in seconds. private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; @@ -405,9 +406,9 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return new ResponseEntity<>(response, HttpStatus.CONFLICT); - } catch (SharedFileCheckFailedException ex) { - // S3 couldn't say whether the path is taken, so nothing was written. That's S3 being - // unavailable for a moment, not a bug here: a 503, and when to try again. + } catch (SharedFileStorageUnavailableException ex) { + // S3 was unavailable for a moment, checking the path or writing the file, so the file + // isn't shared. That's not a bug here: a 503, and when to try again. Map response = new HashMap<>(); response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); 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..bac95d70 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -101,10 +101,7 @@ public GroupChatEvent publishFile(Long groupId, String sender, String filename, throw new IllegalArgumentException("Invalid file path"); } - String uploadResult = groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); - if (uploadResult == null) { - throw new IllegalStateException("Upload failed"); - } + groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); GroupChatEvent event = GroupChatEvent.builder() .context("sendFileServer") diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index f1549961..afc92eee 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -31,6 +32,8 @@ public class GroupChatService { private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; private static final String SHARED_FILES_PREFIX = "shared-files/"; private static final String SHARED_FILES_META = "shared-files-meta.json"; + // S3's error code when a connection was too slow: a 400, but the AWS SDK retries it like a 5xx. + private static final String S3_REQUEST_TIMEOUT = "RequestTimeout"; private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; @@ -306,7 +309,8 @@ public byte[] readSharedFile(String groupName, String path) { /** * Stores a shared file, never over one already there: that throws SharedFileExistsException. - * When S3 can't say for now whether the path is taken, it throws SharedFileCheckFailedException. + * When S3 is unavailable for a moment, checking the path or writing the file, it throws + * SharedFileStorageUnavailableException. */ public String uploadSharedFile(String groupName, String filename, String base64Data, String uploadedBy) { List key = List.of(groupName, filename); @@ -317,10 +321,7 @@ public String uploadSharedFile(String groupName, String filename, String base64D if (isAlreadyShared(groupName, filename)) { throw new SharedFileExistsException(filename); } - String result = s3FileHandler.uploadFile(base64Data, SHARED_FILES_PREFIX + filename, groupName); - if (result == null) { - return null; - } + String result = store(groupName, filename, base64Data); recordFileMeta(groupName, filename, uploadedBy); return result; } finally { @@ -330,20 +331,53 @@ public String uploadSharedFile(String groupName, String filename, String base64D /** * Whether a file is stored at this path. Strict: a check that failed throws, rather than - * reading as a free path. S3 out of reach or answering a 5xx is something to wait out, so - * that throws SharedFileCheckFailedException; anything else goes up as it is. + * reading as a free path. S3 being unavailable throws SharedFileStorageUnavailableException; + * anything else goes up as it is. */ private boolean isAlreadyShared(String groupName, String path) { try { return s3FileHandler.fileExistsOrThrow(groupName, SHARED_FILES_PREFIX + path); } catch (SdkClientException | S3Exception e) { - if (e instanceof S3Exception answered && answered.statusCode() < 500) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + if (!isUnavailable(e)) { throw e; } log.warn("Could not check whether {} is shared in group {}", path, groupName, e); - throw new SharedFileCheckFailedException(path, e); + throw new SharedFileStorageUnavailableException(path, e); + } + } + + /** + * Writes a shared file's bytes. S3 being unavailable throws + * SharedFileStorageUnavailableException; any other failure fails the upload as it always has. + */ + private String store(String groupName, String path, String base64Data) { + try { + return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); + } catch (RuntimeException e) { + log.warn("Could not store {} in group {}", path, groupName, e); + if (isUnavailable(e)) { + throw new SharedFileStorageUnavailableException(path, e); + } + throw new IllegalStateException("Upload failed", e); + } + } + + /** + * S3 out of reach (a timeout, no connection), answering a 5xx (a throttle, an outage) or + * timing out the request itself (RequestTimeout, which comes as a 400): something to wait + * out. Any other 4xx is S3 refusing the request (no permission, a bad key), which waiting + * won't fix, and anything else is a fault here. + */ + private static boolean isUnavailable(RuntimeException e) { + if (e instanceof SdkClientException) { + return true; + } + if (e instanceof S3Exception answered) { + AwsErrorDetails details = answered.awsErrorDetails(); + return answered.statusCode() >= 500 + || (details != null && S3_REQUEST_TIMEOUT.equals(details.errorCode())); } + return false; } // --------------------------------------------------------------------------- diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java deleted file mode 100644 index e71203dd..00000000 --- a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't say for now whether a shared file is already stored at this path: it timed out, - * couldn't be reached or answered with a 5xx (a throttle, an outage). The upload is refused - * rather than risk writing over a file, and the API answers 503 with Retry-After, since S3 being - * unavailable for a moment isn't a bug in this server. - */ -public class SharedFileCheckFailedException extends RuntimeException { - - private final String path; - - public SharedFileCheckFailedException(String path, Throwable cause) { - super("Could not check whether " + path + " is already shared in this group. Try again in a moment.", cause); - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java new file mode 100644 index 00000000..0f1ee102 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java @@ -0,0 +1,22 @@ +package com.open.spring.mvc.groups; + +/** + * S3 was unavailable for a moment while a file was being shared: it timed out, couldn't be + * reached or answered with a 5xx (a throttle, an outage). Either it couldn't say whether the + * path is taken, so the upload is refused rather than risk writing over a file, or the write + * itself failed. The file isn't shared, and the API answers 503 with Retry-After, since S3 being + * unavailable for a moment isn't a bug in this server. + */ +public class SharedFileStorageUnavailableException extends RuntimeException { + + private final String path; + + public SharedFileStorageUnavailableException(String path, Throwable cause) { + super("Could not share " + path + " in this group. Try again in a moment.", cause); + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java new file mode 100644 index 00000000..0e35b375 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java @@ -0,0 +1,79 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * uploadFileOrThrow tells a stored file apart from a write that failed: it throws the failure + * where uploadFile answers null, so a caller can tell S3 being unavailable for a moment from a + * request S3 refused. + */ +class S3FileHandlerUploadTest { + + private static final String HELLO = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8)); + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + ReflectionTestUtils.setField(handler, "bucketName", "pages-assignments"); + } + + @Test + void aWriteS3TakesStoresTheBytesUnderTheGroupsKey() throws Exception { + assertEquals("shared-files/notes.md", handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + ArgumentCaptor body = ArgumentCaptor.forClass(RequestBody.class); + verify(s3).putObject(request.capture(), body.capture()); + assertEquals("pages-assignments", request.getValue().bucket()); + assertEquals("CSA/shared-files/notes.md", request.getValue().key()); + try (InputStream bytes = body.getValue().contentStreamProvider().newStream()) { + assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), bytes.readAllBytes()); + } + } + + @Test + void aWriteThatFailsThrowsTheFailureInsteadOfAnsweringNull() { + S3Exception throttled = (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(throttled); + + assertSame(throttled, assertThrows(S3Exception.class, + () -> handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA"))); + // uploadFile keeps answering null, as its other callers expect. + assertNull(handler.uploadFile(HELLO, "shared-files/notes.md", "CSA")); + } + + @Test + void withoutS3ItThrowsInsteadOfAnsweringNull() { + S3FileHandler notConfigured = new S3FileHandler(); + + assertThrows(IllegalStateException.class, + () -> notConfigured.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + } +} 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..6e6efacd 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -41,6 +41,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -61,6 +62,12 @@ public String uploadFile(String base64Data, String filename, String uid) { return filename; } + // Stores the same way, so a test that slows uploadFile slows this too. + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + return uploadFile(base64Data, filename, uid); + } + @Override public String decodeFile(String uid, String filename) { byte[] bytes = objects.get(uid + "/" + filename); @@ -90,6 +97,36 @@ public Map listFileSizes(String prefix) { } } + /** + * S3 that answers the check but fails the write of a shared file's bytes while `failure` is + * set, the way S3FileHandler sees it: uploadFile swallows the failure and answers null, and + * uploadFileOrThrow throws it. Other writes, like the "shared by" record, still go through. + */ + static class SharedFileWritesFail extends InMemoryStorage { + RuntimeException failure; + + SharedFileWritesFail(RuntimeException failure) { + this.failure = failure; + } + + private boolean failing(String filename) { + return failure != null && filename.startsWith("shared-files/"); + } + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + return failing(filename) ? null : super.uploadFile(base64Data, filename, uid); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (failing(filename)) { + throw failure; + } + return super.uploadFileOrThrow(base64Data, filename, uid); + } + } + private InMemoryStorage storage; private SimpMessagingTemplate messaging; private GroupChatApiController controller; @@ -323,6 +360,67 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + @Test + void aWriteThatFailsForAMomentIsA503AndSharesNothing() { + // The path is free, but S3 throttled the write (503 Slow Down), couldn't be reached, or + // timed out the request (its RequestTimeout comes as a 400). + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + for (RuntimeException failure : failures) { + useStorage(new SharedFileWritesFail(failure)); + + ResponseEntity response = upload("notes.md", "Grace's notes"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + @SuppressWarnings("unchecked") + Map body = (Map) response.getBody(); + assertEquals("notes.md", body.get("filename")); + // No file, no "shared by" record, and no frame telling the group a file arrived. + assertTrue(storage.objects.isEmpty(), "stored: " + storage.objects.keySet()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aWriteS3RefusesOrABugIsStillA500() { + // S3 refusing the write (no permission, a bad request) or a fault in this server: trying + // again won't help, so none is a 503. + List faults = List.of( + new NullPointerException("a bug here, not S3"), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("InvalidRequest").build()) + .message("Invalid Request") + .build()); + for (RuntimeException fault : faults) { + useStorage(new SharedFileWritesFail(fault)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, upload("notes.md", "Grace's notes").getStatusCode(), fault.toString()); + } + } + + @Test + void aShareThatFailedForAMomentGoesThroughWhenTriedAgain() { + // What the 503 promises: once S3 takes writes again, the same share works, instead of + // finding the path still held by the upload that failed. + SharedFileWritesFail s3 = new SharedFileWritesFail( + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + useStorage(s3); + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, upload("notes.md", "Grace's notes").getStatusCode()); + + s3.failure = null; + + assertEquals(HttpStatus.OK, upload("notes.md", "Grace's notes").getStatusCode()); + assertArrayEquals("Grace's notes".getBytes(StandardCharsets.UTF_8), storage.objects.get("CSA/shared-files/notes.md")); + } + @Test void aPathBeingWrittenInOneGroupDoesNotHoldUpALookAlikeInAnother() throws Exception { // "a/b" sharing "c" and "a" sharing "b/c" read the same if group and path are joined. From b30e611fa82f8cd983a1f0cb8617979ee7cef00d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:04:56 -0800 Subject: [PATCH 19/32] Group chat: a restart keeps the history when S3 can't check it At every start, StartupService checks each group's messages file and creates an empty one for a group that has none. The check used fileExists, which reads any failure (a throttle, a 5xx, a timeout) as a missing file, so a check that failed at boot wrote an empty file over that group's whole history. ensureGroupStorageExists now checks with fileExistsOrThrow: only S3's 404 creates the file, and any other failure throws before anything is written. StartupService logs that group with the cause and goes on to the next one, so the server still starts. The check holds the group's message lock, so a message sent while the server is starting isn't written over, and a server without S3 settings checks nothing (S3FileHandler.isConfigured). The shared-files/ placeholder keeps the lenient check: it is empty, so writing it again loses nothing. --- .../java/com/open/spring/StartupService.java | 12 +- .../spring/mvc/S3uploads/S3FileHandler.java | 5 + .../spring/mvc/groups/GroupChatService.java | 25 +- .../com/open/spring/StartupServiceTest.java | 291 ++++++++++++++++++ 4 files changed, 326 insertions(+), 7 deletions(-) create mode 100644 src/test/java/com/open/spring/StartupServiceTest.java diff --git a/src/main/java/com/open/spring/StartupService.java b/src/main/java/com/open/spring/StartupService.java index 0f6c434f..d2c28de6 100644 --- a/src/main/java/com/open/spring/StartupService.java +++ b/src/main/java/com/open/spring/StartupService.java @@ -11,9 +11,11 @@ import com.open.spring.mvc.groups.GroupsJpaRepository; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; @Component @RequiredArgsConstructor +@Slf4j public class StartupService { private final GroupsJpaRepository groupsRepository; @@ -25,9 +27,15 @@ public ApplicationRunner initializeGroupStorage() { // Fetch all existing groups from the database List groups = groupsRepository.findAll(); - // Ensure S3 storage exists for each group + // Ensure S3 storage exists for each group. A group whose storage can't be checked is + // left as it is until the next start, and the other groups are still checked, so one + // group can't stop the server from starting. for (Groups group : groups) { - groupChatService.ensureGroupStorageExists(group.getName()); + try { + groupChatService.ensureGroupStorageExists(group.getName()); + } catch (RuntimeException e) { + log.warn("Could not check the chat storage of group {}, so nothing was written to it", group.getName(), e); + } } }; } diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index 62865a8f..fa2c9b82 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -79,6 +79,11 @@ public void init() { this.s3Client = builder.build(); } + /** Whether this server has S3 settings (AWS credentials, region and bucket). Without them nothing is stored. */ + public boolean isConfigured() { + return s3Client != null; + } + @Override public String uploadFile(String base64Data, String filename, String uid) { if (s3Client == null) { diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 5f902092..f1549961 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -65,14 +65,29 @@ public void initGroupStorage(String groupName) { s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); } + /** + * Creates the group's empty messages file and shared-files/ folder if they're missing. + * Strict for the messages file: only S3's 404 means missing, and a check that failed + * throws without writing, since an empty file written over the real one would erase the + * group's history. + */ public void ensureGroupStorageExists(String groupName) { - // Check if messages.jsonl exists, if not, create it - if (!s3FileHandler.fileExists(groupName, MESSAGES_FILE)) { - String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); - s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + // Without S3 settings nothing is stored, so there's nothing to check. + if (!s3FileHandler.isConfigured()) { + return; + } + + // Check if messages.jsonl exists, if not, create it. Under the group's message lock, + // so a message sent between the check and the write isn't lost under the empty file. + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + if (!s3FileHandler.fileExistsOrThrow(groupName, MESSAGES_FILE)) { + String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); + s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + } } - // Check if shared-files/ folder exists, if not, create it + // Check if shared-files/ folder exists, if not, create it. Its placeholder is empty, + // so writing it again loses nothing. if (!s3FileHandler.fileExists(groupName, SHARED_FILES_PREFIX)) { String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); diff --git a/src/test/java/com/open/spring/StartupServiceTest.java b/src/test/java/com/open/spring/StartupServiceTest.java new file mode 100644 index 00000000..163d31d0 --- /dev/null +++ b/src/test/java/com/open/spring/StartupServiceTest.java @@ -0,0 +1,291 @@ +package com.open.spring; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.groups.GroupChatMessage; +import com.open.spring.mvc.groups.GroupChatService; +import com.open.spring.mvc.groups.Groups; +import com.open.spring.mvc.groups.GroupsJpaRepository; + +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; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * At every start the server checks each group's chat files in S3 and creates an empty + * messages file for a group that has none. A check that failed must not count as none: + * the empty file would replace the group's whole history. + */ +class StartupServiceTest { + + private static final String CSA_MESSAGES = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reaches them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + /** Groups S3 can't answer for right now: checking any of their files throws this. */ + private final Map failingChecks = new ConcurrentHashMap<>(); + private S3Client s3; + private GroupChatService chat; + private GroupsJpaRepository groups; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + // As S3 answers: a key that isn't stored is a 404 NoSuchKey. + when(s3.headObject(any(HeadObjectRequest.class))).thenAnswer(call -> { + String key = call.getArgument(0).key(); + RuntimeException failure = failingChecks.get(key.substring(0, key.indexOf('/'))); + if (failure != null) { + throw failure; + } + if (!objects.containsKey(key)) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw notFound(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + store(call.getArgument(0).key(), call.getArgument(1)); + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + chat = new GroupChatService(storage, new ObjectMapper()); + groups = mock(GroupsJpaRepository.class); + } + + @Test + void aCheckThatFailsLeavesTheHistoryAsItIs() { + // S3 throttled (503 Slow Down), failing (500), refusing (403) or out of reach: none of + // these says the file is missing. + List failures = List.of( + answered(503, "Slow Down"), + answered(500, "We encountered an internal error. Please try again."), + answered(403, "Access Denied"), + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + for (RuntimeException failure : failures) { + objects.clear(); + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", failure); + + assertDoesNotThrow(() -> startUp("CSA"), failure.toString()); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES), failure.toString()); + } + } + + @Test + void aCheckThatFailsIsLoggedWithTheGroupAndTheCause() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + RuntimeException throttle = answered(503, "Slow Down"); + failingChecks.put("CSA", throttle); + + try (Warnings warnings = new Warnings(StartupService.class)) { + startUp("CSA"); + + assertEquals(1, warnings.list().size(), warnings.messages().toString()); + ILoggingEvent warning = warnings.list().get(0); + assertTrue(warning.getFormattedMessage().contains("CSA"), warning.getFormattedMessage()); + assertEquals(throttle.getClass().getName(), warning.getThrowableProxy().getClassName()); + } + } + + @Test + void aGroupThatCantBeCheckedDoesNotStopTheOthers() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", answered(503, "Slow Down")); + + startUp("CSA", "CSP"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + assertEquals("", stored("CSP/messages-images/messages.jsonl")); + } + + @Test + void aGroupWithNoMessagesFileYetGetsAnEmptyOne() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + startUp("CSA"); + + assertEquals("", stored(CSA_MESSAGES)); + assertArrayEquals(new byte[0], objects.get("CSA/shared-files/")); + } + + @Test + void aGroupThatHasItsMessagesKeepsThem() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + + startUp("CSA"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + } + + @Test + void aServerWithoutS3StartsQuietly() { + // A local server without S3 settings stores nothing, so there's nothing to check. + chat = new GroupChatService(new S3FileHandler(), new ObjectMapper()); + + try (Warnings warnings = new Warnings(StartupService.class, GroupChatService.class, S3FileHandler.class)) { + assertDoesNotThrow(() -> startUp("CSA", "CSP")); + assertEquals(List.of(), warnings.messages()); + } + } + + @Test + void aMessageSentWhileTheCheckCreatesTheFileIsKept() throws Exception { + // The check finds no file, but S3's answer only arrives once a send has saved a + // message (or half a second passes). An empty file written after that would erase it. + CountDownLatch checking = new CountDownLatch(1); + CountDownLatch sendSaved = new CountDownLatch(1); + doAnswer(call -> { + String key = call.getArgument(0).key(); + boolean found = objects.containsKey(key); + if (CSA_MESSAGES.equals(key)) { + checking.countDown(); + sendSaved.await(500, TimeUnit.MILLISECONDS); + } + if (!found) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }).when(s3).headObject(any(HeadObjectRequest.class)); + doAnswer(call -> { + String key = call.getArgument(0).key(); + store(key, call.getArgument(1)); + if (CSA_MESSAGES.equals(key) && objects.get(key).length > 0) { + sendSaved.countDown(); + } + return PutObjectResponse.builder().build(); + }).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + Future send = pool.submit(() -> { + checking.await(5, TimeUnit.SECONDS); + return chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-22T08:00:00Z", null)); + }); + startUp("CSA"); + send.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + + assertEquals(List.of("Works for me"), + chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList()); + } + + /** Runs the server's start-up check over groups with these names. */ + private void startUp(String... groupNames) throws Exception { + List found = new ArrayList<>(); + for (String name : groupNames) { + Groups group = new Groups(); + group.setName(name); + found.add(group); + } + when(groups.findAll()).thenReturn(found); + new StartupService(groups, chat).initializeGroupStorage().run(new DefaultApplicationArguments()); + } + + private void store(String key, RequestBody body) throws Exception { + try (InputStream bytes = body.contentStreamProvider().newStream()) { + objects.put(key, bytes.readAllBytes()); + } + } + + private String stored(String key) { + byte[] bytes = objects.get(key); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + private static S3Exception answered(int status, String message) { + return (S3Exception) S3Exception.builder().statusCode(status).message(message).build(); + } + + private static S3Exception notFound() { + return (S3Exception) NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + + /** The warnings the given classes log while it's open. */ + private static final class Warnings implements AutoCloseable { + private final ListAppender appender = new ListAppender<>(); + private final List loggers = new ArrayList<>(); + private final List previousLevels = new ArrayList<>(); + + Warnings(Class... types) { + appender.start(); + for (Class type : types) { + Logger logger = (Logger) LoggerFactory.getLogger(type); + previousLevels.add(logger.getLevel()); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + loggers.add(logger); + } + } + + List list() { + return List.copyOf(appender.list); + } + + List messages() { + return list().stream().map(ILoggingEvent::getFormattedMessage).toList(); + } + + @Override + public void close() { + for (int i = 0; i < loggers.size(); i++) { + loggers.get(i).detachAppender(appender); + loggers.get(i).setLevel(previousLevels.get(i)); + } + appender.stop(); + } + } +} From f34470635af9fcb68cd4050b148d0f741143c6c9 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:21:35 -0800 Subject: [PATCH 20/32] Group chat: a send whose read times out answers 503 like a shared file S3's RequestTimeout comes as a 400, but it means the connection was too slow, and the AWS SDK retries it like a 5xx. The shared-file check and write already count it as S3 being unavailable (isUnavailable), but the send's strict read had its own rule that only counted a 5xx, so a timed-out read got the route's 400 instead of a 503 with Retry-After. The read now uses isUnavailable too, so one check decides it for the whole group chat. The history was kept either way: only the status was wrong. The send test adds a RequestTimeout to the failures that answer 503. --- docs/group-chat-architecture.md | 2 +- .../com/open/spring/mvc/groups/GroupChatService.java | 7 +++---- .../com/open/spring/mvc/groups/GroupChatSendTest.java | 10 ++++++++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a02faa71..8801b33e 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -156,7 +156,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **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. ## Testing diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index afc92eee..d49755a6 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -104,9 +104,8 @@ public List getMessages(String groupName) { /** * The group's messages for a send, which writes the whole file back. Strict: a read that * failed throws rather than reading as an empty chat, which the send would save over the - * history. Only S3's 404 means no messages yet. S3 out of reach or answering a 5xx is - * something to wait out, so that throws MessagesReadFailedException; anything else goes up - * as it is. + * history. Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesReadFailedException; anything else goes up as it is. */ private List readMessagesOrThrow(String groupName) { String base64Data; @@ -115,7 +114,7 @@ private List readMessagesOrThrow(String groupName) { } catch (SdkClientException | S3Exception e) { // Logged for every failure: the route answers a refused read without logging it. log.warn("Could not read the messages of group {}", groupName, e); - if (e instanceof S3Exception answered && answered.statusCode() < 500) { + if (!isUnavailable(e)) { // S3 refused the request (no permission, a bad key): waiting won't fix that. throw e; } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index 05c32271..56c6b6bc 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -37,6 +37,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; @@ -134,10 +135,15 @@ private String storedMessages() { @Test void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { - // S3 throttled (503 Slow Down) or out of reach: failures that clear if you wait. + // S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + // comes as a 400): failures that clear if you wait. List failures = List.of( (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), - SdkClientException.create("Unable to execute HTTP request: Read timed out")); + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); for (RuntimeException failure : failures) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); From 1bc72b0171b8b16e706f6005e80c6559b1d953e0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:07:21 -0800 Subject: [PATCH 21/32] Group chat docs: the start-up check writes only over a missing file The storage notes now say StartupService creates a group's empty messages file and shared-files/ placeholder only when S3 answers 404 (fileExistsOrThrow). Any other failure to check is logged and leaves that group as it is, the other groups are still checked, the check holds the group's message lock, and a server without S3 settings checks nothing. The testing list gets a bullet for StartupServiceTest, with its command. --- docs/group-chat-architecture.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 2ed3e467..67f977ad 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -155,6 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. +- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **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. @@ -165,6 +166,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - 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. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. +- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. ## Known issues From 6a48a1428dbfa393760f2ff3136ad6aff8731c13 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:26:21 -0800 Subject: [PATCH 22/32] Group files: note that a write that timed out may still be stored S3 can store a shared file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a sendFileServer frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. Nothing is lost, and the old 500 ended the same way. Recognizing "this stored file is mine" on a retry would need a way to match the stored copy to the upload, so for now the doc and a comment at the write say what happens. --- docs/group-chat-architecture.md | 1 + src/main/java/com/open/spring/mvc/groups/GroupChatService.java | 2 ++ 2 files changed, 3 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 8801b33e..a5036c49 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -158,6 +158,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **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. +- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. ## Testing diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index d49755a6..e64d59e0 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -353,6 +353,8 @@ private String store(String groupName, String path, String base64Data) { try { return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer). Sharing it again + // then gets a 409, which the page handles like any other taken name. log.warn("Could not store {} in group {}", path, groupName, e); if (isUnavailable(e)) { throw new SharedFileStorageUnavailableException(path, e); From a8f1c657bc0bf143f88d19563f1c2fd7b633f4ce Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:55:32 -0800 Subject: [PATCH 23/32] Group chat: a send, edit or delete answers 503 when S3 can't save it Sending, editing and deleting a message each read the group's messages file and save it back. The save used S3FileHandler.uploadFile, which catches every failure and answers null, so when S3 throttled, timed out or couldn't be reached on the upload, the route still answered 200: a send showed live and was gone after a reload, and an edit or a delete came back after one. Edits and deletes also read with the lenient decodeFile, so a failed read answered an edit with 404 and a delete with 200 (and told the group it was deleted). All three now read with readMessagesOrThrow and save with a strict writeMessagesOrThrow (uploadFileOrThrow). S3 being unavailable on either (isUnavailable) throws MessagesStorageUnavailableException, the renamed MessagesReadFailedException, and the send, edit and delete routes answer 503 with Retry-After. Nothing is broadcast. S3 refusing the request or a bug here still gets the route's usual 400, and the strict read now logs every failure, a bug included, the way the save does. Without S3 settings nothing is saved, and the chat still works live. A save that timed out may still be stored, so a send tried again can show up twice. That's easier to see than a message lost quietly. Tests: GroupChatSendTest adds an upload that fails after a good read, and GroupChatEditDeleteTest covers edits and deletes whose read or upload fails, that both still save when S3 is up, and that every failed read or upload is logged. The S3 failure lists move to S3Failures. GroupChatServiceTest, GroupChatMessageJsonTest and GroupChatRegressionTest now stand in for a configured S3 through the strict read and write; the regression test saves each upload back into its list, so its checks on what's stored can still fail. --- .../mvc/groups/GroupChatApiController.java | 27 +- .../spring/mvc/groups/GroupChatService.java | 77 +++--- .../groups/MessagesReadFailedException.java | 14 - .../MessagesStorageUnavailableException.java | 15 ++ .../mvc/groups/GroupChatEditDeleteTest.java | 241 ++++++++++++++++++ .../mvc/groups/GroupChatMessageJsonTest.java | 3 +- .../mvc/groups/GroupChatRegressionTest.java | 68 ++++- .../spring/mvc/groups/GroupChatSendTest.java | 57 +++-- .../mvc/groups/GroupChatServiceTest.java | 10 +- .../open/spring/mvc/groups/S3Failures.java | 35 +++ 10 files changed, 461 insertions(+), 86 deletions(-) delete mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java create mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/S3Failures.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 fcc528e3..08f5aca8 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -39,8 +39,8 @@ public class GroupChatApiController { // How long to wait before trying again when S3 was unavailable for a moment, checking or - // writing a shared file or reading a group's messages: a throttle or a short outage clears - // in seconds. + // writing a shared file or reading or saving a group's messages: a throttle or a short + // outage clears in seconds. private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; @@ -193,12 +193,8 @@ public ResponseEntity postMessage( try { realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); - } catch (MessagesReadFailedException ex) { - // S3 couldn't read the history, so nothing was saved or broadcast: saving would have - // replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when. - return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) - .body(ex.getMessage()); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -232,6 +228,8 @@ public ResponseEntity editMessage( updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -262,6 +260,8 @@ public ResponseEntity deleteMessage( realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -269,6 +269,17 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.OK); } + /** + * S3 couldn't read or save the group's messages, so the change isn't broadcast (a save that + * timed out may still be stored). That's S3 being unavailable for a moment, not a bug here: + * a 503, and when to try again. + */ + private static ResponseEntity tryAgainLater(MessagesStorageUnavailableException ex) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); + } + /** * 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/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index e64d59e0..9486c094 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -102,27 +102,56 @@ public List getMessages(String groupName) { } /** - * The group's messages for a send, which writes the whole file back. Strict: a read that - * failed throws rather than reading as an empty chat, which the send would save over the - * history. Only S3's 404 means no messages yet. S3 being unavailable for a moment (see - * isUnavailable) throws MessagesReadFailedException; anything else goes up as it is. + * The group's messages for a send, an edit or a delete, which write the whole file back. + * Strict: a read that failed throws rather than reading as an empty chat, which a send would + * save over the history and an edit or delete would answer as "not found". Only S3's 404 + * means no messages yet. S3 being unavailable for a moment (see isUnavailable) throws + * MessagesStorageUnavailableException; anything else goes up as it is. */ private List readMessagesOrThrow(String groupName) { String base64Data; try { base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); - } catch (SdkClientException | S3Exception e) { - // Logged for every failure: the route answers a refused read without logging it. + } catch (RuntimeException e) { + // Logged for every failure: the route answers a refused read or a bug without logging it. log.warn("Could not read the messages of group {}", groupName, e); if (!isUnavailable(e)) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. throw e; } - throw new MessagesReadFailedException(e); + throw new MessagesStorageUnavailableException(e); } return parseMessages(groupName, base64Data); } + /** + * Saves the group's whole messages file. Strict: a write that failed throws, so a send, an + * edit or a delete isn't answered as saved when it wasn't. S3 being unavailable for a moment + * (see isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as + * it is. Without S3 settings nothing is stored, and the chat still works live. + */ + private void writeMessagesOrThrow(String groupName, List messages) { + if (!s3FileHandler.isConfigured()) { + return; + } + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); + String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + try { + s3FileHandler.uploadFileOrThrow(base64Data, MESSAGES_FILE, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer), so a send tried + // again can show up twice. That's easier to see and fix than a message lost quietly. + log.warn("Could not save the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + } + private List parseMessages(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); @@ -164,15 +193,7 @@ public List addMessage(String groupName, GroupChatMessage mess synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); messages.add(message); - - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); return messages; } } @@ -185,7 +206,7 @@ public List addMessage(String groupName, GroupChatMessage mess public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); boolean found = false; for (GroupChatMessage m : messages) { if (messageId.equals(m.getId())) { @@ -200,14 +221,7 @@ public boolean editMessage(String groupName, String messageId, String newMessage } if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); } return found; } @@ -217,7 +231,7 @@ public boolean editMessage(String groupName, String messageId, String newMessage public void deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); GroupChatMessage target = messages.stream() .filter(m -> messageId.equals(m.getId())) @@ -231,14 +245,7 @@ public void deleteMessage(String groupName, String messageId, String requesterUi boolean removed = messages.remove(target); if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); } } } diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java deleted file mode 100644 index f74fcda8..00000000 --- a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't read a group's messages for now: it timed out, couldn't be reached or answered - * with a 5xx (a throttle, an outage). A send writes the whole messages file back, so it's refused - * rather than save the new message over the history, and the API answers 503 with Retry-After, - * since S3 being unavailable for a moment isn't a bug in this server. - */ -public class MessagesReadFailedException extends RuntimeException { - - public MessagesReadFailedException(Throwable cause) { - super("Could not read this group's messages, so the message was not sent. Try again in a moment.", cause); - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java new file mode 100644 index 00000000..93274a54 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java @@ -0,0 +1,15 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read or save a group's messages for now: it timed out, couldn't be reached or + * answered with a 5xx (a throttle, an outage). Sending, editing and deleting a message each read + * the whole messages file and write it back, so the change is refused rather than half done, and + * the API answers 503 with Retry-After, since S3 being unavailable for a moment isn't a bug in + * this server. + */ +public class MessagesStorageUnavailableException extends RuntimeException { + + public MessagesStorageUnavailableException(Throwable cause) { + super("Could not save this change to the group's chat right now. Try again in a moment.", cause); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java new file mode 100644 index 00000000..2718c2f0 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -0,0 +1,241 @@ +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +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.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +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.http.HttpHeaders; +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 ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +/** + * Editing and deleting a message read the group's whole messages file, change it and write the + * file back. When S3 can't do either for a moment, the route must say so (503) instead of + * answering as if the change was saved. + */ +class GroupChatEditDeleteTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** Grace's message in a bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404. */ + private void useFreshStorage() { + objects.clear(); + objects.put(MESSAGES_KEY, GRACE_LINE.getBytes(StandardCharsets.UTF_8)); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity edit() { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage("Meeting at 3"); + return controller.editMessage(7L, "m2", request); + } + + private ResponseEntity delete() { + return controller.deleteMessage(7L, "m2"); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + /** S3 fails the read of the messages file, or the upload after it. */ + private void failS3(boolean onRead, RuntimeException failure) { + if (onRead) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } else { + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + } + + /** S3 failing for a moment, on the read or the upload, gets a 503 with Retry-After and changes nothing. */ + private void assertRefusedForNow(Supplier> change) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + failS3(onRead, failure); + String what = (onRead ? "read: " : "upload: ") + failure; + + ResponseEntity response = change.get(); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), what + ", Retry-After: " + retryAfter); + assertEquals(GRACE_LINE, storedMessages(), what); + // The group isn't told about a change that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + + @Test + void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { + assertEquals(HttpStatus.OK, edit().getStatusCode()); + GroupChatMessage saved = new ObjectMapper().readValue(storedMessages(), GroupChatMessage.class); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + + assertEquals(HttpStatus.OK, delete().getStatusCode()); + assertEquals("", storedMessages()); + } + + @Test + void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { + assertRefusedForNow(this::edit); + } + + @Test + void aDeleteS3CantReadOrSaveForAMomentAnswers503AndKeepsTheMessage() { + assertRefusedForNow(this::delete); + } + + @Test + void anEditOrDeleteS3RefusesOrABugHereIsNotOfferedARetry() { + List>> changes = List.of(this::edit, this::delete); + for (Supplier> change : changes) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + failS3(onRead, fault); + String what = (onRead ? "read: " : "upload: ") + fault; + + ResponseEntity response = change.get(); + + assertFalse(response.getStatusCode().is2xxSuccessful(), what); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), what); + assertEquals(GRACE_LINE, storedMessages(), what); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + } + + @Test + void everyReadOrUploadThatFailsIsLoggedWithTheGroupAndTheCause() { + Logger logger = (Logger) LoggerFactory.getLogger(GroupChatService.class); + ListAppender warnings = new ListAppender<>(); + warnings.start(); + logger.addAppender(warnings); + try { + List failures = new ArrayList<>(S3Failures.unavailable()); + failures.addAll(S3Failures.refusalsAndBugs()); + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : failures) { + useFreshStorage(); + failS3(onRead, failure); + warnings.list.clear(); + + edit(); + + String what = (onRead ? "read: " : "upload: ") + failure; + // The route answers some of these without logging, so the service logs each one. + assertTrue(warnings.list.stream().anyMatch(warning -> + warning.getFormattedMessage().contains("CSA") + && warning.getThrowableProxy() != null + && failure.getClass().getName().equals(warning.getThrowableProxy().getClassName())), + what + " was not logged: " + warnings.list); + } + } + } finally { + logger.detachAppender(warnings); + warnings.stop(); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java index 943a977e..068ed7cf 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,6 +54,7 @@ void messageIsWrittenWithAuthorNotName() throws Exception { @Test void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { S3FileHandler s3 = mock(S3FileHandler.class); + when(s3.isConfigured()).thenReturn(true); when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); @@ -61,7 +62,7 @@ void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { service.addMessage("CSA", new GroupChatMessage("Grace Hopper", "hop", "hello", "2026-10-30T17:00:00Z", null)); ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); - verify(s3).uploadFile(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); + verify(s3).uploadFileOrThrow(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); String[] lines = new String(Base64.getDecoder().decode(uploaded.getValue()), StandardCharsets.UTF_8).split("\n"); assertEquals("Ada Lovelace", objectMapper.readTree(lines[0]).get("author").asText()); assertEquals("Grace Hopper", objectMapper.readTree(lines[1]).get("author").asText()); 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..4959583f 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -13,14 +14,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; 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.messaging.simp.SimpMessagingTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -32,6 +37,8 @@ import com.open.spring.mvc.person.PersonJpaRepository; class GroupChatRegressionTest { + private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; + private S3FileHandler storage; private GroupChatService chat; private GroupsJpaRepository groups; @@ -74,6 +81,49 @@ void setUp() { "2026-10-30T00:00:00Z", null); messages = new ArrayList<>(List.of(message)); doReturn(messages).when(chat).getMessages("CSA"); + // Edits and deletes read the messages file strictly and save it back, so S3 stands in + // for both: a read answers what's in `messages` at that moment, and a save replaces it. + when(storage.isConfigured()).thenReturn(true); + when(storage.decodeFileOrThrow("CSA", MESSAGES_FILE)).thenAnswer(call -> jsonlBase64(messages)); + doAnswer(call -> { + List saved = parse(call.getArgument(0)); + messages.clear(); + messages.addAll(saved); + return MESSAGES_FILE; + }).when(storage).uploadFileOrThrow(anyString(), eq(MESSAGES_FILE), eq("CSA")); + } + + private String jsonlBase64(List stored) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = stored.stream().map(m -> { + try { + return json.writeValueAsString(m); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }).collect(Collectors.joining("\n")); + return Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + } + + /** The messages each save wrote, in order. */ + private List> saves(int expected) throws Exception { + ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); + verify(storage, times(expected)).uploadFileOrThrow(uploaded.capture(), eq(MESSAGES_FILE), eq("CSA")); + List> saves = new ArrayList<>(); + for (String base64 : uploaded.getAllValues()) { + saves.add(parse(base64)); + } + return saves; + } + + private static List parse(String base64) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8); + List saved = new ArrayList<>(); + for (String line : jsonl.split("\n")) { + if (!line.isBlank()) saved.add(json.readValue(line, GroupChatMessage.class)); + } + return saved; } @AfterEach @@ -82,18 +132,20 @@ void clearAuthentication() { } @Test - void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() { + void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() throws Exception { person.setName("Renamed Owner"); signIn("owner"); GroupChatMessage request = new GroupChatMessage(); request.setMessage("updated"); assertEquals(HttpStatus.OK, controller.editMessage(7L, message.getId(), request).getStatusCode()); - assertEquals("updated", message.getMessage()); - assertTrue(message.isEdited()); assertEquals(HttpStatus.OK, controller.deleteMessage(7L, message.getId()).getStatusCode()); + List> saves = saves(2); + assertEquals(1, saves.get(0).size()); + assertEquals("updated", saves.get(0).get(0).getMessage()); + assertTrue(saves.get(0).get(0).isEdited()); + assertTrue(saves.get(1).isEmpty()); assertTrue(messages.isEmpty()); - verify(storage, times(2)).uploadFile(anyString(), eq("messages-images/messages.jsonl"), eq("CSA")); } @Test @@ -104,9 +156,9 @@ void sameDisplayNameDoesNotAuthorizeAnotherAccount() { assertEquals(HttpStatus.FORBIDDEN, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, controller.deleteMessage(7L, message.getId()).getStatusCode()); - assertEquals("original", message.getMessage()); assertEquals(1, messages.size()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + assertEquals("original", messages.get(0).getMessage()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -117,7 +169,7 @@ void unauthenticatedRequestsCannotEditOrDelete() { assertEquals(HttpStatus.UNAUTHORIZED, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.UNAUTHORIZED, controller.deleteMessage(7L, message.getId()).getStatusCode()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -128,7 +180,7 @@ void missingAuthorUidDoesNotFallBackToDisplayName() { () -> chat.editMessage("CSA", message.getId(), "updated", "owner")); assertThrows(SecurityException.class, () -> chat.deleteMessage("CSA", message.getId(), "owner")); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index 56c6b6bc..a8b36d3d 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -37,9 +37,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; -import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; @@ -47,7 +45,6 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; /** * Sending a message reads the group's whole messages file, adds the message and writes the @@ -133,18 +130,10 @@ private String storedMessages() { return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); } + @Test void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { - // S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout - // comes as a 400): failures that clear if you wait. - List failures = List.of( - (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), - SdkClientException.create("Unable to execute HTTP request: Read timed out"), - (S3Exception) S3Exception.builder().statusCode(400) - .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) - .message("Your socket connection to the server was not read from or written to within the timeout period.") - .build()); - for (RuntimeException failure : failures) { + for (RuntimeException failure : S3Failures.unavailable()) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); @@ -162,11 +151,7 @@ void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { @Test void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { - // No permission, a bad key, or a fault in this server: waiting won't fix these. - List faults = List.of( - (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), - new NullPointerException("a bug here, not S3")); - for (RuntimeException fault : faults) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); doThrow(fault).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); @@ -181,6 +166,42 @@ void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { } } + @Test + void anUploadThatFailsForAMomentRefusesTheSendWithA503AndKeepsTheHistory() { + // The read works, and then S3 can't take the upload for a moment. + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // A message that wasn't saved isn't shown to the group as sent. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + @Test void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { // S3's 404: nothing is stored yet, so there's no history to lose. diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java index 97ce7cc1..be0dd3c0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -40,8 +40,14 @@ static class OverlappingReads extends S3FileHandler { final Map objects = new ConcurrentHashMap<>(); final CountDownLatch bothReading = new CountDownLatch(2); + // A configured S3 whose writes never fail. @Override - public String uploadFile(String base64Data, String filename, String uid) { + public boolean isConfigured() { + return true; + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { objects.put(uid + "/" + filename, base64Data); return filename; } @@ -58,7 +64,7 @@ public String decodeFile(String uid, String filename) { return copy; } - // Its reads never fail, so a send's strict read is the same read. + // Its reads never fail, so the strict read a change makes is the same read. @Override public String decodeFileOrThrow(String uid, String filename) { return decodeFile(uid, filename); diff --git a/src/test/java/com/open/spring/mvc/groups/S3Failures.java b/src/test/java/com/open/spring/mvc/groups/S3Failures.java new file mode 100644 index 00000000..344b77e8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/S3Failures.java @@ -0,0 +1,35 @@ +package com.open.spring.mvc.groups; + +import java.util.List; + +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** The S3 failures the group chat tests throw from a stand-in S3 client. */ +final class S3Failures { + + private S3Failures() { + } + + /** + * S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + * comes as a 400): failures that clear if you wait. + */ + static List unavailable() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + } + + /** No permission, a bad key, or a fault in this server: waiting won't fix these. */ + static List refusalsAndBugs() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + } +} From ee2af1939b08823c7edb2b34fc714e11881f40a9 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:55:32 -0800 Subject: [PATCH 24/32] Group chat docs: sends, edits and deletes save their messages strictly The send, edit and delete routes now list their 503 with Retry-After, and that a save which timed out may still be stored. The storage note says all three read and save the messages file strictly (MessagesStorageUnavailableException), a new note says a save that timed out may still be stored, so a send tried again can show up twice, and the testing list names GroupChatEditDeleteTest. --- docs/group-chat-architecture.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a5036c49..07a6536a 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,9 +132,9 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | 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) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | 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 | @@ -156,9 +156,10 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **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. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit or delete tried again makes the same change, so it lands once. ## Testing @@ -169,6 +170,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. +- `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. ## Known issues From 258b8f6edd0fdeb54c882b26394735172eaf721e Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:01:33 -0800 Subject: [PATCH 25/32] Group chat: a send or edit answers with the messages it saved After a send or an edit worked, the route read the group's messages file again with the lenient getMessages and answered with that. If S3 failed on that second read, decodeFile answered null and the route answered 200 with an empty list. The Messages page uses that list to show the sender's own message when its socket missed the frame, so they could see nothing and send again. Every send and edit also read the same S3 file twice. publishMessage now returns the list addMessage saved, and editMessage returns the saved list, or nothing when no message has that id (still a 404). The routes answer with that list and don't read the file again. Tests: a send and an edit whose save works, with every S3 read after it failing, answer with exactly what they saved. --- .../mvc/groups/GroupChatApiController.java | 20 ++++++------- .../mvc/groups/GroupChatRealtimeService.java | 23 ++++++++------- .../spring/mvc/groups/GroupChatService.java | 19 +++++++------ .../mvc/groups/GroupChatEditDeleteTest.java | 24 ++++++++++++++++ .../spring/mvc/groups/GroupChatSendTest.java | 28 +++++++++++++++++++ 5 files changed, 84 insertions(+), 30 deletions(-) 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 08f5aca8..589e6209 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -191,17 +191,16 @@ public ResponseEntity postMessage( return new ResponseEntity<>("name and message are required", HttpStatus.BAD_REQUEST); } + // Answered from what was saved: a second read could fail and answer an empty chat. + List saved; try { - realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + saved = realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); } catch (MessagesStorageUnavailableException ex) { return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - - String groupName = groupOpt.get().getName(); - List updated = groupChatService.getMessages(groupName); - return new ResponseEntity<>(updated, HttpStatus.OK); + return new ResponseEntity<>(saved, HttpStatus.OK); } @PatchMapping("/{groupId}/messages/{messageId}") @@ -223,9 +222,9 @@ public ResponseEntity editMessage( return new ResponseEntity<>("message is required", HttpStatus.BAD_REQUEST); } - boolean updated; + Optional> saved; try { - updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); + saved = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } catch (MessagesStorageUnavailableException ex) { @@ -233,13 +232,10 @@ public ResponseEntity editMessage( } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - if (!updated) { + if (saved.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - - String groupName = groupOpt.get().getName(); - List messages = groupChatService.getMessages(groupName); - return new ResponseEntity<>(messages, HttpStatus.OK); + return new ResponseEntity<>(saved.get(), HttpStatus.OK); } @DeleteMapping("/{groupId}/messages/{messageId}") 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 bac95d70..873f5f0f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,6 +1,7 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -24,7 +25,8 @@ public class GroupChatRealtimeService { private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; - public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { + /** Saves the message, tells the group, and returns the group's messages as saved. */ + public List publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); if ((message == null || message.isBlank()) && (image == null || image.isBlank())) { @@ -34,7 +36,7 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, String date = Instant.now().toString(); GroupChatMessage persisted = new GroupChatMessage(identity.getDisplayName(), identity.getUid(), message, date, image); - groupChatService.addMessage(group.getName(), persisted); + List saved = groupChatService.addMessage(group.getName(), persisted); GroupChatEvent event = GroupChatEvent.builder() .context("sendMessageServer") @@ -47,18 +49,19 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, .build(); broadcastToGroup(groupId, event); - return event; + return saved; } /** - * Returns whether the message existed (and was broadcast as edited). Throws - * {@link SecurityException} if the authenticated requester's uid is not the author uid. + * Edits the message, tells the group, and returns the group's messages as saved, or nothing + * when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester's uid is not the author uid. */ - public boolean editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { + public Optional> editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { Groups group = getGroupOrThrow(groupId); - boolean updated = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); - if (!updated) { - return false; + Optional> saved = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); + if (saved.isEmpty()) { + return saved; } GroupChatEvent event = GroupChatEvent.builder() @@ -71,7 +74,7 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St .build(); broadcastToGroup(groupId, event); - return true; + return saved; } /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 9486c094..c1e60ca3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -199,12 +200,13 @@ public List addMessage(String groupName, GroupChatMessage mess } /** - * Returns whether a message with that id was found (and updated) in this group. - * Throws {@link SecurityException} unless the authenticated requester's uid matches - * the stored author uid. Legacy messages without an author uid cannot be edited. + * Edits a message and returns the group's messages as saved, or nothing when no message + * with that id is in this group. Throws {@link SecurityException} unless the authenticated + * requester's uid matches the stored author uid. Legacy messages without an author uid + * cannot be edited. */ - public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { - if (messageId == null) return false; + public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { + if (messageId == null) return Optional.empty(); synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); boolean found = false; @@ -220,10 +222,11 @@ public boolean editMessage(String groupName, String messageId, String newMessage } } - if (found) { - writeMessagesOrThrow(groupName, messages); + if (!found) { + return Optional.empty(); } - return found; + writeMessagesOrThrow(groupName, messages); + return Optional.of(messages); } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java index 2718c2f0..b76e3ab0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -19,6 +20,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; @@ -175,6 +177,28 @@ void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { assertEquals("", storedMessages()); } + @Test + void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + // The first read of S3 works, and every read after it fails as a throttle. + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = edit(); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List answered = (List) response.getBody(); + assertEquals(1, answered.size(), "answered: " + answered); + GroupChatMessage saved = (GroupChatMessage) answered.get(0); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + } + @Test void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { assertRefusedForNow(this::edit); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index a8b36d3d..f8e71a46 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -7,6 +7,7 @@ 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.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -19,6 +20,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -125,6 +127,18 @@ private ResponseEntity send(String text) { return controller.postMessage(7L, request); } + /** The first read of S3 works, and every read after it fails as a throttle. */ + private void failReadsAfterTheFirst() { + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } + private String storedMessages() { byte[] bytes = objects.get(MESSAGES_KEY); return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); @@ -202,6 +216,20 @@ void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { } } + @Test + void aSendAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failReadsAfterTheFirst(); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List texts = ((List) response.getBody()).stream() + .map(saved -> ((GroupChatMessage) saved).getMessage()) + .toList(); + assertEquals(List.of("Meeting at 3", "Works for me"), texts); + } + @Test void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { // S3's 404: nothing is stored yet, so there's no history to lose. From 320171c1b6bcb45db1439938d4fcfc8e35d98852 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:03:02 -0800 Subject: [PATCH 26/32] Group chat: a delete of a message that isn't saved answers 404 and tells no one Deleting a message that wasn't in the group's messages file returned quietly, and the route still broadcast deleteMessageServer to the whole group and answered 200. The ownership check only runs on a saved message, so any signed-in account could take any message off everyone's screen by sending its id. On a server without S3 settings, where nothing is saved, that worked for every live message. deleteMessage now returns whether a message with that id was removed. The realtime service only broadcasts when it was, and the route answers 404 otherwise, like an edit of an unknown id. Tests: a delete of an id that isn't saved, and any delete on a server without S3 settings, answer 404 and broadcast nothing. --- .../mvc/groups/GroupChatApiController.java | 7 ++++-- .../mvc/groups/GroupChatRealtimeService.java | 14 ++++++++--- .../spring/mvc/groups/GroupChatService.java | 19 +++++++------- .../mvc/groups/GroupChatEditDeleteTest.java | 25 +++++++++++++++++++ 4 files changed, 51 insertions(+), 14 deletions(-) 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 589e6209..a6f6937f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -252,8 +252,9 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + boolean deleted; try { - realtimeService.deleteMessage(groupId, messageId, identity.getUid()); + deleted = realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } catch (MessagesStorageUnavailableException ex) { @@ -261,7 +262,9 @@ public ResponseEntity deleteMessage( } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - + if (!deleted) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } return new ResponseEntity<>(HttpStatus.OK); } 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 873f5f0f..1242ac5d 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -77,10 +77,17 @@ public Optional> editMessage(Long groupId, String message return saved; } - /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ - public void deleteMessage(Long groupId, String messageId, String requesterUid) { + /** + * Deletes the message and tells the group, or returns false and tells no one when the + * message isn't in this group. Throws {@link SecurityException} if the authenticated + * requester didn't send it. + */ + public boolean deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); - groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + if (!groupChatService.deleteMessage(group.getName(), messageId, requesterUid)) { + // Telling the group about a message that isn't saved would take it off everyone's screen. + return false; + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -90,6 +97,7 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { .build(); broadcastToGroup(groupId, event); + return true; } /** diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index c1e60ca3..9b9da570 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -230,9 +230,12 @@ public Optional> editMessage(String groupName, String mes } } - /** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */ - public void deleteMessage(String groupName, String messageId, String requesterUid) { - if (messageId == null) return; + /** + * Deletes a message and returns whether one with that id was in this group. Same ownership + * rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. + */ + public boolean deleteMessage(String groupName, String messageId, String requesterUid) { + if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); @@ -240,16 +243,14 @@ public void deleteMessage(String groupName, String messageId, String requesterUi .filter(m -> messageId.equals(m.getId())) .findFirst() .orElse(null); - if (target == null) return; + if (target == null) return false; if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { throw new SecurityException("Not the message sender"); } - boolean removed = messages.remove(target); - - if (removed) { - writeMessagesOrThrow(groupName, messages); - } + messages.remove(target); + writeMessagesOrThrow(groupName, messages); + return true; } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java index b76e3ab0..16f5cefe 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -100,7 +100,11 @@ private void useFreshStorage() { S3FileHandler storage = new S3FileHandler(); ReflectionTestUtils.setField(storage, "s3Client", s3); ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + /** The edit and delete routes over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); @@ -199,6 +203,27 @@ void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { assertTrue(saved.isEdited()); } + @Test + void aDeleteOfAMessageThatIsntSavedAnswers404AndTellsNoOne() { + ResponseEntity response = controller.deleteMessage(7L, "not-a-saved-id"); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(GRACE_LINE, storedMessages()); + // Telling the group would take the message off everyone's screen. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void withoutS3SettingsADeleteAnswers404AndTellsNoOne() { + // A local server without S3 saves nothing, so there's no message to delete, whoever sent it. + wire(new S3FileHandler()); + + ResponseEntity response = delete(); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + @Test void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { assertRefusedForNow(this::edit); From 1cc55364107ae4f1994b7315412f2863432b6dc7 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:08:12 -0800 Subject: [PATCH 27/32] Group chat: a line that doesn't read as a message is kept when the file is saved parseMessages skipped a line of the messages file that didn't read as a message, and the next send, edit or delete wrote the file back without it, so one bad line was gone for good. toJson answered "{}" for a message it couldn't write, which replaced that message in the file with nothing. A send, an edit and a delete now read the file as MessagesLine entries: a message, or a line that didn't read as one, kept as it was. The save writes each message as JSON and each unreadable line back in its place, and loading the chat still leaves unreadable lines out. A message that can't be written now throws, so the change is refused and the file stays as it was; the log line names the message's id instead of printing its text. Tests: GroupChatMessagesFileTest keeps an unreadable line in place through a send, an edit and a delete, leaves it out when the chat loads, and refuses a message that can't be written without touching the file. --- .../spring/mvc/groups/GroupChatService.java | 121 +++++++++------ .../mvc/groups/GroupChatMessagesFileTest.java | 144 ++++++++++++++++++ 2 files changed, 215 insertions(+), 50 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 9b9da570..1e6bd635 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -103,13 +104,23 @@ public List getMessages(String groupName) { } /** - * The group's messages for a send, an edit or a delete, which write the whole file back. - * Strict: a read that failed throws rather than reading as an empty chat, which a send would - * save over the history and an edit or delete would answer as "not found". Only S3's 404 - * means no messages yet. S3 being unavailable for a moment (see isUnavailable) throws - * MessagesStorageUnavailableException; anything else goes up as it is. + * One line of a group's messages file: a message, or a line that didn't read as one, kept + * as it was so that saving the file again doesn't drop it. */ - private List readMessagesOrThrow(String groupName) { + private record MessagesLine(GroupChatMessage message, String unreadable) { + static MessagesLine of(GroupChatMessage message) { + return new MessagesLine(message, null); + } + } + + /** + * The group's messages file, line by line, for a send, an edit or a delete, which write the + * whole file back. Strict: a read that failed throws rather than reading as an empty chat, + * which a send would save over the history and an edit or delete would answer as "not + * found". Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + */ + private List readMessagesOrThrow(String groupName) { String base64Data; try { base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); @@ -122,21 +133,22 @@ private List readMessagesOrThrow(String groupName) { } throw new MessagesStorageUnavailableException(e); } - return parseMessages(groupName, base64Data); + return parseLines(groupName, base64Data); } /** - * Saves the group's whole messages file. Strict: a write that failed throws, so a send, an - * edit or a delete isn't answered as saved when it wasn't. S3 being unavailable for a moment - * (see isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as - * it is. Without S3 settings nothing is stored, and the chat still works live. + * Saves the group's whole messages file: each message as JSON, and each line that didn't + * read as a message as it was. Strict: a write that failed throws, so a send, an edit or a + * delete isn't answered as saved when it wasn't. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + * Without S3 settings nothing is stored, and the chat still works live. */ - private void writeMessagesOrThrow(String groupName, List messages) { + private void writeMessagesOrThrow(String groupName, List lines) { if (!s3FileHandler.isConfigured()) { return; } - String jsonl = messages.stream() - .map(this::toJson) + String jsonl = lines.stream() + .map(line -> line.message() != null ? toJson(line.message()) : line.unreadable()) .collect(Collectors.joining("\n")); String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); try { @@ -154,6 +166,24 @@ private void writeMessagesOrThrow(String groupName, List messa } private List parseMessages(String groupName, String base64Data) { + return messagesOf(parseLines(groupName, base64Data)); + } + + private static List messagesOf(List lines) { + return lines.stream() + .map(MessagesLine::message) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); + } + + private static GroupChatMessage find(List lines, String messageId) { + return messagesOf(lines).stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + } + + private List parseLines(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -171,31 +201,32 @@ private List parseMessages(String groupName, String base64Data return new ArrayList<>(); } - List messages = new ArrayList<>(); + List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new StringReader(jsonl))) { String line; while ((line = reader.readLine()) != null) { if (line.isBlank()) continue; try { - GroupChatMessage msg = objectMapper.readValue(line, GroupChatMessage.class); - messages.add(msg); + lines.add(MessagesLine.of(objectMapper.readValue(line, GroupChatMessage.class))); } catch (Exception e) { - log.warn("Skipping invalid message line for group {}: {}", groupName, line, e); + // Left out of the chat, but kept in the file: a save writes it back as it is. + log.warn("Keeping an unreadable message line of group {} as it is: {}", groupName, line, e); + lines.add(new MessagesLine(null, line)); } } } catch (Exception e) { log.warn("Failed reading messages for group {}", groupName, e); } - return messages; + return lines; } public List addMessage(String groupName, GroupChatMessage message) { synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - messages.add(message); - writeMessagesOrThrow(groupName, messages); - return messages; + List lines = readMessagesOrThrow(groupName); + lines.add(MessagesLine.of(message)); + writeMessagesOrThrow(groupName, lines); + return messagesOf(lines); } } @@ -208,25 +239,18 @@ public List addMessage(String groupName, GroupChatMessage mess public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return Optional.empty(); synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - boolean found = false; - for (GroupChatMessage m : messages) { - if (messageId.equals(m.getId())) { - if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } - m.setMessage(newMessage); - m.setEdited(true); - found = true; - break; - } - } - - if (!found) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) { return Optional.empty(); } - writeMessagesOrThrow(groupName, messages); - return Optional.of(messages); + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + target.setMessage(newMessage); + target.setEdited(true); + writeMessagesOrThrow(groupName, lines); + return Optional.of(messagesOf(lines)); } } @@ -237,19 +261,15 @@ public Optional> editMessage(String groupName, String mes public boolean deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - - GroupChatMessage target = messages.stream() - .filter(m -> messageId.equals(m.getId())) - .findFirst() - .orElse(null); + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); if (target == null) return false; if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { throw new SecurityException("Not the message sender"); } - messages.remove(target); - writeMessagesOrThrow(groupName, messages); + lines.removeIf(line -> line.message() == target); + writeMessagesOrThrow(groupName, lines); return true; } } @@ -496,8 +516,9 @@ private String toJson(GroupChatMessage message) { try { return objectMapper.writeValueAsString(message); } catch (Exception e) { - log.warn("Failed to serialize message: {}", message, e); - return "{}"; + // Writing "{}" instead would replace the message in the file with nothing. + log.warn("Could not write message {} of a group chat", message.getId(), e); + throw new IllegalStateException("Could not write message " + message.getId(), e); } } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java new file mode 100644 index 00000000..4bd46524 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java @@ -0,0 +1,144 @@ +package com.open.spring.mvc.groups; + +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 java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * A group's messages file can hold a line that doesn't read as a message, and a message can + * fail to be written. Neither may quietly lose a message when the file is saved again. + */ +class GroupChatMessagesFileTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + // A line that isn't a whole message: S3 holds it, but it doesn't read as JSON. + private static final String UNREADABLE = "{\"id\":\"m0\",\"author\":\"Ada Lovelace\",\"message\":\"Agenda for"; + + /** A configured S3 kept in a map, whose reads and writes never fail. */ + static class InMemoryS3 extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String decodeFile(String uid, String filename) { + return objects.get(uid + "/" + filename); + } + + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private InMemoryS3 storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new InMemoryS3(); + chat = new GroupChatService(storage, json); + } + + private void store(String... lines) { + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private List storedLines() { + String base64 = storage.objects.get(MESSAGES_KEY); + return List.of(new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8).split("\n")); + } + + private String text(String line) throws Exception { + return json.readValue(line, GroupChatMessage.class).getMessage(); + } + + @Test + void anUnreadableLineIsKeptWhereItWasWhenAMessageIsSent() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + chat.addMessage("CSA", new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-21T10:06:00Z", null)); + + List lines = storedLines(); + assertEquals(4, lines.size(), lines.toString()); + assertEquals("Meeting at 3", text(lines.get(0))); + assertEquals(UNREADABLE, lines.get(1)); + assertEquals("Meetign at 3", text(lines.get(2))); + assertEquals("Works for me", text(lines.get(3))); + } + + @Test + void anUnreadableLineIsKeptWhenAMessageIsEditedOrDeleted() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + assertTrue(chat.editMessage("CSA", "m2", "Meeting at 3", "grace").isPresent()); + List lines = storedLines(); + assertEquals(3, lines.size(), lines.toString()); + assertEquals(List.of("Meeting at 3", UNREADABLE, "Meeting at 3"), + List.of(text(lines.get(0)), lines.get(1), text(lines.get(2)))); + + assertTrue(chat.deleteMessage("CSA", "m1", "ada")); + lines = storedLines(); + assertEquals(2, lines.size(), lines.toString()); + assertEquals(UNREADABLE, lines.get(0)); + assertEquals("Meeting at 3", text(lines.get(1))); + } + + @Test + void loadingTheChatSkipsAnUnreadableLine() { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + List texts = chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList(); + + assertEquals(List.of("Meeting at 3", "Meetign at 3"), texts); + } + + @Test + void aMessageThatCantBeWrittenRefusesTheChangeAndKeepsTheFile() { + ObjectMapper failsOnOneMessage = new ObjectMapper() { + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + if (value instanceof GroupChatMessage message && "can't write me".equals(message.getMessage())) { + throw new JsonMappingException(null, "can't write this message"); + } + return super.writeValueAsString(value); + } + }; + chat = new GroupChatService(storage, failsOnOneMessage); + store(ADA_LINE); + + assertThrows(RuntimeException.class, () -> chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "can't write me", "2026-11-21T10:06:00Z", null))); + + assertEquals(List.of(ADA_LINE), storedLines()); + } +} From 8dfea9a83d4a207da842d570b8d18eb1440df64d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:01:33 -0800 Subject: [PATCH 28/32] Group chat docs: a send or edit returns the history as it was saved The send and edit routes now say they return the history as saved, the edit route lists its 404, and the testing list names the new checks. --- docs/group-chat-architecture.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 07a6536a..1fd87049 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,8 +132,8 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | -| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | @@ -171,6 +171,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. +- `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. ## Known issues From aac4ab9c88d9f9898172fd136dd85d000d60446f Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:03:02 -0800 Subject: [PATCH 29/32] Group chat docs: a delete of a message that isn't saved answers 404 The delete route lists its 404, the note on servers without S3 settings says edits and deletes answer 404 there, the note on saves that time out says a retried delete answers 404, and the testing list names the new checks. --- docs/group-chat-architecture.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1fd87049..7633261b 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -134,7 +134,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | | POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | -| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message; 404 when no message has that id, and then nothing is broadcast. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | 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 | @@ -154,12 +154,12 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. -- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. +- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty, and an edit or delete answers 404 since there's no message to change. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **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. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. -- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit or delete tried again makes the same change, so it lands once. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. ## Testing @@ -172,6 +172,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. - `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. +- `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. ## Known issues From d5c385288d6ef6a941f6d046c1c48b02f2570fcd Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:08:12 -0800 Subject: [PATCH 30/32] Group chat docs: a line that doesn't read as a message is kept A new note under Persistence says a send, edit or delete writes an unreadable line back as it was, loading leaves it out, and a message that can't be written refuses the change instead of being saved as {}. The testing list names GroupChatMessagesFileTest. --- docs/group-chat-architecture.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 7633261b..4601a166 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -160,6 +160,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **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. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. - **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. +- **A line that doesn't read as a message is kept.** Loading the chat leaves it out and logs a warning, and a send, edit or delete writes it back as it was (`MessagesLine` in `GroupChatService`), so one bad line isn't lost the next time the file is saved. A message that can't be written as JSON refuses the change, and the route gives its usual 400, instead of being saved as `{}`. ## Testing @@ -173,6 +174,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. - `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. - `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. +- `GroupChatMessagesFileTest` covers a line that doesn't read as a message, kept in place through a send, an edit and a delete and left out when the chat loads, and a message that can't be written. ## Known issues From 8fc7ef69ede86b24e2983744f03545203b432b96 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 26 Nov 2026 00:16:32 -0800 Subject: [PATCH 31/32] Group chat: a delete still tells the group when its reactions can't be removed By the time the reactions are removed, the message is already gone from S3. A database error there answered an error and told no one, and a retry found nothing to delete (404). Now the error is logged, the group still gets deleteMessageServer, and the leftover reactions are never shown. --- docs/group-chat-architecture.md | 2 +- .../mvc/groups/GroupChatRealtimeService.java | 12 +++++++++++- .../spring/mvc/groups/GroupChatReactionTest.java | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 8cf9e929..abd5ca3d 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -171,7 +171,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 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. +- 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. If the database can't remove them, the delete still goes through and is broadcast, the error is logged, and the leftover reactions are never shown. - 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/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 9f8d1c69..11c24a52 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; +import org.springframework.dao.DataAccessException; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; @@ -14,6 +15,7 @@ import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Service to handle the real-time publishing of group chat messages and presence events. @@ -21,6 +23,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class GroupChatRealtimeService { public static final String GROUP_TOPIC_PREFIX = "/topic/group/"; @@ -93,7 +96,14 @@ public boolean deleteMessage(Long groupId, String messageId, String requesterUid // Telling the group about a message that isn't saved would take it off everyone's screen. return false; } - reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + try { + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + } catch (DataAccessException e) { + // The message is already gone from S3, so the group still has to hear about it, and a + // retry would find nothing to delete. Its reactions stay in the table, where no message + // shows them. + log.warn("Could not remove the reactions of deleted message {} in group {}", messageId, groupId, e); + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") 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 d5d4d054..314a7ae0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -20,6 +21,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -174,6 +176,19 @@ void deletingAMessageThatIsntSavedKeepsItsReactions() { verify(reactionService, never()).removeAllFor(any(), any(), any()); } + @Test + void aDeleteStillTellsTheGroupWhenItsReactionsCantBeRemoved() { + doReturn(true).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.GROUP, 3L, MESSAGE_ID); + + assertTrue(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("deleteMessageServer", frame.getValue().getContext()); + } + @Test void onlyAReactionsFrameCarriesReactions() throws Exception { ObjectMapper json = new ObjectMapper(); From 6aa4b6a42e2d3086da006e7533230666dfd60c13 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 26 Nov 2026 00:21:27 -0800 Subject: [PATCH 32/32] Reactions: a DM delete no longer rolls back when its reactions can't be removed DirectMessageService.deleteMessage removed the message's reactions inside its own transaction, so any error from the reactions table, such as a missing message_reaction table under ddl-auto=none, rolled back the delete and sent no "deleted" frame. The reactions are now removed after the delete commits, and a failure there is logged. removeAllFor runs in a transaction of its own (REQUIRES_NEW), since Spring runs a transactional call made from afterCommit inside the finished transaction, where it would never commit. MessageReactionTableInitializer's comment now says what breaks without the table. --- docs/group-chat-architecture.md | 4 +-- .../directmessages/DirectMessageService.java | 19 ++++++++++++-- .../mvc/reactions/MessageReactionService.java | 8 ++++-- .../MessageReactionTableInitializer.java | 5 ++-- .../DirectMessageReactionTest.java | 25 +++++++++++++++++++ .../reactions/MessageReactionServiceTest.java | 14 +++++++++++ 6 files changed, 67 insertions(+), 8 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index abd5ca3d..2f76a451 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -171,7 +171,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 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. If the database can't remove them, the delete still goes through and is broadcast, the error is logged, and the leftover reactions are never shown. +- 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, a DM's once the delete commits. If the database can't remove them, the delete still goes through and is broadcast, and the error is logged. - 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`. @@ -180,7 +180,7 @@ 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 any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. -- 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. +- 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, the table's primary key on SQLite, and a delete whose reactions can't be removed. - 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. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. 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 3ab1b53b..dc82a598 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -8,6 +8,7 @@ import java.util.NoSuchElementException; import java.util.Set; +import org.springframework.dao.DataAccessException; import org.springframework.data.domain.PageRequest; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; @@ -22,6 +23,7 @@ import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Business logic for direct messages: finding/creating conversations, checking @@ -31,6 +33,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class DirectMessageService { public static final String DM_TOPIC_PREFIX = "/topic/dm/"; @@ -228,8 +231,10 @@ 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)); + // A tombstone shows no reactions, so none are kept for it. They're removed after the delete + // commits: an error from the reactions table inside this transaction would undo the delete. + Long conversationId = conversation.getId(); + afterCommit(() -> removeReactions(conversationId, messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -282,6 +287,16 @@ public List setReaction(DirectMessageCon } // Runs once the current transaction commits, or right away outside one. + /** Removes a deleted message's reactions. The delete is already done, so a failure is only logged. */ + private void removeReactions(Long conversationId, Long messageId) { + try { + reactionService.removeAllFor(ChatType.DM, conversationId, String.valueOf(messageId)); + } catch (DataAccessException e) { + log.warn("Could not remove the reactions of deleted message {} in conversation {}", + messageId, conversationId, e); + } + } + private static void afterCommit(Runnable action) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { 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 f498f897..afb8540c 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -91,8 +91,12 @@ public Map> forChat(ChatType type, Long chatId) { return result; } - /** Removes every reaction on a message, as when the message is deleted. */ - @Transactional + /** + * Removes every reaction on a message, as when the message is deleted. The chats call it once + * their delete is done (a DM's after its transaction commits), so it runs in a transaction of + * its own: a transactional call made from inside a finished transaction never commits. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) public void removeAllFor(ChatType type, Long chatId, String messageId) { repository.deleteAllOnMessage(type, chatId, 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 index a2cbdfad..a7412931 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -38,8 +38,9 @@ public ApplicationRunner migrateMessageReaction() { try { jdbcTemplate.execute(CREATE_TABLE); } catch (DataAccessException e) { - // 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. + // The rest of Spring keeps running, as it does when another table can't be made. + // Until the table exists the reaction routes fail, and deleting a message still + // works but logs that its reactions couldn't be removed. 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/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java index 01fcc894..04197e05 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -6,6 +6,7 @@ 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.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -20,6 +21,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -204,6 +206,29 @@ void deletingAMessageRemovesItsReactions() { verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); } + @Test + void aDeleteStillGoesThroughWhenItsReactionsCantBeRemoved() { + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + TransactionSynchronizationManager.initSynchronization(); + try { + service.deleteMessage(conversation, bob, 42L); + + // Nothing in the delete's own transaction touches the reactions, so they can't undo it. + verify(reactionService, never()).removeAllFor(any(), any(), any()); + assertTrue(message.isDeleted()); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("deleted", frame.getValue().getType()); + + // Once it commits they're removed, and a failure there is logged, not thrown at the caller. + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + @Test void onlyAReactionsFrameCarriesReactions() throws Exception { ObjectMapper json = new ObjectMapper(); 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 d14b7a4b..aa27a3c2 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -13,6 +13,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; @@ -154,4 +156,16 @@ private static Person person(long id, String uid, String name) { person.setName(name); return person; } + + @Test + void removingAMessagesReactionsCommitsOnItsOwn() throws Exception { + // Chats remove a deleted message's reactions after the delete commits. Spring runs a + // transactional call made then inside the finished transaction, where nothing commits, + // unless it asks for a new one. + Transactional transactional = MessageReactionService.class + .getMethod("removeAllFor", ChatType.class, Long.class, String.class) + .getAnnotation(Transactional.class); + + assertEquals(Propagation.REQUIRES_NEW, transactional.propagation()); + } }