diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..a5036c49 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 | @@ -140,7 +140,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/index` | Shared files as `[{path, size, uploadedBy, uploadedAt}]`, sorted by path, without bytes | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/content?path=` | One shared file's bytes (`application/octet-stream`, named by the last part of its path); 400 for a path that isn't valid, 404 when there is no such file | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 can't say for now whether the path is taken. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | +| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 is unavailable for a moment, checking the path or writing the file. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | | GET | `/api/groups/chat/analytics/{personId}` | Message and file counts across a person's groups | Any signed-in account | ## Persistence @@ -150,19 +150,25 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | -| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | +| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. The write is strict too (`S3FileHandler.uploadFileOrThrow`): a failed write throws instead of answering null. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx (a throttle, an outage), checking or writing, that's a 503 with `Retry-After` (`SharedFileStorageUnavailableException`); S3 refusing the request (any other 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **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. +- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. ## Testing - `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'`. +- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. +- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. ## Known issues @@ -173,7 +179,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/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 fafef205..8f1f4dab 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) { @@ -105,6 +110,23 @@ public String uploadFile(String base64Data, String filename, String uid) { } } + /** + * Like uploadFile, but a write that fails throws instead of answering null, so a caller can + * tell S3 being unavailable for a moment (a throttle, a 5xx, no connection) from a request + * S3 refused. + */ + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (s3Client == null) { + throw new IllegalStateException("S3 client is not configured"); + } + s3Client.putObject(PutObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build(), + RequestBody.fromBytes(Base64.getDecoder().decode(base64Data))); + return filename; + } + @Override public String decodeFile(String uid, String filename) { if (s3Client == null) { @@ -264,6 +286,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..fcc528e3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -38,9 +38,10 @@ @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 was unavailable for a moment, checking or + // writing a shared file or reading a group's messages: a throttle or a short outage clears + // in seconds. + private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; @@ -192,6 +193,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); } @@ -399,14 +406,14 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return new ResponseEntity<>(response, HttpStatus.CONFLICT); - } catch (SharedFileCheckFailedException ex) { - // S3 couldn't say whether the path is taken, so nothing was written. That's S3 being - // unavailable for a moment, not a bug here: a 503, and when to try again. + } catch (SharedFileStorageUnavailableException ex) { + // S3 was unavailable for a moment, checking the path or writing the file, so the file + // isn't shared. That's not a bug here: a 503, and when to try again. Map response = new HashMap<>(); response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); 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/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d69..bac95d70 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -101,10 +101,7 @@ public GroupChatEvent publishFile(Long groupId, String sender, String filename, throw new IllegalArgumentException("Invalid file path"); } - String uploadResult = groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); - if (uploadResult == null) { - throw new IllegalStateException("Upload failed"); - } + groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); GroupChatEvent event = GroupChatEvent.builder() .context("sendFileServer") diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 790db7d3..e64d59e0 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -31,10 +32,18 @@ public class GroupChatService { private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; private static final String SHARED_FILES_PREFIX = "shared-files/"; private static final String SHARED_FILES_META = "shared-files-meta.json"; + // S3's error code when a connection was too slow: a 400, but the AWS SDK retries it like a 5xx. + private static final String S3_REQUEST_TIMEOUT = "RequestTimeout"; private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; + // 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. @@ -59,14 +68,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 shared-files/ folder exists, if not, create it + // 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. 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); @@ -74,7 +98,32 @@ 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 being unavailable for a moment (see + * isUnavailable) 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 (!isUnavailable(e)) { + // 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 +161,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 +184,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); + + 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"); + } - boolean removed = messages.remove(target); + boolean removed = messages.remove(target); - if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + if (removed) { + 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); + } } } @@ -253,7 +308,8 @@ public byte[] readSharedFile(String groupName, String path) { /** * Stores a shared file, never over one already there: that throws SharedFileExistsException. - * When S3 can't say for now whether the path is taken, it throws SharedFileCheckFailedException. + * When S3 is unavailable for a moment, checking the path or writing the file, it throws + * SharedFileStorageUnavailableException. */ public String uploadSharedFile(String groupName, String filename, String base64Data, String uploadedBy) { List key = List.of(groupName, filename); @@ -264,10 +320,7 @@ public String uploadSharedFile(String groupName, String filename, String base64D if (isAlreadyShared(groupName, filename)) { throw new SharedFileExistsException(filename); } - String result = s3FileHandler.uploadFile(base64Data, SHARED_FILES_PREFIX + filename, groupName); - if (result == null) { - return null; - } + String result = store(groupName, filename, base64Data); recordFileMeta(groupName, filename, uploadedBy); return result; } finally { @@ -277,20 +330,55 @@ public String uploadSharedFile(String groupName, String filename, String base64D /** * Whether a file is stored at this path. Strict: a check that failed throws, rather than - * reading as a free path. S3 out of reach or answering a 5xx is something to wait out, so - * that throws SharedFileCheckFailedException; anything else goes up as it is. + * reading as a free path. S3 being unavailable throws SharedFileStorageUnavailableException; + * anything else goes up as it is. */ private boolean isAlreadyShared(String groupName, String path) { try { return s3FileHandler.fileExistsOrThrow(groupName, SHARED_FILES_PREFIX + path); } catch (SdkClientException | S3Exception e) { - if (e instanceof S3Exception answered && answered.statusCode() < 500) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + if (!isUnavailable(e)) { throw e; } log.warn("Could not check whether {} is shared in group {}", path, groupName, e); - throw new SharedFileCheckFailedException(path, e); + throw new SharedFileStorageUnavailableException(path, e); + } + } + + /** + * Writes a shared file's bytes. S3 being unavailable throws + * SharedFileStorageUnavailableException; any other failure fails the upload as it always has. + */ + private String store(String groupName, String path, String base64Data) { + try { + return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer). Sharing it again + // then gets a 409, which the page handles like any other taken name. + log.warn("Could not store {} in group {}", path, groupName, e); + if (isUnavailable(e)) { + throw new SharedFileStorageUnavailableException(path, e); + } + throw new IllegalStateException("Upload failed", e); + } + } + + /** + * S3 out of reach (a timeout, no connection), answering a 5xx (a throttle, an outage) or + * timing out the request itself (RequestTimeout, which comes as a 400): something to wait + * out. Any other 4xx is S3 refusing the request (no permission, a bad key), which waiting + * won't fix, and anything else is a fault here. + */ + private static boolean isUnavailable(RuntimeException e) { + if (e instanceof SdkClientException) { + return true; + } + if (e instanceof S3Exception answered) { + AwsErrorDetails details = answered.awsErrorDetails(); + return answered.statusCode() >= 500 + || (details != null && S3_REQUEST_TIMEOUT.equals(details.errorCode())); } + return false; } // --------------------------------------------------------------------------- diff --git a/src/main/java/com/open/spring/mvc/groups/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/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java deleted file mode 100644 index e71203dd..00000000 --- a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't say for now whether a shared file is already stored at this path: it timed out, - * couldn't be reached or answered with a 5xx (a throttle, an outage). The upload is refused - * rather than risk writing over a file, and the API answers 503 with Retry-After, since S3 being - * unavailable for a moment isn't a bug in this server. - */ -public class SharedFileCheckFailedException extends RuntimeException { - - private final String path; - - public SharedFileCheckFailedException(String path, Throwable cause) { - super("Could not check whether " + path + " is already shared in this group. Try again in a moment.", cause); - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java new file mode 100644 index 00000000..0f1ee102 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java @@ -0,0 +1,22 @@ +package com.open.spring.mvc.groups; + +/** + * S3 was unavailable for a moment while a file was being shared: it timed out, couldn't be + * reached or answered with a 5xx (a throttle, an outage). Either it couldn't say whether the + * path is taken, so the upload is refused rather than risk writing over a file, or the write + * itself failed. The file isn't shared, and the API answers 503 with Retry-After, since S3 being + * unavailable for a moment isn't a bug in this server. + */ +public class SharedFileStorageUnavailableException extends RuntimeException { + + private final String path; + + public SharedFileStorageUnavailableException(String path, Throwable cause) { + super("Could not share " + path + " in this group. Try again in a moment.", cause); + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/test/java/com/open/spring/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(); + } + } +} 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/S3uploads/S3FileHandlerUploadTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java new file mode 100644 index 00000000..0e35b375 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java @@ -0,0 +1,79 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * uploadFileOrThrow tells a stored file apart from a write that failed: it throws the failure + * where uploadFile answers null, so a caller can tell S3 being unavailable for a moment from a + * request S3 refused. + */ +class S3FileHandlerUploadTest { + + private static final String HELLO = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8)); + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + ReflectionTestUtils.setField(handler, "bucketName", "pages-assignments"); + } + + @Test + void aWriteS3TakesStoresTheBytesUnderTheGroupsKey() throws Exception { + assertEquals("shared-files/notes.md", handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + ArgumentCaptor body = ArgumentCaptor.forClass(RequestBody.class); + verify(s3).putObject(request.capture(), body.capture()); + assertEquals("pages-assignments", request.getValue().bucket()); + assertEquals("CSA/shared-files/notes.md", request.getValue().key()); + try (InputStream bytes = body.getValue().contentStreamProvider().newStream()) { + assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), bytes.readAllBytes()); + } + } + + @Test + void aWriteThatFailsThrowsTheFailureInsteadOfAnsweringNull() { + S3Exception throttled = (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(throttled); + + assertSame(throttled, assertThrows(S3Exception.class, + () -> handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA"))); + // uploadFile keeps answering null, as its other callers expect. + assertNull(handler.uploadFile(HELLO, "shared-files/notes.md", "CSA")); + } + + @Test + void withoutS3ItThrowsInsteadOfAnsweringNull() { + S3FileHandler notConfigured = new S3FileHandler(); + + assertThrows(IllegalStateException.class, + () -> notConfigured.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1f..6e6efacd 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -41,6 +41,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -61,6 +62,12 @@ public String uploadFile(String base64Data, String filename, String uid) { return filename; } + // Stores the same way, so a test that slows uploadFile slows this too. + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + return uploadFile(base64Data, filename, uid); + } + @Override public String decodeFile(String uid, String filename) { byte[] bytes = objects.get(uid + "/" + filename); @@ -90,6 +97,36 @@ public Map listFileSizes(String prefix) { } } + /** + * S3 that answers the check but fails the write of a shared file's bytes while `failure` is + * set, the way S3FileHandler sees it: uploadFile swallows the failure and answers null, and + * uploadFileOrThrow throws it. Other writes, like the "shared by" record, still go through. + */ + static class SharedFileWritesFail extends InMemoryStorage { + RuntimeException failure; + + SharedFileWritesFail(RuntimeException failure) { + this.failure = failure; + } + + private boolean failing(String filename) { + return failure != null && filename.startsWith("shared-files/"); + } + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + return failing(filename) ? null : super.uploadFile(base64Data, filename, uid); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (failing(filename)) { + throw failure; + } + return super.uploadFileOrThrow(base64Data, filename, uid); + } + } + private InMemoryStorage storage; private SimpMessagingTemplate messaging; private GroupChatApiController controller; @@ -323,6 +360,67 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + @Test + void aWriteThatFailsForAMomentIsA503AndSharesNothing() { + // The path is free, but S3 throttled the write (503 Slow Down), couldn't be reached, or + // timed out the request (its RequestTimeout comes as a 400). + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + for (RuntimeException failure : failures) { + useStorage(new SharedFileWritesFail(failure)); + + ResponseEntity response = upload("notes.md", "Grace's notes"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + @SuppressWarnings("unchecked") + Map body = (Map) response.getBody(); + assertEquals("notes.md", body.get("filename")); + // No file, no "shared by" record, and no frame telling the group a file arrived. + assertTrue(storage.objects.isEmpty(), "stored: " + storage.objects.keySet()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aWriteS3RefusesOrABugIsStillA500() { + // S3 refusing the write (no permission, a bad request) or a fault in this server: trying + // again won't help, so none is a 503. + List faults = List.of( + new NullPointerException("a bug here, not S3"), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("InvalidRequest").build()) + .message("Invalid Request") + .build()); + for (RuntimeException fault : faults) { + useStorage(new SharedFileWritesFail(fault)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, upload("notes.md", "Grace's notes").getStatusCode(), fault.toString()); + } + } + + @Test + void aShareThatFailedForAMomentGoesThroughWhenTriedAgain() { + // What the 503 promises: once S3 takes writes again, the same share works, instead of + // finding the path still held by the upload that failed. + SharedFileWritesFail s3 = new SharedFileWritesFail( + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + useStorage(s3); + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, upload("notes.md", "Grace's notes").getStatusCode()); + + s3.failure = null; + + assertEquals(HttpStatus.OK, upload("notes.md", "Grace's notes").getStatusCode()); + assertArrayEquals("Grace's notes".getBytes(StandardCharsets.UTF_8), storage.objects.get("CSA/shared-files/notes.md")); + } + @Test void aPathBeingWrittenInOneGroupDoesNotHoldUpALookAlikeInAnother() throws Exception { // "a/b" sharing "c" and "a" sharing "b/c" read the same if group and path are joined. 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..56c6b6bc --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,209 @@ +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.awscore.exception.AwsErrorDetails; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +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), out of reach, or timing out the request (its RequestTimeout + // comes as a 400): failures that clear if you wait. + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + for (RuntimeException failure : failures) { + 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); + } + } +}