Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions docs/group-chat-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,15 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`)
| Method | Route | Operation | Who |
|---|---|---|---|
| GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account |
| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. |
| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | Any signed-in account. The sender is the signed-in account. |
| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) |
| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) |
| GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You |
| 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
Expand All @@ -150,19 +150,25 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`)
| Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. |
| Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. |
| Messages | S3: `<group name>/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. |
| Shared files | S3: `<group name>/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: `<group name>/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. The write is strict too (`S3FileHandler.uploadFileOrThrow`): a failed write throws instead of answering null. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx (a throttle, an outage), checking or writing, that's a 503 with `Retry-After` (`SharedFileStorageUnavailableException`); S3 refusing the request (any other 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. |
| Presence | Memory only | Lost on restart; rebuilt as clients rejoin. |

- **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name.
- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server.
- **Every new message rewrites the whole file**, read then write, with no lock.
- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked.
- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing.
- **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows.
- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name.

## Testing

- `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group.
- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`.
- Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check.
- `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once.
- `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`.
- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`.
- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write.

## Known issues

Expand All @@ -173,7 +179,6 @@ These were each reproduced against a local server built from `master` on 2026-10
- **The client chooses the name for presence and typing.** `joinGroup`, `typingStart` and `heartbeat` use the `sender` field the client sends, even from a socket that isn't signed in.
- **No membership checks.** Any signed-in account can read and send in any group, list and upload its files, and manage any group, its members and its grades. The membership checks in `GroupChatApiController` are commented out.
- **Edit and delete require the stored author uid.** The REST controller passes the authenticated account's uid through the realtime service; display names never establish ownership. Legacy messages without `author_uid` cannot be edited or deleted through these routes. Teachers cannot delete another account's message.
- **Two sends at once can lose one.** Each send reads the group's S3 file, adds a line and writes the file back, without a lock.
- **The first group created after a restart fails on SQLite.** `POST /api/groups` returns 500 with `SQLITE_BUSY_SNAPSHOT` the first time after the server starts; the next attempt works. This is the `GenerationType.AUTO` lock problem described under Assignment grading in `AGENTS.md`, here on `submitter_seq`. Not checked on MySQL.

## Change checklist
Expand Down
12 changes: 10 additions & 2 deletions src/main/java/com/open/spring/StartupService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -25,9 +27,15 @@ public ApplicationRunner initializeGroupStorage() {
// Fetch all existing groups from the database
List<Groups> 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);
}
}
};
}
Expand Down
47 changes: 47 additions & 0 deletions src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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<GetObjectResponse> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@
@CrossOrigin
public class GroupChatApiController {

// How long to wait before sharing again when S3 couldn't check a path: a throttle or a
// short outage clears in seconds.
private static final int SHARE_RETRY_AFTER_SECONDS = 5;
// How long to wait before trying again when S3 was unavailable for a moment, checking or
// writing a shared file or reading a group's messages: a throttle or a short outage clears
// in seconds.
private static final int RETRY_AFTER_SECONDS = 5;

private final GroupChatService groupChatService;
private final GroupChatRealtimeService realtimeService;
Expand Down Expand Up @@ -192,6 +193,12 @@ public ResponseEntity<?> postMessage(

try {
realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity);
} catch (MessagesReadFailedException ex) {
// S3 couldn't read the history, so nothing was saved or broadcast: saving would have
// replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when.
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS))
.body(ex.getMessage());
} catch (RuntimeException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
Expand Down Expand Up @@ -399,14 +406,14 @@ public ResponseEntity<?> uploadSharedFile(
response.put("message", ex.getMessage());
response.put("filename", ex.getPath());
return new ResponseEntity<>(response, HttpStatus.CONFLICT);
} catch (SharedFileCheckFailedException ex) {
// S3 couldn't say whether the path is taken, so nothing was written. That's S3 being
// unavailable for a moment, not a bug here: a 503, and when to try again.
} catch (SharedFileStorageUnavailableException ex) {
// S3 was unavailable for a moment, checking the path or writing the file, so the file
// isn't shared. That's not a bug here: a 503, and when to try again.
Map<String, String> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,7 @@ public GroupChatEvent publishFile(Long groupId, String sender, String filename,
throw new IllegalArgumentException("Invalid file path");
}

String uploadResult = groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender);
if (uploadResult == null) {
throw new IllegalStateException("Upload failed");
}
groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender);

GroupChatEvent event = GroupChatEvent.builder()
.context("sendFileServer")
Expand Down
Loading