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
7 changes: 4 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,16 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`)

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

## Testing

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

## Known issues

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

## Change checklist
Expand Down
25 changes: 25 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 @@ -264,6 +264,31 @@ public boolean fileExistsOrThrow(String uid, String filename) {
}
}

/**
* Like decodeFile, but only "not found" (404) reads as nothing stored: any other failure to
* read (a throttle, a 5xx, no connection) throws. For a caller that writes back what it read,
* a read that failed is not an empty file. With no S3 client there is nothing to read and
* nothing can be written, so that reads as nothing stored, as in decodeFile.
*/
public String decodeFileOrThrow(String uid, String filename) {
if (s3Client == null) {
log.warn("S3 download attempted but S3 client is not configured.");
return null;
}
try {
ResponseBytes<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
132 changes: 85 additions & 47 deletions src/main/java/com/open/spring/mvc/groups/GroupChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public class GroupChatService {
private final S3FileHandler s3FileHandler;
private final ObjectMapper objectMapper;

// One lock per group for its messages file. Sending, editing and deleting each read the
// whole file, change it and write it back, so two at once would both change the same old
// copy and the later write would drop the other's change. This keeps them apart within
// this server only; several servers would need S3's conditional writes instead.
private final Map<String, Object> 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.
Expand Down Expand Up @@ -74,7 +80,33 @@ public void ensureGroupStorageExists(String groupName) {
}

public List<GroupChatMessage> getMessages(String groupName) {
String base64Data = s3FileHandler.decodeFile(groupName, MESSAGES_FILE);
return parseMessages(groupName, s3FileHandler.decodeFile(groupName, MESSAGES_FILE));
}

/**
* The group's messages for a send, which writes the whole file back. Strict: a read that
* failed throws rather than reading as an empty chat, which the send would save over the
* history. Only S3's 404 means no messages yet. S3 out of reach or answering a 5xx is
* something to wait out, so that throws MessagesReadFailedException; anything else goes up
* as it is.
*/
private List<GroupChatMessage> readMessagesOrThrow(String groupName) {
String base64Data;
try {
base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE);
} catch (SdkClientException | S3Exception e) {
// Logged for every failure: the route answers a refused read without logging it.
log.warn("Could not read the messages of group {}", groupName, e);
if (e instanceof S3Exception answered && answered.statusCode() < 500) {
// S3 refused the request (no permission, a bad key): waiting won't fix that.
throw e;
}
throw new MessagesReadFailedException(e);
}
return parseMessages(groupName, base64Data);
}

private List<GroupChatMessage> parseMessages(String groupName, String base64Data) {
if (base64Data == null || base64Data.isBlank()) {
return new ArrayList<>();
}
Expand Down Expand Up @@ -112,18 +144,20 @@ public List<GroupChatMessage> getMessages(String groupName) {
}

public List<GroupChatMessage> addMessage(String groupName, GroupChatMessage message) {
List<GroupChatMessage> messages = getMessages(groupName);
messages.add(message);
synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) {
List<GroupChatMessage> messages = readMessagesOrThrow(groupName);
messages.add(message);

String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));
String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));

String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));
String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));

s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
return messages;
s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
return messages;
}
}

/**
Expand All @@ -133,58 +167,62 @@ public List<GroupChatMessage> addMessage(String groupName, GroupChatMessage mess
*/
public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) {
if (messageId == null) return false;
List<GroupChatMessage> messages = getMessages(groupName);
boolean found = false;
for (GroupChatMessage m : messages) {
if (messageId.equals(m.getId())) {
if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) {
throw new SecurityException("Not the message sender");
synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) {
List<GroupChatMessage> messages = getMessages(groupName);
boolean found = false;
for (GroupChatMessage m : messages) {
if (messageId.equals(m.getId())) {
if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) {
throw new SecurityException("Not the message sender");
}
m.setMessage(newMessage);
m.setEdited(true);
found = true;
break;
}
m.setMessage(newMessage);
m.setEdited(true);
found = true;
break;
}
}

if (found) {
String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));
if (found) {
String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));

String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));
String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));

s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
}
return found;
}
return found;
}

/** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */
public void deleteMessage(String groupName, String messageId, String requesterUid) {
if (messageId == null) return;
List<GroupChatMessage> messages = getMessages(groupName);

GroupChatMessage target = messages.stream()
.filter(m -> messageId.equals(m.getId()))
.findFirst()
.orElse(null);
if (target == null) return;
if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) {
throw new SecurityException("Not the message sender");
}
synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) {
List<GroupChatMessage> messages = getMessages(groupName);

boolean removed = messages.remove(target);
GroupChatMessage target = messages.stream()
.filter(m -> messageId.equals(m.getId()))
.findFirst()
.orElse(null);
if (target == null) return;
if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) {
throw new SecurityException("Not the message sender");
}

if (removed) {
String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));
boolean removed = messages.remove(target);

String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));
if (removed) {
String jsonl = messages.stream()
.map(this::toJson)
.collect(Collectors.joining("\n"));

s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
String base64Data = Base64.getEncoder()
.encodeToString(jsonl.getBytes(StandardCharsets.UTF_8));

s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.open.spring.mvc.groups;

/**
* S3 couldn't read a group's messages for now: it timed out, couldn't be reached or answered
* with a 5xx (a throttle, an outage). A send writes the whole messages file back, so it's refused
* rather than save the new message over the history, and the API answers 503 with Retry-After,
* since S3 being unavailable for a moment isn't a bug in this server.
*/
public class MessagesReadFailedException extends RuntimeException {

public MessagesReadFailedException(Throwable cause) {
super("Could not read this group's messages, so the message was not sent. Try again in a moment.", cause);
}
}
Loading