Skip to content

Commit 9ff60da

Browse files
Minor Fix on the Collaboration Service (#86)
* Minor Fix on the Collaboration Service Database - Fix the part where the room is initialised as api/collaboration/room_id to only room_id * Minor Fix to Collaboration Service Based On Comments - Remove guard clause - Change the way of handling the authorise under webSocketService * Feed roomId as docName --------- Co-authored-by: Samuel Lim <[email protected]>
1 parent 1794597 commit 9ff60da

File tree

4 files changed

+29
-16
lines changed

4 files changed

+29
-16
lines changed

.env.sample

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,6 @@ YJS_DB_LOCAL_URI=mongodb://collaboration-db:27017/yjs-documents
2828
HISTORY_DB_CLOUD_URI=<FILL-THIS-IN>
2929
HISTORY_DB_LOCAL_URI=mongodb://history-db:27017/history
3030

31-
# Will use cloud MongoDB Atlas database
32-
ENV=PROD
33-
3431
# Broker
3532
BROKER_URL=amqp://broker:5672
3633

services/collaboration/src/controllers/roomController.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ export const updateUserStatusInRoomController = async (req: Request, res: Respon
154154

155155
// Check if all users in the room have forfeited
156156
const allUsersForfeited = updatedRoom.users.every(user => user.isForfeit === true);
157+
console.log('All users forfeited check:', allUsersForfeited, updatedRoom.users);
157158
if (allUsersForfeited) {
158159
// Close the room if both users have forfeited
159160
const result = await closeRoomById(roomId);

services/collaboration/src/services/mongodbService.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,10 @@ export const createYjsDocument = async (roomId: string) => {
132132
*/
133133
export const deleteYjsDocument = async (roomId: string) => {
134134
try {
135+
console.log(`Attempting to delete Yjs document collection for room: ${roomId}`);
135136
const db = await connectToYJSDB();
136-
await db.collection(roomId).drop();
137-
console.log(`Yjs document collection for room ${roomId} deleted`);
137+
const result = await db.collection(roomId).drop();
138+
console.log(`Yjs document collection for room ${roomId} deleted successfully: ${result}`);
138139
} catch (error) {
139140
console.error(`Failed to delete Yjs document for room ${roomId}:`, error);
140141
throw error;
@@ -196,6 +197,12 @@ export const closeRoomById = async (roomId: string) => {
196197
}
197198
};
198199

200+
/**
201+
* Update the user isForfeit status in a room
202+
* @param roomId
203+
* @param userId
204+
* @param isForfeit
205+
*/
199206
export const updateRoomUserStatus = async (roomId: string, userId: string, isForfeit: boolean) => {
200207
try {
201208
const db = await connectToRoomDB();

services/collaboration/src/services/webSocketService.ts

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,20 @@ const { setPersistence, setupWSConnection } = require('../utils/utility.js');
1111

1212
const URL_REGEX = /^.*\/([0-9a-f]{24})\?accessToken=([a-zA-Z0-9\-._~%]{1,})$/;
1313

14-
const authorize = async (ws: WebSocket, request: IncomingMessage): Promise<boolean> => {
14+
/**
15+
* Verifies the user's access to a specific room by validating the JWT token,
16+
* checking the room's status, and ensuring the user has not forfeited.
17+
* Returns `roomId` if the access is authorized, or `null` otherwise.
18+
* @param ws
19+
* @param request
20+
* @returns
21+
*/
22+
const authorize = async (ws: WebSocket, request: IncomingMessage): Promise<string | null> => {
1523
const url = request.url ?? '';
1624
const match = url?.match(URL_REGEX);
1725
if (!match) {
1826
handleAuthFailed(ws, 'Authorization failed: Invalid format');
19-
return false;
27+
return null;
2028
}
2129
const roomId = match[1];
2230
const accessToken = match[2];
@@ -34,27 +42,27 @@ const authorize = async (ws: WebSocket, request: IncomingMessage): Promise<boole
3442
});
3543
if (!user) {
3644
handleAuthFailed(ws, 'Authorization failed: Invalid token');
37-
return false;
45+
return null;
3846
}
3947

4048
const room = await findRoomById(roomId, user.id);
4149
if (!room) {
4250
handleAuthFailed(ws, 'Authorization failed');
43-
return false;
51+
return null;
4452
}
4553

4654
if (!room.room_status) {
4755
handleRoomClosed(ws);
48-
return false;
56+
return null;
4957
}
5058

5159
const userInRoom = room.users.find((u: { id: string }) => u.id === user.id);
5260
if (userInRoom?.isForfeit) {
5361
handleAuthFailed(ws, 'Authorization failed: User has forfeited');
54-
return false;
62+
return null;
5563
}
5664
console.log('WebSocket connection established for room:', roomId);
57-
return true;
65+
return roomId;
5866
};
5967

6068
/**
@@ -65,13 +73,13 @@ export const startWebSocketServer = (server: Server) => {
6573
const wss = new WebSocketServer({ server });
6674

6775
wss.on('connection', async (conn: WebSocket, req: IncomingMessage) => {
68-
const isAuthorized = await authorize(conn, req);
69-
if (!isAuthorized) {
76+
const roomId = await authorize(conn, req);
77+
if (!roomId) {
7078
return;
7179
}
7280

7381
try {
74-
setupWSConnection(conn, req);
82+
setupWSConnection(conn, req, { docName: roomId });
7583
} catch (error) {
7684
console.error('Failed to set up WebSocket connection:', error);
7785
handleAuthFailed(conn, 'Authorization failed');
@@ -85,7 +93,7 @@ export const startWebSocketServer = (server: Server) => {
8593
console.log(`Loaded persisted document for ${docName}`);
8694

8795
const newUpdates = Y.encodeStateAsUpdate(ydoc);
88-
mdb.storeUpdate(docName, newUpdates);
96+
await mdb.storeUpdate(docName, newUpdates);
8997

9098
Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(persistedYdoc));
9199

0 commit comments

Comments
 (0)