diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279..4818603d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Entity-removal helpers (run before any large cleanup): - Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate. - Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter. - [docs/group-chat-architecture.md](docs/group-chat-architecture.md) covers every groups and chat route, the WebSocket event contexts, S3 message storage (keyed by group name, not id) and the known issues. Over the WebSocket there is no Spring Security context, so a service that needs the signed-in account (like `GroupChatIdentityService`) only works from REST. The socket does read the `jwt_java_spring` cookie when it opens (`ChatSocketIdentityInterceptor`, same checks as `JwtRequestFilter`, and only when the request's `Origin` is in the REST CORS list, since a cross-site GET carries the cookie but no Origin), but only for `DirectMessageTopicGuard`: only a conversation's participants can subscribe to `/topic/dm/{id}`, and wildcard subscriptions, `/user/...` destinations and client SENDs to DM topics are dropped. It sets no Principal, on purpose, so `GroupChatWebSocketController` still ignores events. HTTP: `api/groups.http`. +- A client's SEND to any `/topic/...` destination is dropped too, group topics included, because the simple broker relays it to every subscriber. Only the server publishes there (the prefix is `WebSocketBrokerConfig.BROKER_PREFIX`). ## Assignment grading diff --git a/api/groups.http b/api/groups.http index c047fa49..e888e8be 100644 --- a/api/groups.http +++ b/api/groups.http @@ -133,6 +133,22 @@ Content-Type: application/json {"filename": "notes/hello.txt", "base64Data": "Z29vZGJ5ZQ=="} +### 13g. React to a message with a Like -> 200 with {messageId, reactions}, and a reactionsServer frame on /topic/group/{id} +# Any UUID is accepted: Spring doesn't read the S3 file to check the message, and a reaction +# on a message that doesn't exist is never shown. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13h. List the chat's reactions -> 200 with {"3f2c8a8e-...": [{"reaction": "like", "people": [{uid, name}]}]} +GET {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/reactions + +### 13i. Take the Like back -> 200 with an empty reactions list +DELETE {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13j. A key that isn't one of the six is refused -> 400 +# Direct messages have the same three routes under /api/dm/conversations/{id}: GET .../reactions, +# and PUT or DELETE .../messages/{messageId}/reactions/{reaction}, for participants only. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/thumbsup + ### 14. Remove yourself from the test group -> 200 DELETE {{baseUrl}}/api/groups/{{createGroup.response.body.$.id}}/members/{{me.response.body.$.id}} diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..2f76a451 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -104,7 +104,7 @@ The client sends a `GroupChatEvent` JSON object whose `context` names the event. | `heartbeat` | `heartbeatServer` with `participants` | | | anything else | `errorServer` | `Unsupported context`. | -Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. +Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. So are reactions, as `reactionsServer` with the `messageId` and the message's `reactions` after the change (see Reactions). ## REST operations @@ -132,15 +132,18 @@ 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. | -| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | -| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message; 404 when no message has that id, and then nothing is broadcast. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a lowercase UUID | Any signed-in account | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | 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 @@ -149,20 +152,44 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) |---|---|---| | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | +| Reactions | SQL: `message_reaction` (`chat_type`, `chat_id`, `message_id`, `person_id`, `reaction`), created at startup by `MessageReactionTableInitializer` | Shared with direct messages (`chat_type` is `DM` or `GROUP`). All five columns are the primary key, so a person leaves each reaction once on a message. Never stored in the group's S3 file. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | -| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | +| 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. +- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty, and an edit or delete answers 404 since there's no message to change. This is the normal state of a local server. +- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. +- **A line that doesn't read as a message is kept.** Loading the chat leaves it out and logs a warning, and a send, edit or delete writes it back as it was (`MessagesLine` in `GroupChatService`), so one bad line isn't lost the next time the file is saved. A message that can't be written as JSON refuses the change, and the route gives its usual 400, instead of being saved as `{}`. + +## Reactions + +People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. + +- A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions, a DM's once the delete commits. If the database can't remove them, the delete still goes through and is broadcast, and the error is logged. +- Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. +- A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. +- `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. ## Testing - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. -- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. +- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. +- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, the table's primary key on SQLite, and a delete whose reactions can't be removed. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. +- `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. +- `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. +- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. +- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. +- `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. +- `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. +- `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. +- `GroupChatMessagesFileTest` covers a line that doesn't read as a message, kept in place through a send, an edit and a delete and left out when the chat loads, and a message that can't be written. ## Known issues @@ -173,12 +200,12 @@ 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 - Keep routes, event `context` names and JSON field names stable: the course site's chat pages depend on them. Change them together with the Pages client. - New tables need a `CREATE TABLE IF NOT EXISTS` that runs at startup, because Hibernate runs with `ddl-auto=none`. +- Reaction keys change in `Reaction` and in Pages' Messages `reactions.js` together. - Anything that needs to know who is sending must work over both REST and the WebSocket, or send through REST. - Update this guide and `api/groups.http` when routes, events or storage change. `README.md` and `AGENTS.md` link here. 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/directmessages/DirectMessageApiController.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java index 9dab2859..889c9ed5 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java @@ -17,6 +17,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -24,6 +25,10 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,6 +51,7 @@ public class DirectMessageApiController { private final DirectMessageConversationJpaRepository conversationRepository; private final DirectMessageJpaRepository messageRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; @Data @NoArgsConstructor @@ -295,6 +301,81 @@ public ResponseEntity deleteMessage( } } + /** Every reaction in the conversation, by message id: what the page draws when it opens it. */ + @GetMapping("/conversations/{id}/reactions") + @Transactional(readOnly = true) + public ResponseEntity getReactions( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + if (!directMessageService.isParticipant(conversationOpt.get(), person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + return new ResponseEntity<>(reactionService.forChat(ChatType.DM, id), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity addReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity removeReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, false); + } + + private ResponseEntity setReaction(UserDetails userDetails, Long id, Long messageId, String key, boolean on) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + DirectMessageConversation conversation = conversationOpt.get(); + if (!directMessageService.isParticipant(conversation, person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST); + } + + try { + return new ResponseEntity<>(new MessageReactions(String.valueOf(messageId), + directMessageService.setReaction(conversation, person, messageId, reaction.get(), on)), HttpStatus.OK); + } catch (NoSuchElementException ex) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (IllegalStateException ex) { + return new ResponseEntity<>(Map.of("error", ex.getMessage()), HttpStatus.CONFLICT); + } + } + @PostMapping("/conversations/{id}/read") @Transactional public ResponseEntity markRead( diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java index b68c9c46..09b7b42f 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java @@ -1,5 +1,10 @@ package com.open.spring.mvc.directmessages; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -16,7 +21,7 @@ public class DirectMessageEvent { private Long id; private Long conversationId; - private String type; // "message" for new posts, "edited" for edits + private String type; // "message", "edited", "deleted", or "reactions" private String senderUid; private String senderName; private String senderPfp; @@ -26,4 +31,10 @@ public class DirectMessageEvent { private String sentAt; private boolean deleted; private boolean edited; + /** + * On a "reactions" frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5c910139..dc82a598 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -8,15 +8,22 @@ import java.util.NoSuchElementException; import java.util.Set; +import org.springframework.dao.DataAccessException; import org.springframework.data.domain.PageRequest; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Business logic for direct messages: finding/creating conversations, checking @@ -26,6 +33,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class DirectMessageService { public static final String DM_TOPIC_PREFIX = "/topic/dm/"; @@ -41,6 +49,7 @@ public class DirectMessageService { private final DirectMessageReadStateJpaRepository readStateRepository; private final SimpMessagingTemplate messagingTemplate; private final PushNotificationService pushNotificationService; + private final MessageReactionService reactionService; public record UnreadSender(String uid, String name) { } @@ -222,6 +231,10 @@ public void deleteMessage(DirectMessageConversation conversation, Person request message.setDeleted(true); message.setBody(""); messageRepository.save(message); + // A tombstone shows no reactions, so none are kept for it. They're removed after the delete + // commits: an error from the reactions table inside this transaction would undo the delete. + Long conversationId = conversation.getId(); + afterCommit(() -> removeReactions(conversationId, messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -235,6 +248,68 @@ public void deleteMessage(DirectMessageConversation conversation, Person request messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * conversation's topic with a "reactions" frame. A reaction isn't a message: nobody gets a + * phone notification and nothing becomes unread. Throws {@link NoSuchElementException} if + * the message isn't in this conversation and {@link IllegalStateException} if it was + * deleted; {@code noRollbackFor} for the reason given on {@link #editMessage}. + */ + @Transactional(noRollbackFor = {NoSuchElementException.class, IllegalStateException.class}) + public List setReaction(DirectMessageConversation conversation, + Person person, Long messageId, Reaction reaction, boolean on) { + DirectMessage message = messageRepository.findByIdAndConversation(messageId, conversation) + .orElseThrow(() -> new NoSuchElementException("Message not found")); + if (message.isDeleted()) { + throw new IllegalStateException("Message was deleted"); + } + + String key = String.valueOf(messageId); + if (on) { + reactionService.add(ChatType.DM, conversation.getId(), key, person, reaction); + } else { + reactionService.remove(ChatType.DM, conversation.getId(), key, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.DM, conversation.getId(), key); + + // The frame goes out once this commits, with the reactions read again then. Read here, + // inside this transaction, they could miss a reaction someone else saved at the same time, + // and that person's frame would miss this one. + Long conversationId = conversation.getId(); + afterCommit(() -> messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversationId, DirectMessageEvent.builder() + .id(messageId) + .conversationId(conversationId) + .type("reactions") + .reactions(reactionService.forMessageNow(ChatType.DM, conversationId, key)) + .build())); + return reactions; + } + + // Runs once the current transaction commits, or right away outside one. + /** Removes a deleted message's reactions. The delete is already done, so a failure is only logged. */ + private void removeReactions(Long conversationId, Long messageId) { + try { + reactionService.removeAllFor(ChatType.DM, conversationId, String.valueOf(messageId)); + } catch (DataAccessException e) { + log.warn("Could not remove the reactions of deleted message {} in conversation {}", + messageId, conversationId, e); + } + } + + private static void afterCommit(Runnable action) { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + action.run(); + } + }); + } else { + action.run(); + } + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java index ac52e689..88776100 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java @@ -13,6 +13,7 @@ import org.springframework.util.PathMatcher; import com.open.spring.mvc.groups.ChatSocketIdentityInterceptor; +import com.open.spring.mvc.groups.WebSocketBrokerConfig; import lombok.extern.slf4j.Slf4j; @@ -26,8 +27,9 @@ *
  • No wildcard SUBSCRIBE on any topic. The broker matches {@code *}, {@code **}, {@code ?} * and {@code {name}} as patterns, so {@code /topic/**} would get every DM with no id at all. * No client uses one.
  • - *
  • No client SEND to a DM topic. The broker relays a client's SEND to every subscriber, so it - * would show up in someone's thread as a real message. Only the server posts there.
  • + *
  • No client SEND to any topic, DM or group ({@code /topic...}). The broker relays a client's + * SEND to every subscriber, so it would show up in someone's chat as a real message. Only the + * server posts there; pages send through REST or {@code /app/groups.chat}.
  • *
  • No SUBSCRIBE or SEND to a user destination ({@code /user/...}). Nothing on this socket uses * them, and Spring rewrites a {@code /user/X} subscription to X plus "-user" plus the session id * after this check. A SockJS client picks its own session id, so the two halves together can make @@ -102,8 +104,8 @@ private String whySubscribeIsRefused(String destination, Map ses /** Why a client's SEND is refused, or null to let it through. */ private static String whySendIsRefused(String destination) { - if (isDirectMessageTopic(destination)) { - return "only the server sends to direct message topics"; + if (destination != null && destination.startsWith(WebSocketBrokerConfig.BROKER_PREFIX)) { + return "only the server sends to topics"; } if (isUserDestination(destination)) { return NO_USER_DESTINATIONS; diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java index 60eaaf80..0a3816b4 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.regex.Pattern; import java.nio.charset.StandardCharsets; @@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -28,6 +30,10 @@ import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -38,27 +44,37 @@ @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 or saving a group's messages: a throttle or a short + // outage clears in seconds. + private static final int RETRY_AFTER_SECONDS = 5; + + // A saved group message's id is a UUID (GroupChatMessage), written in lowercase. Reactions + // don't read the group's S3 file to check that the message exists, so the id at least has to + // look like one; an uppercase copy would match some lookups and not others on MySQL. + static final Pattern MESSAGE_ID = + Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; private final GroupChatReadService readService; private final GroupsJpaRepository groupsRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; public GroupChatApiController( GroupChatService groupChatService, GroupChatRealtimeService realtimeService, GroupChatReadService readService, GroupsJpaRepository groupsRepository, - PersonJpaRepository personRepository) { + PersonJpaRepository personRepository, + MessageReactionService reactionService) { this.groupChatService = groupChatService; this.realtimeService = realtimeService; this.readService = readService; this.groupsRepository = groupsRepository; this.personRepository = personRepository; + this.reactionService = reactionService; } @Data @@ -190,15 +206,16 @@ public ResponseEntity postMessage( return new ResponseEntity<>("name and message are required", HttpStatus.BAD_REQUEST); } + // Answered from what was saved: a second read could fail and answer an empty chat. + List saved; try { - realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + saved = realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - - String groupName = groupOpt.get().getName(); - List updated = groupChatService.getMessages(groupName); - return new ResponseEntity<>(updated, HttpStatus.OK); + return new ResponseEntity<>(saved, HttpStatus.OK); } @PatchMapping("/{groupId}/messages/{messageId}") @@ -220,21 +237,20 @@ public ResponseEntity editMessage( return new ResponseEntity<>("message is required", HttpStatus.BAD_REQUEST); } - boolean updated; + Optional> saved; try { - updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); + saved = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - if (!updated) { + if (saved.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - - String groupName = groupOpt.get().getName(); - List messages = groupChatService.getMessages(groupName); - return new ResponseEntity<>(messages, HttpStatus.OK); + return new ResponseEntity<>(saved.get(), HttpStatus.OK); } @DeleteMapping("/{groupId}/messages/{messageId}") @@ -251,17 +267,87 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + boolean deleted; try { - realtimeService.deleteMessage(groupId, messageId, identity.getUid()); + deleted = realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - + if (!deleted) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } return new ResponseEntity<>(HttpStatus.OK); } + /** + * S3 couldn't read or save the group's messages, so the change isn't broadcast (a save that + * timed out may still be stored). That's S3 being unavailable for a moment, not a bug here: + * a 503, and when to try again. + */ + private static ResponseEntity tryAgainLater(MessagesStorageUnavailableException ex) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); + } + + /** + * Every reaction in the group's chat, by message id: what the page draws when it opens the + * chat. Like posting, it needs a signed-in person but not membership. + */ + @GetMapping("/{groupId}/reactions") + public ResponseEntity getReactions(@PathVariable Long groupId) { + if (currentPerson() == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(reactionService.forChat(ChatType.GROUP, groupId), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity addReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity removeReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, false); + } + + private ResponseEntity setReaction(Long groupId, String messageId, String key, boolean on) { + Person person = currentPerson(); + if (person == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>("unknown reaction", HttpStatus.BAD_REQUEST); + } + if (messageId == null || !MESSAGE_ID.matcher(messageId).matches()) { + return new ResponseEntity<>("messageId is not a message id", HttpStatus.BAD_REQUEST); + } + + List reactions = + realtimeService.setReaction(groupId, person, messageId, reaction.get(), on); + return new ResponseEntity<>(new MessageReactions(messageId, reactions), HttpStatus.OK); + } + /** * Unread counts for the signed-in member's own groups, keyed by group id. Groups * with nothing unread are left out, so an empty map means nothing is waiting. @@ -399,14 +485,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/GroupChatEvent.java b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java index acedc9fd..00f671a3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java @@ -2,6 +2,9 @@ import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -29,4 +32,10 @@ public class GroupChatEvent { private String error; private List participants; private boolean edited; + /** + * On a reactionsServer frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d69..11c24a52 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,14 +1,21 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; +import org.springframework.dao.DataAccessException; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Service to handle the real-time publishing of group chat messages and presence events. @@ -16,6 +23,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class GroupChatRealtimeService { public static final String GROUP_TOPIC_PREFIX = "/topic/group/"; @@ -23,8 +31,10 @@ public class GroupChatRealtimeService { private final GroupChatService groupChatService; private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; + private final MessageReactionService reactionService; - public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { + /** Saves the message, tells the group, and returns the group's messages as saved. */ + public List publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); if ((message == null || message.isBlank()) && (image == null || image.isBlank())) { @@ -34,7 +44,7 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, String date = Instant.now().toString(); GroupChatMessage persisted = new GroupChatMessage(identity.getDisplayName(), identity.getUid(), message, date, image); - groupChatService.addMessage(group.getName(), persisted); + List saved = groupChatService.addMessage(group.getName(), persisted); GroupChatEvent event = GroupChatEvent.builder() .context("sendMessageServer") @@ -47,18 +57,19 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, .build(); broadcastToGroup(groupId, event); - return event; + return saved; } /** - * Returns whether the message existed (and was broadcast as edited). Throws - * {@link SecurityException} if the authenticated requester's uid is not the author uid. + * Edits the message, tells the group, and returns the group's messages as saved, or nothing + * when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester's uid is not the author uid. */ - public boolean editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { + public Optional> editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { Groups group = getGroupOrThrow(groupId); - boolean updated = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); - if (!updated) { - return false; + Optional> saved = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); + if (saved.isEmpty()) { + return saved; } GroupChatEvent event = GroupChatEvent.builder() @@ -71,13 +82,28 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St .build(); broadcastToGroup(groupId, event); - return true; + return saved; } - /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ - public void deleteMessage(Long groupId, String messageId, String requesterUid) { + /** + * Deletes the message and its reactions and tells the group, or returns false and tells no + * one when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester didn't send it. + */ + public boolean deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); - groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + if (!groupChatService.deleteMessage(group.getName(), messageId, requesterUid)) { + // Telling the group about a message that isn't saved would take it off everyone's screen. + return false; + } + try { + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + } catch (DataAccessException e) { + // The message is already gone from S3, so the group still has to hear about it, and a + // retry would find nothing to delete. Its reactions stay in the table, where no message + // shows them. + log.warn("Could not remove the reactions of deleted message {} in group {}", messageId, groupId, e); + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -87,6 +113,35 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { .build(); broadcastToGroup(groupId, event); + return true; + } + + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * group's topic with a reactionsServer frame. Reactions are kept in the database, never in + * the group's S3 message file, so a reaction can't change or drop a message. + */ + public List setReaction( + Long groupId, Person person, String messageId, Reaction reaction, boolean on) { + getGroupOrThrow(groupId); + if (on) { + reactionService.add(ChatType.GROUP, groupId, messageId, person, reaction); + } else { + reactionService.remove(ChatType.GROUP, groupId, messageId, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.GROUP, groupId, messageId); + + GroupChatEvent event = GroupChatEvent.builder() + .context("reactionsServer") + .groupId(groupId) + .messageId(messageId) + .reactions(reactions) + .date(Instant.now().toString()) + .build(); + + broadcastToGroup(groupId, event); + return reactions; } /** @@ -101,10 +156,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..1e6bd635 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -21,6 +23,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 +34,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 +70,29 @@ public void initGroupStorage(String groupName) { s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); } + /** + * Creates the group's empty messages file and shared-files/ folder if they're missing. + * Strict for the messages file: only S3's 404 means missing, and a check that failed + * throws without writing, since an empty file written over the real one would erase the + * group's history. + */ public void ensureGroupStorageExists(String groupName) { - // Check if messages.jsonl exists, if not, create it - if (!s3FileHandler.fileExists(groupName, MESSAGES_FILE)) { - String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); - s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + // Without S3 settings nothing is stored, so there's nothing to check. + if (!s3FileHandler.isConfigured()) { + return; + } + + // Check if messages.jsonl exists, if not, create it. Under the group's message lock, + // so a message sent between the check and the write isn't lost under the empty file. + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + if (!s3FileHandler.fileExistsOrThrow(groupName, MESSAGES_FILE)) { + String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); + s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + } } - // Check if shared-files/ folder exists, if not, create it + // Check if shared-files/ folder exists, if not, create it. Its placeholder is empty, + // so writing it again loses nothing. if (!s3FileHandler.fileExists(groupName, SHARED_FILES_PREFIX)) { String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); @@ -74,7 +100,90 @@ 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)); + } + + /** + * One line of a group's messages file: a message, or a line that didn't read as one, kept + * as it was so that saving the file again doesn't drop it. + */ + private record MessagesLine(GroupChatMessage message, String unreadable) { + static MessagesLine of(GroupChatMessage message) { + return new MessagesLine(message, null); + } + } + + /** + * The group's messages file, line by line, for a send, an edit or a delete, which write the + * whole file back. Strict: a read that failed throws rather than reading as an empty chat, + * which a send would save over the history and an edit or delete would answer as "not + * found". Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + */ + private List readMessagesOrThrow(String groupName) { + String base64Data; + try { + base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); + } catch (RuntimeException e) { + // Logged for every failure: the route answers a refused read or a bug without logging it. + log.warn("Could not read the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + return parseLines(groupName, base64Data); + } + + /** + * Saves the group's whole messages file: each message as JSON, and each line that didn't + * read as a message as it was. Strict: a write that failed throws, so a send, an edit or a + * delete isn't answered as saved when it wasn't. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + * Without S3 settings nothing is stored, and the chat still works live. + */ + private void writeMessagesOrThrow(String groupName, List lines) { + if (!s3FileHandler.isConfigured()) { + return; + } + String jsonl = lines.stream() + .map(line -> line.message() != null ? toJson(line.message()) : line.unreadable()) + .collect(Collectors.joining("\n")); + String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + try { + s3FileHandler.uploadFileOrThrow(base64Data, MESSAGES_FILE, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer), so a send tried + // again can show up twice. That's easier to see and fix than a message lost quietly. + log.warn("Could not save the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + } + + private List parseMessages(String groupName, String base64Data) { + return messagesOf(parseLines(groupName, base64Data)); + } + + private static List messagesOf(List lines) { + return lines.stream() + .map(MessagesLine::message) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); + } + + private static GroupChatMessage find(List lines, String messageId) { + return messagesOf(lines).stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + } + + private List parseLines(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -92,99 +201,76 @@ public List getMessages(String groupName) { return new ArrayList<>(); } - List messages = new ArrayList<>(); + List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new StringReader(jsonl))) { String line; while ((line = reader.readLine()) != null) { if (line.isBlank()) continue; try { - GroupChatMessage msg = objectMapper.readValue(line, GroupChatMessage.class); - messages.add(msg); + lines.add(MessagesLine.of(objectMapper.readValue(line, GroupChatMessage.class))); } catch (Exception e) { - log.warn("Skipping invalid message line for group {}: {}", groupName, line, e); + // Left out of the chat, but kept in the file: a save writes it back as it is. + log.warn("Keeping an unreadable message line of group {} as it is: {}", groupName, line, e); + lines.add(new MessagesLine(null, line)); } } } catch (Exception e) { log.warn("Failed reading messages for group {}", groupName, e); } - return messages; + return lines; } public List addMessage(String groupName, GroupChatMessage message) { - List messages = getMessages(groupName); - messages.add(message); - - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - return messages; + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + lines.add(MessagesLine.of(message)); + writeMessagesOrThrow(groupName, lines); + return messagesOf(lines); + } } /** - * Returns whether a message with that id was found (and updated) in this group. - * Throws {@link SecurityException} unless the authenticated requester's uid matches - * the stored author uid. Legacy messages without an author uid cannot be edited. + * Edits a message and returns the group's messages as saved, or nothing when no message + * with that id is in this group. Throws {@link SecurityException} unless the authenticated + * requester's uid matches the stored author uid. Legacy messages without an author uid + * cannot be edited. */ - public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { - if (messageId == null) return false; - 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; + public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { + if (messageId == null) return Optional.empty(); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) { + return Optional.empty(); } + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + target.setMessage(newMessage); + target.setEdited(true); + writeMessagesOrThrow(groupName, lines); + return Optional.of(messagesOf(lines)); } - - if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - } - 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"); - } - - boolean removed = messages.remove(target); - - if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + /** + * Deletes a message and returns whether one with that id was in this group. Same ownership + * rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. + */ + public boolean deleteMessage(String groupName, String messageId, String requesterUid) { + if (messageId == null) return false; + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) return false; + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + lines.removeIf(line -> line.message() == target); + writeMessagesOrThrow(groupName, lines); + return true; } } @@ -253,7 +339,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 +351,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 +361,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; } // --------------------------------------------------------------------------- @@ -397,8 +516,9 @@ private String toJson(GroupChatMessage message) { try { return objectMapper.writeValueAsString(message); } catch (Exception e) { - log.warn("Failed to serialize message: {}", message, e); - return "{}"; + // Writing "{}" instead would replace the message in the file with nothing. + log.warn("Could not write message {} of a group chat", message.getId(), e); + throw new IllegalStateException("Could not write message " + message.getId(), e); } } } diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java new file mode 100644 index 00000000..93274a54 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java @@ -0,0 +1,15 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read or save a group's messages for now: it timed out, couldn't be reached or + * answered with a 5xx (a throttle, an outage). Sending, editing and deleting a message each read + * the whole messages file and write it back, so the change is refused rather than half done, and + * the API answers 503 with Retry-After, since S3 being unavailable for a moment isn't a bug in + * this server. + */ +public class MessagesStorageUnavailableException extends RuntimeException { + + public MessagesStorageUnavailableException(Throwable cause) { + super("Could not save this change to the group's chat right now. Try again in a moment.", cause); + } +} diff --git a/src/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/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java index 84ab9f48..590f56a5 100644 --- a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java +++ b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java @@ -20,12 +20,15 @@ *

    * When a socket opens, {@link ChatSocketIdentityInterceptor} reads the login cookie. Every frame a * client sends then passes {@link DirectMessageTopicGuard}, which lets only a conversation's - * participants subscribe to its /topic/dm/{id}. + * participants subscribe to its /topic/dm/{id} and keeps clients from sending to any topic. */ @Configuration @EnableWebSocketMessageBroker public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer { + /** The simple broker handles every destination that starts with this, so only the server may send there. */ + public static final String BROKER_PREFIX = "/topic"; + private final ChatSocketIdentityInterceptor identityInterceptor; private final DirectMessageTopicGuard directMessageTopicGuard; @@ -53,7 +56,7 @@ public void configureClientInboundChannel(ChannelRegistration registration) { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.enableSimpleBroker("/topic"); + registry.enableSimpleBroker(BROKER_PREFIX); registry.setApplicationDestinationPrefixes("/app"); } } diff --git a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java index 08f63862..1ba9a0c3 100644 --- a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java +++ b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java @@ -4,14 +4,19 @@ import java.security.Security; import java.time.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -49,6 +54,13 @@ public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class); private static final int TTL_SECONDS = 60 * 60 * 24; // keep undelivered pushes for a day private static final int MAX_BODY_CHARS = 140; + // The markers Messages puts in a body for the page to read: a reply's quote, shared files, + // a code block, a pin, and the course chats' events and lessons. A phone shouldn't show them. + // Pages lists the same names in ANY_MARKER_PATTERN (assets/js/chat/chat-reply.js), so a + // marker added there needs adding here too, or its raw text shows up in DM notifications. + // No marker Pages writes has a bracket inside it (it escapes or URL-encodes them), so the + // payload leaves out "[" as well: that keeps matching linear when a body is full of "[[". + private static final Pattern CHAT_MARKER = Pattern.compile("\\[\\[(reply|event|lesson|files|code|pin|unpin):[^\\[\\]]*\\]\\]"); /** How long an unchanged subscription goes before a re-send refreshes last_used_at. */ private static final Duration RESEEN_AFTER = Duration.ofDays(1); @@ -174,7 +186,7 @@ public void notifyPerson(Person person, String title, String body, String url, S } Map payload = Map.of( "title", title == null ? "New message" : title, - "body", snippet(body), + "body", pushText(body), "url", url == null ? "/dm" : url, "tag", tag == null ? "ocs" : tag); Long personId = person.getId(); @@ -191,6 +203,17 @@ public void afterCommit() { } } + // notifyPerson never throws, and it runs inside the message's transaction, so a body the + // text can't be made from still sends the message and its notification, without text. + private static String pushText(String body) { + try { + return snippet(body); + } catch (RuntimeException ex) { + log.warn("Web push: could not make the notification's text ({})", ex.getMessage()); + return ""; + } + } + /** Runs on the sender thread: loads the person's subscriptions and pushes to each. */ private void sendToPerson(Long personId, Map payload) { List subscriptions; @@ -236,12 +259,47 @@ private void send(PushSubscriptionEntity subscription, String json) { } } + /** + * The notification's text: the message as a reader sees it in the chat, cut to + * {@value #MAX_BODY_CHARS} characters. The chat's markers are left out, and the rich + * composer's HTML becomes plain text (tags gone, entities decoded, {@code  } a space). + * If no words are left, the text says what the message did instead, such as "pinned a + * message", or just "sent a message". + */ static String snippet(String body) { - if (body == null) { + if (body == null || body.isBlank()) { return ""; } - String oneLine = body.replaceAll("\\s+", " ").trim(); - return oneLine.length() <= MAX_BODY_CHARS ? oneLine : oneLine.substring(0, MAX_BODY_CHARS - 1) + "…"; + Set markers = new HashSet<>(); + Matcher marker = CHAT_MARKER.matcher(body); + StringBuilder words = new StringBuilder(); + while (marker.find()) { + markers.add(marker.group(1)); + marker.appendReplacement(words, " "); + } + marker.appendTail(words); + String text = Jsoup.parse(words.toString()).text().replace('\u00A0', ' ').replaceAll("\\s+", " ").trim(); + if (text.isEmpty()) { + text = onlyMarkers(markers); + } + return text.length() <= MAX_BODY_CHARS ? text : text.substring(0, MAX_BODY_CHARS - 1) + "…"; + } + + // What a message that was only markers did, said after the sender's name (the title). + private static String onlyMarkers(Set markers) { + if (markers.contains("pin")) { + return "pinned a message"; + } + if (markers.contains("unpin")) { + return "unpinned a message"; + } + if (markers.contains("code")) { + return "sent code"; + } + if (markers.contains("files")) { + return "shared files"; + } + return "sent a message"; } @PreDestroy diff --git a/src/main/java/com/open/spring/mvc/reactions/ChatType.java b/src/main/java/com/open/spring/mvc/reactions/ChatType.java new file mode 100644 index 00000000..9e8583ed --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/ChatType.java @@ -0,0 +1,7 @@ +package com.open.spring.mvc.reactions; + +/** The kind of chat a reacted-to message is in: a DM conversation or a group chat. */ +public enum ChatType { + DM, + GROUP +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java new file mode 100644 index 00000000..13cdfc27 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java @@ -0,0 +1,57 @@ +package com.open.spring.mvc.reactions; + +import java.io.Serializable; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * One person's reaction to one message. The whole row is its key, so a person leaves each + * reaction at most once on a message. DM messages are rows and group messages live in S3, + * so a message is named by its chat and its id as text. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "message_reaction") +public class MessageReaction { + + @EmbeddedId + private Key key; + + /** Which chat, which message, who, and which emoji. */ + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Key implements Serializable { + + @Enumerated(EnumType.STRING) + @Column(name = "chat_type", length = 8) + private ChatType chatType; + + /** The DM conversation's id or the group's id. */ + @Column(name = "chat_id") + private Long chatId; + + /** A DM message's numeric id as text, or a group message's UUID. */ + @Column(name = "message_id", length = 64) + private String messageId; + + @Column(name = "person_id") + private Long personId; + + @Enumerated(EnumType.STRING) + @Column(name = "reaction", length = 16) + private Reaction reaction; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java new file mode 100644 index 00000000..b920148d --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -0,0 +1,52 @@ +package com.open.spring.mvc.reactions; + +import java.util.Collection; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +/** Reactions, read by chat or by message. */ +public interface MessageReactionJpaRepository extends JpaRepository { + + /** Every reaction in one chat. */ + List findByKeyChatTypeAndKeyChatId(ChatType chatType, Long chatId); + + /** Every reaction on one message. */ + List findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + + /** + * Removes one person's reaction in one statement. Reading the row first and then deleting it + * let a second remove at the same moment fail; a statement that deletes 0 rows doesn't. + */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId and r.key.personId = :personId and r.key.reaction = :reaction") + int deleteOne(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, @Param("messageId") String messageId, + @Param("personId") Long personId, @Param("reaction") Reaction reaction); + + /** Removes every reaction on one message in one statement, as when the message is deleted. */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId") + int deleteAllOnMessage(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, + @Param("messageId") String messageId); + + /** + * The uid and name of each person who reacted, in one query. Loading whole Person rows + * would also load each one's eager links, several queries per person. + */ + @Query("select p.id as id, p.uid as uid, p.name as name from Person p where p.id in :ids") + List findReactorNames(@Param("ids") Collection ids); + + /** A person who reacted, as far as a reaction needs to know them. */ + interface ReactorName { + Long getId(); + + String getUid(); + + String getName(); + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java new file mode 100644 index 00000000..afb8540c --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -0,0 +1,132 @@ +package com.open.spring.mvc.reactions; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; + +import lombok.RequiredArgsConstructor; + +/** + * Saves and summarizes the reactions on DM and group messages. It doesn't decide who may react + * or whether a message exists: each chat's own service checks that before calling here. + */ +@Service +@RequiredArgsConstructor +public class MessageReactionService { + + private static final Comparator BY_NAME = Comparator + .comparing((Reactor reactor) -> reactor.name() == null ? "" : reactor.name(), String.CASE_INSENSITIVE_ORDER) + .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); + + private final MessageReactionJpaRepository repository; + + /** Someone who reacted, as the page shows them. */ + public record Reactor(String uid, String name) { + } + + /** One emoji on a message, by its lowercase key, and everyone who left it. */ + public record ReactionSummary(String reaction, List people) { + } + + /** A message's reactions after a change: the body PUT and DELETE answer with. */ + public record MessageReactions(String messageId, List reactions) { + } + + /** Adds this person's reaction. Adding one that is already there changes nothing. */ + @Transactional + public void add(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (!repository.existsById(key)) { + repository.save(new MessageReaction(key)); + } + } + + /** Removes this person's reaction. Removing one that isn't there changes nothing. */ + @Transactional + public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + repository.deleteOne(type, chatId, messageId, person.getId(), reaction); + } + + /** One message's reactions, in the enum's order. */ + @Transactional(readOnly = true) + public List forMessage(ChatType type, Long chatId, String messageId) { + List rows = repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + return summarize(rows, reactorsFor(rows)); + } + + /** + * One message's reactions, read in a transaction of its own: for the frame a DM sends once its + * change has committed, so the read sees what everyone else committed by then. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public List forMessageNow(ChatType type, Long chatId, String messageId) { + return forMessage(type, chatId, messageId); + } + + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ + @Transactional(readOnly = true) + public Map> forChat(ChatType type, Long chatId) { + List rows = repository.findByKeyChatTypeAndKeyChatId(type, chatId); + Map reactors = reactorsFor(rows); + Map> byMessage = rows.stream().collect( + Collectors.groupingBy(row -> row.getKey().getMessageId(), LinkedHashMap::new, Collectors.toList())); + Map> result = new LinkedHashMap<>(); + byMessage.forEach((messageId, messageRows) -> { + List summaries = summarize(messageRows, reactors); + if (!summaries.isEmpty()) { + result.put(messageId, summaries); + } + }); + return result; + } + + /** + * Removes every reaction on a message, as when the message is deleted. The chats call it once + * their delete is done (a DM's after its transaction commits), so it runs in a transaction of + * its own: a transactional call made from inside a finished transaction never commits. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void removeAllFor(ChatType type, Long chatId, String messageId) { + repository.deleteAllOnMessage(type, chatId, messageId); + } + + // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. + private Map reactorsFor(List rows) { + List ids = rows.stream().map(row -> row.getKey().getPersonId()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + Map reactors = new HashMap<>(); + for (MessageReactionJpaRepository.ReactorName person : repository.findReactorNames(ids)) { + reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); + } + return reactors; + } + + private List summarize(List rows, Map reactors) { + List summaries = new ArrayList<>(); + for (Reaction reaction : Reaction.values()) { + List people = rows.stream() + .filter(row -> row.getKey().getReaction() == reaction) + .map(row -> reactors.get(row.getKey().getPersonId())) + .filter(Objects::nonNull) + .sorted(BY_NAME) + .toList(); + if (!people.isEmpty()) { + summaries.add(new ReactionSummary(reaction.key(), people)); + } + } + return summaries; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java new file mode 100644 index 00000000..a7412931 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -0,0 +1,48 @@ +package com.open.spring.mvc.reactions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; + +/** + * Creates message_reaction for databases run with ddl-auto=none, and leaves an existing one + * as it is. The primary key is all five columns: that keeps a person to one of each reaction + * on a message, and it needs no auto-increment, so one statement in unquoted lowercase with + * plain types runs on both SQLite and MySQL. + */ +@Component +@RequiredArgsConstructor +public class MessageReactionTableInitializer { + + static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS message_reaction (" + + "chat_type varchar(8) NOT NULL, " + + "chat_id bigint NOT NULL, " + + "message_id varchar(64) NOT NULL, " + + "person_id bigint NOT NULL, " + + "reaction varchar(16) NOT NULL, " + + "PRIMARY KEY (chat_type, chat_id, message_id, person_id, reaction))"; + + private static final Logger logger = LoggerFactory.getLogger(MessageReactionTableInitializer.class); + + private final JdbcTemplate jdbcTemplate; + + @Bean + public ApplicationRunner migrateMessageReaction() { + return args -> { + try { + jdbcTemplate.execute(CREATE_TABLE); + } catch (DataAccessException e) { + // The rest of Spring keeps running, as it does when another table can't be made. + // Until the table exists the reaction routes fail, and deleting a message still + // works but logs that its reactions couldn't be removed. + logger.error("Could not create the message_reaction table, so reactions won't work: {}", e.getMessage()); + } + }; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/Reaction.java b/src/main/java/com/open/spring/mvc/reactions/Reaction.java new file mode 100644 index 00000000..bb778d61 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/Reaction.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import java.util.Arrays; +import java.util.Optional; + +/** + * The emoji a message can get. A row stores the enum name; routes and JSON use the lowercase + * key. Pages' Messages reactions.js lists the same keys in the same order, so change both + * together. + */ +public enum Reaction { + LIKE("like"), + LOVE("love"), + HAHA("haha"), + WOW("wow"), + SAD("sad"), + CELEBRATE("celebrate"); + + private final String key; + + Reaction(String key) { + this.key = key; + } + + /** The lowercase name a route and the page use, such as "like". */ + public String key() { + return key; + } + + /** The reaction with exactly this key, or empty for anything else, "LIKE" included. */ + public static Optional fromKey(String key) { + return Arrays.stream(values()).filter(reaction -> reaction.key.equals(key)).findFirst(); + } +} diff --git a/src/main/resources/data/permissions.json b/src/main/resources/data/permissions.json index 579ed3f9..607f05ef 100644 --- a/src/main/resources/data/permissions.json +++ b/src/main/resources/data/permissions.json @@ -476,6 +476,9 @@ "POST /api/dm/conversations/{id}/messages", "DELETE /api/dm/conversations/{id}/messages/{messageId}", "PATCH /api/dm/conversations/{id}/messages/{messageId}", + "DELETE /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "PUT /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "GET /api/dm/conversations/{id}/reactions", "POST /api/dm/conversations/{id}/read", "GET /api/dm/search", "GET /api/dm/unread", @@ -531,6 +534,9 @@ "POST /api/groups/chat/{groupId}/messages", "DELETE /api/groups/chat/{groupId}/messages/{messageId}", "PATCH /api/groups/chat/{groupId}/messages/{messageId}", + "DELETE /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "PUT /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "GET /api/groups/chat/{groupId}/reactions", "POST /api/groups/chat/{groupId}/read", "PUT /api/groups/class-memberships", "GET /api/groups/person/{personId}", 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/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java new file mode 100644 index 00000000..04197e05 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -0,0 +1,255 @@ +package com.open.spring.mvc.directmessages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a direct message: only participants, never on a deleted message, broadcast as a + * "reactions" frame, and never a phone notification or a change to what is unread. + */ +class DirectMessageReactionTest { + + private DirectMessageConversationJpaRepository conversationRepository; + private DirectMessageJpaRepository messageRepository; + private DirectMessageReadStateJpaRepository readStateRepository; + private SimpMessagingTemplate messagingTemplate; + private PushNotificationService pushNotificationService; + private MessageReactionService reactionService; + private PersonJpaRepository personRepository; + private DirectMessageService service; + private DirectMessageApiController controller; + private Person alice; + private Person bob; + private DirectMessageConversation conversation; + private DirectMessage message; + private List summaries; + + @BeforeEach + void setUp() { + conversationRepository = mock(DirectMessageConversationJpaRepository.class); + messageRepository = mock(DirectMessageJpaRepository.class); + readStateRepository = mock(DirectMessageReadStateJpaRepository.class); + messagingTemplate = mock(SimpMessagingTemplate.class); + pushNotificationService = mock(PushNotificationService.class); + reactionService = mock(MessageReactionService.class); + personRepository = mock(PersonJpaRepository.class); + service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, + messagingTemplate, pushNotificationService, reactionService); + controller = new DirectMessageApiController(service, conversationRepository, messageRepository, + personRepository, reactionService); + + alice = person(1L, "alice"); + bob = person(2L, "bob"); + Person carol = person(3L, "carol"); + when(personRepository.findByUid("alice")).thenReturn(alice); + when(personRepository.findByUid("carol")).thenReturn(carol); + + conversation = new DirectMessageConversation(List.of(alice, bob)); + ReflectionTestUtils.setField(conversation, "id", 7L); + when(conversationRepository.findById(7L)).thenReturn(Optional.of(conversation)); + + message = new DirectMessage(conversation, bob, "did anyone finish the FRQ?"); + ReflectionTestUtils.setField(message, "id", 42L); + when(messageRepository.findByIdAndConversation(42L, conversation)).thenReturn(Optional.of(message)); + + summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); + when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(summaries); + } + + @Test + void aReactionGoesOutAsAReactionsFrame() { + List result = service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verify(reactionService).add(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("reactions", frame.getValue().getType()); + assertEquals(42L, frame.getValue().getId()); + assertEquals(7L, frame.getValue().getConversationId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void theFrameGoesOutAfterTheCommitWithReactionsReadThen() { + // Read after the commit, the list has a reaction someone else committed at the same time. + List fresh = List.of(new ReactionSummary("like", + List.of(new Reactor("alice", "alice"), new Reactor("bob", "bob")))); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(fresh); + TransactionSynchronizationManager.initSynchronization(); + try { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + verify(messagingTemplate, never()).convertAndSend(eq("/topic/dm/7"), any(Object.class)); + + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals(fresh, frame.getValue().getReactions()); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void takingAReactionBackRemovesIt() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); + + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aReactionSendsNoPushAndLeavesReadStateAlone() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verifyNoInteractions(pushNotificationService, readStateRepository); + } + + @Test + void aDeletedMessageCannotBeReactedTo() { + message.setDeleted(true); + + assertThrows(IllegalStateException.class, + () -> service.setReaction(conversation, alice, 42L, Reaction.LIKE, true)); + assertEquals(HttpStatus.CONFLICT, controller.addReaction(signedIn("alice"), 7L, 42L, "like").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aMessageFromAnotherConversationIsNotFound() { + when(messageRepository.findByIdAndConversation(99L, conversation)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, + () -> service.setReaction(conversation, alice, 99L, Reaction.LIKE, true)); + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(signedIn("alice"), 7L, 99L, "like").getStatusCode()); + } + + @Test + void anUnknownReactionIs400() { + ResponseEntity response = controller.addReaction(signedIn("alice"), 7L, 42L, "thumbsup"); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void onlyASignedInParticipantMayReactOrList() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(null, 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removeReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.getReactions(signedIn("carol"), 7L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void theRoutesAnswerWithTheMessagesReactions() { + ResponseEntity added = controller.addReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions("42", summaries), added.getBody()); + + ResponseEntity removed = controller.removeReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + + Map> byMessage = Map.of("42", summaries); + when(reactionService.forChat(ChatType.DM, 7L)).thenReturn(byMessage); + ResponseEntity listed = controller.getReactions(signedIn("alice"), 7L); + assertEquals(HttpStatus.OK, listed.getStatusCode()); + assertEquals(byMessage, listed.getBody()); + } + + @Test + void deletingAMessageRemovesItsReactions() { + service.deleteMessage(conversation, bob, 42L); + + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } + + @Test + void aDeleteStillGoesThroughWhenItsReactionsCantBeRemoved() { + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + TransactionSynchronizationManager.initSynchronization(); + try { + service.deleteMessage(conversation, bob, 42L); + + // Nothing in the delete's own transaction touches the reactions, so they can't undo it. + verify(reactionService, never()).removeAllFor(any(), any(), any()); + assertTrue(message.isDeleted()); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("deleted", frame.getValue().getType()); + + // Once it commits they're removed, and a failure there is logged, not thrown at the caller. + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("message").id(1L).conversationId(7L).body("hi").build()); + String reactionsFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("reactions").id(1L).conversationId(7L).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private static UserDetails signedIn(String uid) { + return User.withUsername(uid).password("unused").build(); + } + + private static Person person(Long id, String uid) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(uid); + return person; + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java index dbde1e3e..2845cfed 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.push.PushNotificationService; import com.open.spring.mvc.push.PushSubscriptionJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; @@ -144,7 +145,8 @@ void setUp() { }), new ObjectMapper(), "", "", ""); service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, - new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService); + new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService, + org.mockito.Mockito.mock(MessageReactionService.class)); } @Test diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java index d2f192fc..3d3e00ae 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java @@ -65,6 +65,35 @@ void tearDown() { broker.stop(); } + /** A group chat reader, signed out like a course chat visitor, must not get a frame a client made up. */ + @Test + void aClientSendToAGroupTopicReachesNobody() { + connect("reader-socket"); + connect("outsider-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + StompHeaderAccessor send = StompHeaderAccessor.create(StompCommand.SEND); + send.setSessionId("outsider-socket"); + send.setSessionAttributes(Map.of()); + send.setDestination("/topic/group/7"); + clientInbound.send(MessageBuilder.createMessage( + "{\"context\":\"sendMessageServer\",\"groupId\":7,\"sender\":\"Thomas Edison\",\"message\":\"FAKE: click this link\"}" + .getBytes(StandardCharsets.UTF_8), + send.getMessageHeaders())); + + assertEquals(List.of(), socketsThatReceivedSomething()); + } + + @Test + void theServersGroupBroadcastStillReachesSignedOutReaders() { + connect("reader-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + serverBroadcast("/topic/group/7", "{\"context\":\"sendMessageServer\",\"message\":\"hello class\"}"); + + assertEquals(List.of("reader-socket"), socketsThatReceivedSomething()); + } + /** * Spring turns SUBSCRIBE /user/X into a subscription to X + "-user" + the session id, which a * SockJS client picks itself. Session id "}" closes the brace this destination opens, so the diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java index e2fd0814..834b7d24 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java @@ -91,10 +91,12 @@ void userDestinationsAreRefused() { assertNull(guard.preSend(frame(StompCommand.SEND, "/user/hop/queue/messages", SIGNED_OUT), channel)); } - @Test - void clientCannotSendToADmTopic() { - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", HOP), channel)); - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", SIGNED_OUT), channel)); + /** The broker relays a client's SEND to every subscriber of any destination starting with /topic. */ + @ParameterizedTest + @ValueSource(strings = {"/topic/dm/1", "/topic/group/7", "/topic/anything", "/topicx"}) + void clientCannotSendToAnyTopic(String destination) { + assertNull(guard.preSend(frame(StompCommand.SEND, destination, HOP), channel)); + assertNull(guard.preSend(frame(StompCommand.SEND, destination, SIGNED_OUT), channel)); } @Test diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java new file mode 100644 index 00000000..16f5cefe --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -0,0 +1,290 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +/** + * Editing and deleting a message read the group's whole messages file, change it and write the + * file back. When S3 can't do either for a moment, the route must say so (503) instead of + * answering as if the change was saved. + */ +class GroupChatEditDeleteTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** Grace's message in a bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404. */ + private void useFreshStorage() { + objects.clear(); + objects.put(MESSAGES_KEY, GRACE_LINE.getBytes(StandardCharsets.UTF_8)); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + + /** The edit and delete routes over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity edit() { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage("Meeting at 3"); + return controller.editMessage(7L, "m2", request); + } + + private ResponseEntity delete() { + return controller.deleteMessage(7L, "m2"); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + /** S3 fails the read of the messages file, or the upload after it. */ + private void failS3(boolean onRead, RuntimeException failure) { + if (onRead) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } else { + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + } + + /** S3 failing for a moment, on the read or the upload, gets a 503 with Retry-After and changes nothing. */ + private void assertRefusedForNow(Supplier> change) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + failS3(onRead, failure); + String what = (onRead ? "read: " : "upload: ") + failure; + + ResponseEntity response = change.get(); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), what + ", Retry-After: " + retryAfter); + assertEquals(GRACE_LINE, storedMessages(), what); + // The group isn't told about a change that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + + @Test + void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { + assertEquals(HttpStatus.OK, edit().getStatusCode()); + GroupChatMessage saved = new ObjectMapper().readValue(storedMessages(), GroupChatMessage.class); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + + assertEquals(HttpStatus.OK, delete().getStatusCode()); + assertEquals("", storedMessages()); + } + + @Test + void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + // The first read of S3 works, and every read after it fails as a throttle. + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = edit(); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List answered = (List) response.getBody(); + assertEquals(1, answered.size(), "answered: " + answered); + GroupChatMessage saved = (GroupChatMessage) answered.get(0); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + } + + @Test + void aDeleteOfAMessageThatIsntSavedAnswers404AndTellsNoOne() { + ResponseEntity response = controller.deleteMessage(7L, "not-a-saved-id"); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(GRACE_LINE, storedMessages()); + // Telling the group would take the message off everyone's screen. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void withoutS3SettingsADeleteAnswers404AndTellsNoOne() { + // A local server without S3 saves nothing, so there's no message to delete, whoever sent it. + wire(new S3FileHandler()); + + ResponseEntity response = delete(); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { + assertRefusedForNow(this::edit); + } + + @Test + void aDeleteS3CantReadOrSaveForAMomentAnswers503AndKeepsTheMessage() { + assertRefusedForNow(this::delete); + } + + @Test + void anEditOrDeleteS3RefusesOrABugHereIsNotOfferedARetry() { + List>> changes = List.of(this::edit, this::delete); + for (Supplier> change : changes) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + failS3(onRead, fault); + String what = (onRead ? "read: " : "upload: ") + fault; + + ResponseEntity response = change.get(); + + assertFalse(response.getStatusCode().is2xxSuccessful(), what); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), what); + assertEquals(GRACE_LINE, storedMessages(), what); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + } + + @Test + void everyReadOrUploadThatFailsIsLoggedWithTheGroupAndTheCause() { + Logger logger = (Logger) LoggerFactory.getLogger(GroupChatService.class); + ListAppender warnings = new ListAppender<>(); + warnings.start(); + logger.addAppender(warnings); + try { + List failures = new ArrayList<>(S3Failures.unavailable()); + failures.addAll(S3Failures.refusalsAndBugs()); + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : failures) { + useFreshStorage(); + failS3(onRead, failure); + warnings.list.clear(); + + edit(); + + String what = (onRead ? "read: " : "upload: ") + failure; + // The route answers some of these without logging, so the service logs each one. + assertTrue(warnings.list.stream().anyMatch(warning -> + warning.getFormattedMessage().contains("CSA") + && warning.getThrowableProxy() != null + && failure.getClass().getName().equals(warning.getThrowableProxy().getClassName())), + what + " was not logged: " + warnings.list); + } + } + } finally { + logger.detachAppender(warnings); + warnings.stop(); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1f..ad542f0a 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -40,7 +40,9 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -61,6 +63,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 +98,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; @@ -104,10 +142,10 @@ private void useStorage(InMemoryStorage store) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); + GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging, mock(MessageReactionService.class)); GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = new Groups(); group.setName("CSA"); @@ -323,6 +361,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..068ed7cf 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,14 +54,15 @@ 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.isConfigured()).thenReturn(true); + when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); service.addMessage("CSA", new GroupChatMessage("Grace Hopper", "hop", "hello", "2026-10-30T17:00:00Z", null)); ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); - verify(s3).uploadFile(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); + verify(s3).uploadFileOrThrow(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); String[] lines = new String(Base64.getDecoder().decode(uploaded.getValue()), StandardCharsets.UTF_8).split("\n"); assertEquals("Ada Lovelace", objectMapper.readTree(lines[0]).get("author").asText()); assertEquals("Grace Hopper", objectMapper.readTree(lines[1]).get("author").asText()); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java new file mode 100644 index 00000000..4bd46524 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java @@ -0,0 +1,144 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * A group's messages file can hold a line that doesn't read as a message, and a message can + * fail to be written. Neither may quietly lose a message when the file is saved again. + */ +class GroupChatMessagesFileTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + // A line that isn't a whole message: S3 holds it, but it doesn't read as JSON. + private static final String UNREADABLE = "{\"id\":\"m0\",\"author\":\"Ada Lovelace\",\"message\":\"Agenda for"; + + /** A configured S3 kept in a map, whose reads and writes never fail. */ + static class InMemoryS3 extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String decodeFile(String uid, String filename) { + return objects.get(uid + "/" + filename); + } + + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private InMemoryS3 storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new InMemoryS3(); + chat = new GroupChatService(storage, json); + } + + private void store(String... lines) { + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private List storedLines() { + String base64 = storage.objects.get(MESSAGES_KEY); + return List.of(new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8).split("\n")); + } + + private String text(String line) throws Exception { + return json.readValue(line, GroupChatMessage.class).getMessage(); + } + + @Test + void anUnreadableLineIsKeptWhereItWasWhenAMessageIsSent() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + chat.addMessage("CSA", new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-21T10:06:00Z", null)); + + List lines = storedLines(); + assertEquals(4, lines.size(), lines.toString()); + assertEquals("Meeting at 3", text(lines.get(0))); + assertEquals(UNREADABLE, lines.get(1)); + assertEquals("Meetign at 3", text(lines.get(2))); + assertEquals("Works for me", text(lines.get(3))); + } + + @Test + void anUnreadableLineIsKeptWhenAMessageIsEditedOrDeleted() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + assertTrue(chat.editMessage("CSA", "m2", "Meeting at 3", "grace").isPresent()); + List lines = storedLines(); + assertEquals(3, lines.size(), lines.toString()); + assertEquals(List.of("Meeting at 3", UNREADABLE, "Meeting at 3"), + List.of(text(lines.get(0)), lines.get(1), text(lines.get(2)))); + + assertTrue(chat.deleteMessage("CSA", "m1", "ada")); + lines = storedLines(); + assertEquals(2, lines.size(), lines.toString()); + assertEquals(UNREADABLE, lines.get(0)); + assertEquals("Meeting at 3", text(lines.get(1))); + } + + @Test + void loadingTheChatSkipsAnUnreadableLine() { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + List texts = chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList(); + + assertEquals(List.of("Meeting at 3", "Meetign at 3"), texts); + } + + @Test + void aMessageThatCantBeWrittenRefusesTheChangeAndKeepsTheFile() { + ObjectMapper failsOnOneMessage = new ObjectMapper() { + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + if (value instanceof GroupChatMessage message && "can't write me".equals(message.getMessage())) { + throw new JsonMappingException(null, "can't write this message"); + } + return super.writeValueAsString(value); + } + }; + chat = new GroupChatService(storage, failsOnOneMessage); + store(ADA_LINE); + + assertThrows(RuntimeException.class, () -> chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "can't write me", "2026-11-21T10:06:00Z", null))); + + assertEquals(List.of(ADA_LINE), storedLines()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java new file mode 100644 index 00000000..314a7ae0 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -0,0 +1,207 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a group chat message: signed in, a real message id, broadcast as a + * reactionsServer frame, and never a read or write of the group's S3 message file. + */ +class GroupChatReactionTest { + + private static final String MESSAGE_ID = "3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10"; + + private S3FileHandler storage; + private GroupChatService chat; + private SimpMessagingTemplate messaging; + private MessageReactionService reactionService; + private GroupChatRealtimeService realtime; + private GroupChatApiController controller; + private Person ada; + private List summaries; + + @BeforeEach + void setUp() { + storage = mock(S3FileHandler.class); + chat = spy(new GroupChatService(storage, new ObjectMapper())); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + reactionService = mock(MessageReactionService.class); + realtime = new GroupChatRealtimeService(chat, groups, messaging, reactionService); + PersonJpaRepository people = mock(PersonJpaRepository.class); + GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, reactionService); + + Groups group = spy(new Groups()); + when(group.getId()).thenReturn(3L); + group.setName("Team Three"); + when(groups.findById(3L)).thenReturn(Optional.of(group)); + + ada = new Person(); + ReflectionTestUtils.setField(ada, "id", 1L); + ada.setUid("ada"); + ada.setName("Ada"); + when(people.findByUid("ada")).thenReturn(ada); + + summaries = List.of(new ReactionSummary("love", List.of(new Reactor("ada", "Ada")))); + when(reactionService.forMessage(ChatType.GROUP, 3L, MESSAGE_ID)).thenReturn(summaries); + } + + @AfterEach + void clearAuthentication() { + SecurityContextHolder.clearContext(); + } + + @Test + void aReactionGoesOutAsAReactionsServerFrame() { + List result = realtime.setReaction(3L, ada, MESSAGE_ID, Reaction.LOVE, true); + + verify(reactionService).add(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("reactionsServer", frame.getValue().getContext()); + assertEquals(3L, frame.getValue().getGroupId()); + assertEquals(MESSAGE_ID, frame.getValue().getMessageId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void aReactionNeverTouchesTheGroupsFile() { + signIn("ada"); + + ResponseEntity added = controller.addReaction(3L, MESSAGE_ID, "love"); + ResponseEntity removed = controller.removeReaction(3L, MESSAGE_ID, "love"); + when(reactionService.forChat(ChatType.GROUP, 3L)).thenReturn(java.util.Map.of(MESSAGE_ID, summaries)); + ResponseEntity listed = controller.getReactions(3L); + + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions(MESSAGE_ID, summaries), added.getBody()); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + assertEquals(java.util.Map.of(MESSAGE_ID, summaries), listed.getBody()); + verifyNoInteractions(storage); + } + + @Test + void signedOutIs401() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.removeReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.getReactions(3L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void aBadMessageIdIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + // Saved ids are lowercase; an uppercase one would match some lookups and not others on MySQL. + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID.toUpperCase(), "love").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownReactionIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID, "thumbsup").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownGroupIs404() { + signIn("ada"); + + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(99L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, controller.getReactions(99L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void deletingAMessageRemovesItsReactions() { + GroupChatMessage saved = new GroupChatMessage("Ada", "ada", "hello", "2026-11-21T00:00:00Z", null); + // The chat's delete reads S3 itself and says whether it found the message. + doReturn(true).when(chat).deleteMessage("Team Three", saved.getId(), "ada"); + + realtime.deleteMessage(3L, saved.getId(), "ada"); + + verify(reactionService).removeAllFor(ChatType.GROUP, 3L, saved.getId()); + } + + @Test + void deletingAMessageThatIsntSavedKeepsItsReactions() { + doReturn(false).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + + assertFalse(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + verify(reactionService, never()).removeAllFor(any(), any(), any()); + } + + @Test + void aDeleteStillTellsTheGroupWhenItsReactionsCantBeRemoved() { + doReturn(true).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.GROUP, 3L, MESSAGE_ID); + + assertTrue(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("deleteMessageServer", frame.getValue().getContext()); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("sendMessageServer").groupId(3L).messageId(MESSAGE_ID).message("hi").build()); + String reactionsFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("reactionsServer").groupId(3L).messageId(MESSAGE_ID).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private void signIn(String uid) { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(uid, null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java index c310e301..f5d42c40 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -13,14 +14,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.http.HttpStatus; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -30,8 +35,11 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; class GroupChatRegressionTest { + private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; + private S3FileHandler storage; private GroupChatService chat; private GroupsJpaRepository groups; @@ -50,9 +58,9 @@ void setUp() { groups = mock(GroupsJpaRepository.class); readStates = mock(GroupChatReadStateJpaRepository.class); reads = new GroupChatReadService(readStates, groups, chat); - realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class)); + realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class), mock(MessageReactionService.class)); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = spy(new Groups()); when(group.getId()).thenReturn(7L); @@ -74,6 +82,49 @@ void setUp() { "2026-10-30T00:00:00Z", null); messages = new ArrayList<>(List.of(message)); doReturn(messages).when(chat).getMessages("CSA"); + // Edits and deletes read the messages file strictly and save it back, so S3 stands in + // for both: a read answers what's in `messages` at that moment, and a save replaces it. + when(storage.isConfigured()).thenReturn(true); + when(storage.decodeFileOrThrow("CSA", MESSAGES_FILE)).thenAnswer(call -> jsonlBase64(messages)); + doAnswer(call -> { + List saved = parse(call.getArgument(0)); + messages.clear(); + messages.addAll(saved); + return MESSAGES_FILE; + }).when(storage).uploadFileOrThrow(anyString(), eq(MESSAGES_FILE), eq("CSA")); + } + + private String jsonlBase64(List stored) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = stored.stream().map(m -> { + try { + return json.writeValueAsString(m); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }).collect(Collectors.joining("\n")); + return Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + } + + /** The messages each save wrote, in order. */ + private List> saves(int expected) throws Exception { + ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); + verify(storage, times(expected)).uploadFileOrThrow(uploaded.capture(), eq(MESSAGES_FILE), eq("CSA")); + List> saves = new ArrayList<>(); + for (String base64 : uploaded.getAllValues()) { + saves.add(parse(base64)); + } + return saves; + } + + private static List parse(String base64) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8); + List saved = new ArrayList<>(); + for (String line : jsonl.split("\n")) { + if (!line.isBlank()) saved.add(json.readValue(line, GroupChatMessage.class)); + } + return saved; } @AfterEach @@ -82,18 +133,20 @@ void clearAuthentication() { } @Test - void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() { + void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() throws Exception { person.setName("Renamed Owner"); signIn("owner"); GroupChatMessage request = new GroupChatMessage(); request.setMessage("updated"); assertEquals(HttpStatus.OK, controller.editMessage(7L, message.getId(), request).getStatusCode()); - assertEquals("updated", message.getMessage()); - assertTrue(message.isEdited()); assertEquals(HttpStatus.OK, controller.deleteMessage(7L, message.getId()).getStatusCode()); + List> saves = saves(2); + assertEquals(1, saves.get(0).size()); + assertEquals("updated", saves.get(0).get(0).getMessage()); + assertTrue(saves.get(0).get(0).isEdited()); + assertTrue(saves.get(1).isEmpty()); assertTrue(messages.isEmpty()); - verify(storage, times(2)).uploadFile(anyString(), eq("messages-images/messages.jsonl"), eq("CSA")); } @Test @@ -104,9 +157,9 @@ void sameDisplayNameDoesNotAuthorizeAnotherAccount() { assertEquals(HttpStatus.FORBIDDEN, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, controller.deleteMessage(7L, message.getId()).getStatusCode()); - assertEquals("original", message.getMessage()); assertEquals(1, messages.size()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + assertEquals("original", messages.get(0).getMessage()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -117,7 +170,7 @@ void unauthenticatedRequestsCannotEditOrDelete() { assertEquals(HttpStatus.UNAUTHORIZED, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.UNAUTHORIZED, controller.deleteMessage(7L, message.getId()).getStatusCode()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -128,7 +181,7 @@ void missingAuthorUidDoesNotFallBackToDisplayName() { () -> chat.editMessage("CSA", message.getId(), "updated", "owner")); assertThrows(SecurityException.class, () -> chat.deleteMessage("CSA", message.getId(), "owner")); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java new file mode 100644 index 00000000..f8e71a46 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,258 @@ +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.doAnswer; +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 java.util.concurrent.atomic.AtomicInteger; + +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.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; + +/** + * 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); + } + + /** The first read of S3 works, and every read after it fails as a throttle. */ + private void failReadsAfterTheFirst() { + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + + @Test + void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { + for (RuntimeException failure : S3Failures.unavailable()) { + 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() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + 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 anUploadThatFailsForAMomentRefusesTheSendWithA503AndKeepsTheHistory() { + // The read works, and then S3 can't take the upload for a moment. + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // A message that wasn't saved isn't shown to the group as sent. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aSendAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failReadsAfterTheFirst(); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List texts = ((List) response.getBody()).stream() + .map(saved -> ((GroupChatMessage) saved).getMessage()) + .toList(); + assertEquals(List.of("Meeting at 3", "Works for me"), texts); + } + + @Test + void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + 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..be0dd3c0 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -0,0 +1,158 @@ +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); + + // A configured S3 whose writes never fail. + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String uploadFileOrThrow(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 the strict read a change makes 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/S3Failures.java b/src/test/java/com/open/spring/mvc/groups/S3Failures.java new file mode 100644 index 00000000..344b77e8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/S3Failures.java @@ -0,0 +1,35 @@ +package com.open.spring.mvc.groups; + +import java.util.List; + +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** The S3 failures the group chat tests throw from a stand-in S3 client. */ +final class S3Failures { + + private S3Failures() { + } + + /** + * S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + * comes as a 400): failures that clear if you wait. + */ + static List unavailable() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + } + + /** No permission, a bad key, or a fault in this server: waiting won't fix these. */ + static List refusalsAndBugs() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + } +} 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); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java new file mode 100644 index 00000000..6b45dca8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java @@ -0,0 +1,64 @@ +package com.open.spring.mvc.push; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +/** + * The text a phone shows for a direct message: the words a reader sees in the chat, without + * the markers the page reads ([[reply:…]], [[files:…]], [[code:…]], [[pin:…]]) or the rich + * composer's HTML. + */ +class PushNotificationSnippetTest { + + @Test + void chatMarkersAreLeftOut() { + assertEquals("thanks!", PushNotificationService.snippet("[[reply:9|Bob|hey%20there]] thanks!")); + assertEquals("look", PushNotificationService.snippet("[[files:f~shots%2Fa.png~5]] look")); + // Pages escapes brackets, "|", "%", "<", ">" and "&" in code, but keeps quotes, tabs and newlines. + assertEquals("try this", PushNotificationService.snippet( + "[[code:python|print(\"hi\")\nfor i in range(3):\n\tprint(i)]] try this")); + assertEquals("see this", PushNotificationService.snippet( + "[[reply:9|Bob|hey]] [[files:f~a.txt~1]] [[code:java|int x;]] see this")); + } + + @Test + void aMessageThatIsOnlyAMarkerSaysWhatItDid() { + assertEquals("pinned a message", PushNotificationService.snippet("[[pin:401]]")); + assertEquals("unpinned a message", PushNotificationService.snippet("[[unpin:401]]")); + assertEquals("sent code", PushNotificationService.snippet("[[code:python|print(1)]]")); + assertEquals("shared files", PushNotificationService.snippet("[[files:f~a.png~5]]")); + // A reply that only attaches an image has nothing but its reply marker in the body. + assertEquals("sent a message", PushNotificationService.snippet("[[reply:9|Bob|hey]]")); + } + + @Test + void theComposersHtmlBecomesPlainText() { + assertEquals("check https://github.com/o/r/pull/3", PushNotificationService.snippet( + "check " + + "https://github.com/o/r/pull/3 ")); + assertEquals("Fish & chips tonight", PushNotificationService.snippet("Fish & chips
    tonight")); + assertEquals("a < b", PushNotificationService.snippet("a < b")); + } + + @Test + void longTextIsCutAndBlankStaysBlank() { + String cut = PushNotificationService.snippet("x".repeat(200)); + assertEquals(140, cut.length()); + assertEquals('…', cut.charAt(139)); + assertEquals("", PushNotificationService.snippet(null)); + assertEquals("", PushNotificationService.snippet(" ")); + } + + @Test + void markerOpeningsThatNeverCloseStayFast() { + // None of these markers closes, so a pattern that rescans the rest of the body at each + // "[[" takes seconds here; matching has to stay linear. + String body = "[[code:".repeat(20_000); + String text = assertTimeoutPreemptively(Duration.ofSeconds(1), () -> PushNotificationService.snippet(body)); + assertEquals(140, text.length()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java new file mode 100644 index 00000000..aa27a3c2 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -0,0 +1,171 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; + +/** + * Saving a reaction once, removing it safely, and the summaries both chats send: reactions in + * the enum's order, people by name, and nobody listed who no longer has an account. + */ +class MessageReactionServiceTest { + + private MessageReactionJpaRepository repository; + private MessageReactionService service; + // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. + private Person ada; + private Person ana; + private Person ben; + + @BeforeEach + void setUp() { + repository = mock(MessageReactionJpaRepository.class); + service = new MessageReactionService(repository); + ada = person(1L, "ada", "ada"); + ana = person(2L, "ana", "Ana"); + ben = person(3L, "ben", "Ben"); + } + + @Test + void addSavesANewReactionOnce() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(true); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).save(any()); + + when(repository.existsById(key)).thenReturn(false); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).save(new MessageReaction(key)); + } + + @Test + void removeIsOneDeleteStatement() { + // Read-then-delete let two removes at once fail the second; one statement just deletes 0 rows. + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + + verify(repository).deleteOne(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + verify(repository, never()).existsById(any()); + verify(repository, never()).deleteById(any()); + } + + @Test + void summariesFollowTheTableOrderAndSortPeople() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ben), name(ana), name(ada))); + + List summaries = service.forMessage(ChatType.DM, 7L, "42"); + + assertEquals(List.of( + new ReactionSummary("like", List.of(new Reactor("ada", "ada"), new Reactor("ana", "Ana"))), + new ReactionSummary("wow", List.of(new Reactor("ben", "Ben")))), summaries); + } + + @Test + void aPersonWhoIsGoneIsLeftOut() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); + // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + service.forMessage(ChatType.DM, 7L, "42")); + } + + @Test + void forMessageNowReadsTheSameSummary() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(service.forMessage(ChatType.DM, 7L, "42"), service.forMessageNow(ChatType.DM, 7L, "42")); + } + + @Test + void forChatKeysByMessageId() { + when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( + row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), + row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), + row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada), name(ben))); + + Map> byMessage = service.forChat(ChatType.GROUP, 3L); + + // "60" is left out: its only reaction is from someone whose account is gone. + assertEquals(Map.of( + "42", List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + "57", List.of(new ReactionSummary("haha", List.of(new Reactor("ben", "Ben"))))), byMessage); + } + + @Test + void removeAllForDeletesThatMessagesReactionsInOneStatement() { + service.removeAllFor(ChatType.GROUP, 3L, "abc"); + + verify(repository).deleteAllOnMessage(ChatType.GROUP, 3L, "abc"); + } + + // Reactors are read as id, uid and name only, never as whole accounts with their links. + private static MessageReactionJpaRepository.ReactorName name(Person person) { + return new MessageReactionJpaRepository.ReactorName() { + @Override + public Long getId() { + return person.getId(); + } + + @Override + public String getUid() { + return person.getUid(); + } + + @Override + public String getName() { + return person.getName(); + } + }; + } + + private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { + return new MessageReaction(new MessageReaction.Key(type, chatId, messageId, personId, reaction)); + } + + private static Person person(long id, String uid, String name) { + Person person = new Person(); + // Submitter has no id setter; the DM tests set it the same way. + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(name); + return person; + } + + @Test + void removingAMessagesReactionsCommitsOnItsOwn() throws Exception { + // Chats remove a deleted message's reactions after the delete commits. Spring runs a + // transactional call made then inside the finished transaction, where nothing commits, + // unless it asks for a new one. + Transactional transactional = MessageReactionService.class + .getMethod("removeAllFor", ChatType.class, Long.class, String.class) + .getAnnotation(Transactional.class); + + assertEquals(Propagation.REQUIRES_NEW, transactional.propagation()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java new file mode 100644 index 00000000..27093fe6 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -0,0 +1,96 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +/** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ +class MessageReactionTableInitializerTest { + + private static final String INSERT = "INSERT INTO message_reaction " + + "(chat_type, chat_id, message_id, person_id, reaction) VALUES (?, ?, ?, ?, ?)"; + + private SingleConnectionDataSource dataSource; + private JdbcTemplate jdbc; + + @BeforeEach + void setUp() { + dataSource = new SingleConnectionDataSource("jdbc:sqlite::memory:", true); + jdbc = new JdbcTemplate(dataSource); + } + + @AfterEach + void tearDown() { + dataSource.destroy(); + } + + @Test + void createsTheTableAndCanRunTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + @Test + void rejectsTheSameReactionTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertThrows(DataAccessException.class, () -> jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE")); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LOVE"); + + assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + // Startup goes on, as it does for the other tables (calls, calendar), but the log says plainly + // that reactions are broken: a warning was easy to miss. + @Test + void aFailedCreateIsLoggedAsAnErrorAndStartupGoesOn() { + JdbcTemplate failing = new JdbcTemplate(dataSource) { + @Override + public void execute(String sql) { + throw new DataAccessResourceFailureException("the database is read-only"); + } + }; + ApplicationRunner runner = new MessageReactionTableInitializer(failing).migrateMessageReaction(); + Logger logger = (Logger) LoggerFactory.getLogger(MessageReactionTableInitializer.class); + Level previous = logger.getLevel(); + ListAppender logs = new ListAppender<>(); + logs.start(); + logger.addAppender(logs); + logger.setLevel(Level.INFO); + try { + assertDoesNotThrow(() -> runner.run(new DefaultApplicationArguments())); + } finally { + logger.detachAppender(logs); + logger.setLevel(previous); + logs.stop(); + } + + assertEquals(1, logs.list.size()); + ILoggingEvent event = logs.list.get(0); + assertEquals(Level.ERROR, event.getLevel()); + assertTrue(event.getFormattedMessage().contains("reactions won't work"), event.getFormattedMessage()); + assertTrue(event.getFormattedMessage().contains("the database is read-only"), event.getFormattedMessage()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java new file mode 100644 index 00000000..26f259e9 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +/** + * The reaction keys are a contract with the Pages client: Messages' reactions.js lists the + * same keys in the same order, and a route's {reaction} is read with fromKey. + */ +class ReactionTest { + + @Test + void everyKeyRoundTrips() { + for (Reaction reaction : Reaction.values()) { + assertEquals(Optional.of(reaction), Reaction.fromKey(reaction.key())); + } + List keys = Arrays.stream(Reaction.values()).map(Reaction::key).toList(); + assertEquals(List.of("like", "love", "haha", "wow", "sad", "celebrate"), keys); + } + + @Test + void unknownKeysAreRefused() { + assertTrue(Reaction.fromKey(null).isEmpty()); + assertTrue(Reaction.fromKey("").isEmpty()); + assertTrue(Reaction.fromKey("LIKE").isEmpty()); + assertTrue(Reaction.fromKey("thumbsup").isEmpty()); + } +}