diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..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, 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 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 @@ -163,6 +163,8 @@ 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. +- `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 @@ -173,7 +175,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 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 790db7d3..5f902092 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. @@ -74,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<>(); } @@ -112,18 +144,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 = readMessagesOrThrow(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 +167,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/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..05c32271 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,203 @@ +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); + // 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 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 new file mode 100644 index 00000000..97ce7cc1 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -0,0 +1,152 @@ +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; + } + + // 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(); + 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()); + } +} 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); + } + } +}