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
9 changes: 6 additions & 3 deletions docs/group-chat-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`)
| Method | Route | Operation | Who |
|---|---|---|---|
| GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account |
| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. |
| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | Any signed-in account. The sender is the signed-in account. |
| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) |
| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) |
| GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You |
Expand All @@ -155,14 +155,18 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`)

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

## 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'`.

## Known issues

Expand All @@ -173,7 +177,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
30 changes: 30 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 Down Expand Up @@ -264,6 +269,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,9 @@
@CrossOrigin
public class GroupChatApiController {

// How long to wait before sharing again when S3 couldn't check a path: a throttle or a
// short outage clears in seconds.
private static final int SHARE_RETRY_AFTER_SECONDS = 5;
// How long to wait before trying again when S3 couldn't check a shared path or read a
// group's messages: a throttle or a short outage clears in seconds.
private static final int RETRY_AFTER_SECONDS = 5;

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

try {
realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity);
} catch (MessagesReadFailedException ex) {
// S3 couldn't read the history, so nothing was saved or broadcast: saving would have
// replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when.
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS))
.body(ex.getMessage());
} catch (RuntimeException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
Expand Down Expand Up @@ -406,7 +412,7 @@ public ResponseEntity<?> uploadSharedFile(
response.put("message", ex.getMessage());
response.put("filename", ex.getPath());
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, String.valueOf(SHARE_RETRY_AFTER_SECONDS))
.header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS))
.body(response);
} catch (RuntimeException ex) {
return new ResponseEntity<>("Upload failed", HttpStatus.INTERNAL_SERVER_ERROR);
Expand Down
Loading