Skip to content

Commit b3c9236

Browse files
committed
Refactor code and include type use for websocket
1 parent fa3d6c9 commit b3c9236

File tree

5 files changed

+22
-163
lines changed

5 files changed

+22
-163
lines changed

Backend/MatchingService/rabbitmq/publisher.js

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@ async function publishToQueue({userId, difficulty, language}) {
88
const channel = await connection.createChannel();
99
const routingKey = `${difficulty}.${language}`;
1010

11-
// Connect to the exchange (just in case it does not exist)
12-
await channel.assertExchange(matching_exchange_name, 'topic', { durable: false });
13-
1411
// Publish the message to the exchange
1512
const messageSent = channel.publish(
1613
matching_exchange_name,

Backend/MatchingService/rabbitmq/setup.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ async function setupRabbitMQ() {
4646
await channel.bindQueue(queueName, matching_exchange_name, queueName); // Bind to exchange
4747
}
4848

49+
// Delete DLQ before asserting it
50+
await channel.deleteQueue(dead_letter_queue_name);
51+
4952
// Declare the dead-letter queue and bind it to the dead-letter exchange
5053
await channel.assertQueue(dead_letter_queue_name, { durable: false });
5154
await channel.bindQueue(dead_letter_queue_name, dead_letter_exchange_name, ''); // Bind with no routing key

Backend/MatchingService/rabbitmq/subscriber.js

Lines changed: 4 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -10,71 +10,10 @@ const { notifyUsers } = require('../websocket/websocket');
1010

1111
const dead_letter_queue_name = "dead_letter_queue";
1212
const timeoutMap = {};
13+
1314
// Local dictionary to store waiting users
1415
const waitingUsers = {};
1516

16-
// manual rejection of message that is constantly being consumed. Not using TTL feature.
17-
// Race condition: upon matching user 2 with user 1, the flag for whether user 1 is matched is still false.
18-
// async function consumeQueue() {
19-
// try {
20-
// // Connect
21-
// const connection = await amqp.connect(process.env.RABBITMQ_URL);
22-
// const channel = await connection.createChannel();
23-
24-
// console.log("Waiting for users...");
25-
26-
// // Process + subscribe to each matchmaking queue
27-
// for (let queueName of queueNames) {
28-
// await channel.consume(queueName, (msg) => {
29-
// if (msg !== null) {
30-
// const userData = JSON.parse(msg.content.toString());
31-
// const { userId, language, difficulty } = userData;
32-
33-
// // Perform the matching logic
34-
// console.log(`Received user ${userId} with ${language} and ${difficulty}`);
35-
// const matched = matchUsers(userId, language, difficulty);
36-
37-
// // Flag to track if a match is found
38-
// // let isMatched = false;
39-
// if (timeoutMap[userId]) {
40-
// clearTimeout(timeoutMap[userId]);
41-
// delete timeoutMap[userId];
42-
// }
43-
44-
// // Only acknowledge if a match was found
45-
// if (matched) {
46-
// // isMatched = true; // Set the flag
47-
// channel.ack(msg);
48-
// console.log(`Matched user ${userId}`);
49-
50-
// // clearTimeout(timeoutMap[userId]);
51-
// // delete timeoutMap[userId];
52-
// } else {
53-
// console.log(`No match for ${userId}, waiting for TTL to expire.`);
54-
55-
// // Set a timeout for rejection only if not matched
56-
// const timeoutId = setTimeout(() => {
57-
// // if (!isMatched) { // Check if matched after timeout
58-
// console.log(`is the user matched upon timeout? ${matched}`);
59-
// console.log(`Rejecting user ${userId} after 10 seconds.`);
60-
// channel.reject(msg, false); // Reject without requeuing
61-
// // }
62-
// }, 10000); // 10 seconds delay
63-
64-
// timeoutMap[userId] = timeoutId;
65-
// }
66-
// }
67-
// });
68-
// }
69-
70-
// console.log("Listening to matchmaking queues");
71-
// } catch (error) {
72-
// console.error('Error consuming RabbitMQ queue:', error);
73-
// }
74-
// }
75-
76-
77-
7817
// using promises to handle errors and ensure clearing of timer.
7918
function matchUsers(channel, msg, userId, language, difficulty) {
8019
const criteriaKey = `${difficulty}.${language}`;
@@ -93,7 +32,8 @@ function matchUsers(channel, msg, userId, language, difficulty) {
9332
console.log(`Matched users: ${matchedUsers.map(user => user.userId)}`);
9433

9534
// Send match success (this could trigger WebSocket communication)
96-
notifyUsers(matchedUsers.map(user => user.userId));
35+
// notifyUsers(matchedUsers.map(user => user.userId));
36+
notifyUsers(matchedUsers.map(user => user.userId), 'Match found!', 'match');
9737

9838
// Acknowledge the messages for both matched users
9939
matchedUsers.forEach(({ msg }) => {
@@ -191,7 +131,7 @@ async function consumeDLQ() {
191131
console.log(`Received message from DLQ for user: ${userId}`);
192132

193133
// Notify the user via WebSocket
194-
notifyUsers(userId, `Match not found for ${difficulty} ${language}, please try again.`);
134+
notifyUsers(userId, `Match not found for ${difficulty} ${language}, please try again.`, 'rejection');
195135

196136
// Acknowledge the message (so it's removed from the DLQ)
197137
channel.ack(msg);

Backend/MatchingService/services/matchingService.js

Lines changed: 0 additions & 91 deletions
This file was deleted.

Backend/MatchingService/websocket/websocket.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
// TODO: Write socket logic to connect backend to frontend here
2-
31
const WebSocket = require('ws');
42
const wss = new WebSocket.Server({ port: 8080 });
53

@@ -15,11 +13,23 @@ wss.on('connection', (ws) => {
1513
});
1614
});
1715

18-
function notifyUsers(userId, message) {
19-
console.log(`Notifying user: ${userId}, Message: ${message}`); // Add this log to track notifications
16+
/**
17+
* Notify users through WebSocket.
18+
* @param {string|array} userId - User ID or an array of user IDs to notify.
19+
* @param {string} message - The message to send.
20+
* @param {string} type - The type of message (e.g., 'match' or 'rejection').
21+
*/
22+
function notifyUsers(userId, message, type) {
23+
console.log(`Notifying user: ${userId}, Message: ${message}, Type: ${type}`); // Log message details
24+
2025
wss.clients.forEach((client) => {
2126
if (client.readyState === WebSocket.OPEN) {
22-
client.send(JSON.stringify({ userId, message }));
27+
// Construct the payload to include userId, message, and type
28+
client.send(JSON.stringify({
29+
userId,
30+
message,
31+
type // This allows the frontend to differentiate between match and rejection messages
32+
}));
2333
}
2434
});
2535
}

0 commit comments

Comments
 (0)