From 5b9931674d7ca23967842a7fad54c2f23bd4af2b Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:00:05 -0800 Subject: [PATCH 1/7] 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 af1dba22dec69a108b29bbca6215629d6eba0378 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:01:17 -0800 Subject: [PATCH 2/7] 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 bc79ac5997ad97cd3dfe98a328646b7c21713e96 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 3/7] 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 9a3bf22ba93a64a637c6a338d779d0a1bb38871c Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 4/7] 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 d9a74b42b7839aa292d0d4201a9c0ffc946ff5c7 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:21:35 -0800 Subject: [PATCH 5/7] 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 b30e611fa82f8cd983a1f0cb8617979ee7cef00d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:04:56 -0800 Subject: [PATCH 6/7] 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 1bc72b0171b8b16e706f6005e80c6559b1d953e0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:07:21 -0800 Subject: [PATCH 7/7] 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