Skip to content

Commit 79af2b6

Browse files
committed
resolve some logic error within the matching algorithm
1 parent 0edbb20 commit 79af2b6

File tree

4 files changed

+85
-22
lines changed

4 files changed

+85
-22
lines changed

peer-prep/src/matching-service/controllers/matchingController.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,30 @@ const matchingService = require('../services/matchingService');
22

33
async function findMatch(req, res, next) {
44
try {
5-
const { id, language, proficiency, difficulty, topic } = req.body;
5+
const {language, proficiency, difficulty, topic } = req.body;
6+
const id = req.params.userId; // Extract user id from request params
67
console.log(req.body);
78
console.log(`${id}, ${language}, ${proficiency}, ${difficulty}, ${topic}`);
89

9-
const matchResult = await matchingService.findMatch({ id, language, proficiency, difficulty, topic });
10-
11-
res.status(200).json(matchResult);
10+
const matchResult = await matchingService.findMatch({id, language, proficiency, difficulty, topic});
11+
12+
switch(matchResult.status) {
13+
case 'success':
14+
res.status(200).json(matchResult);
15+
break;
16+
case 'failed':
17+
res.status(400).json(matchResult);
18+
break;
19+
case 'cancel':
20+
res.status(200).json(matchResult);
21+
break;
22+
default:
23+
res.status(500).json({message:'Failed to find a match. Please try again!'});
24+
}
1225

1326
} catch (error) {
14-
next(error);
27+
console.error(error);
28+
res.status(500).json({message:'Failed to find a match. Please try again!'})
1529
}
1630
}
1731

peer-prep/src/matching-service/database/matchedPairDb.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,12 @@ async function endSession(sessionId) {
3838
try {
3939
const filter = { sessionId: sessionId };
4040
const update = { $set: { isEnded: true } };
41-
await MatchedPair.updateOne(filter, update);
41+
const result = await MatchedPair.updateOne(filter, update);
42+
43+
if (result.nModified == 0) {
44+
console.warn(`No session was updated for session ${sessionId}`);
45+
}
46+
4247
console.log(`Successfully update session state for session ${sessionId}`);
4348

4449
} catch (error) {

peer-prep/src/matching-service/server.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
const express = require('express');
22
const app = express();
33
const mongoose = require('mongoose');
4-
const bodyParser = require('body-parser');
5-
const routes = require('./routes/routes');
64
const config = require('./config/config');
5+
const routes = require('./routes/routes');
6+
77

88
mongoose.connect(config.mongodbUri, {
99
useNewUrlParser: true,
1010
useUnifiedTopology: true,
1111
});
1212

13-
app.use(bodyParser.urlencoded({ extended: true }));
13+
app.use(express.urlencoded({ extended: true })); // use express's built-in middleware
14+
app.use(express.json()); // This is the middleware to handle JSON payloads
1415

1516
app.use('/', routes);
1617

peer-prep/src/matching-service/services/matchingService.js

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ const amqp = require('amqplib');
33
const { v4: uuidv4 } = require('uuid');
44
const { addMatchedPair, getCurrentMatchedPair } = require('../database/matchedPairDb');
55
const MatchedPair = require('../models/matchedPairModel');
6+
const matchedPairDb = require('../database/matchedPairDb');
7+
68

79
const refreshDuration = 3000; // 3 seconds
810
const waitingDuration = 3000;
@@ -14,6 +16,7 @@ let availabilityCache = new Set();
1416

1517
// Find matching pair based on the selected criteria : language, proficiency, difficulty, topic
1618
async function findMatch(request) {
19+
1720
return new Promise(async(resolve) => {
1821
let connection;
1922
let channel;
@@ -25,10 +28,10 @@ async function findMatch(request) {
2528

2629
console.log('Successfully connected to RabbitMQ');
2730

28-
const criteria = `${request.language}
29-
.${request.proficiency}
30-
.${request.difficulty}
31-
.${request.topic}`;
31+
const criteria = `${request.language || 'None'}
32+
.${request.proficiency || 'None'}
33+
.${request.difficulty || 'None'}
34+
.${request.topic || 'None'}`;
3235

3336
checkCancel = setInterval(async() => {
3437
if (isCancelled.has(parseInt(request.id))) {
@@ -94,6 +97,8 @@ async function findMatch(request) {
9497
}
9598
} catch (error) {
9699
console.log('Error finding match: ', error);
100+
throw error;
101+
97102
} finally {
98103
availabilityCache.delete(request.id);
99104

@@ -107,6 +112,18 @@ async function findMatch(request) {
107112
});
108113
}
109114

115+
function criteriaMatches(requestCriteria, currentCriteria) {
116+
const fields = ['language', 'proficiency', 'difficulty', 'topic'];
117+
for (let field of fields) {
118+
if (requestCriteria[field] !== "None" &&
119+
currentCriteria[field] !== "None" &&
120+
requestCriteria[field] !== currentCriteria[field]) {
121+
return false;
122+
}
123+
}
124+
return true;
125+
}
126+
110127
// Add new request into the queue, 'topic' exchange type is used to route the message
111128
async function addRequestIntoQueue(channel, criteria, request) {
112129
try {
@@ -167,29 +184,26 @@ async function listenToMatchingQueue(channel, criteria, request) {
167184
channel.consume(queueName, async(message) => {
168185
const currentRequest = JSON.parse(message.content.toString());
169186
const checkActivePair = await getCurrentMatchedPair(currentRequest.request.id);
170-
171-
if (checkActivePair &&
172-
(String(checkActivePair.id1) === String(request.id) ||
173-
String(checkActivePair.id2) === String(request.id))) {
174-
187+
188+
// Check if there is an active pair and if the criteria still match
189+
if (checkActivePair && criteriaMatches(request, currentRequest.request)) {
190+
const collaboratorId = String(checkActivePair.id1) === String(request.id) ? checkActivePair.id2 : checkActivePair.id1;
175191
resolve({
176192
stored: true,
177193
isMatched: true,
178194
id: request.id,
179-
collaboratorId: currentRequest.request.id
195+
collaboratorId: collaboratorId
180196
});
181197

182198
} else if (checkActivePair ||
183199
isCancelled.has(parseInt(currentRequest.request.id))) {
184200

185201
console.log(`Remove match ${currentRequest.request.id}`);
186-
187202
availabilityCache.delete(currentRequest.request.id);
188203
channel.ack(message);
189204

190205
} else if (!matched &&
191-
currentRequest.request.id !== request.id &&
192-
currentRequest.criteria === criteria &&
206+
currentRequest.request.id !== request.id && criteriaMatches(request, currentRequest.request) &&
193207
availabilityCache.has(currentRequest.request.id)) {
194208

195209
console.log(`Found a match for ${request.id}`);
@@ -219,13 +233,42 @@ async function listenToMatchingQueue(channel, criteria, request) {
219233

220234
// Cancel matching service
221235

236+
//async function cancelMatch(requestId) {
237+
// isCancelled.add(parseInt(requestId));
238+
// availabilityCache.delete(requestId);
239+
//
240+
// console.log(`Matching service is cancelled for ${requestId}`);
241+
242+
// return true;
243+
//}
244+
222245
async function cancelMatch(requestId) {
246+
// Adding the requestId to the cancelled set
223247
isCancelled.add(parseInt(requestId));
248+
249+
// Removing the requestId from the availability cache
224250
availabilityCache.delete(requestId);
225251

226252
console.log(`Matching service is cancelled for ${requestId}`);
227253

254+
// Check if there's an ongoing session for the given requestId
255+
const currentMatchedPair = await matchedPairDb.getCurrentMatchedPair(requestId);
256+
if (currentMatchedPair) {
257+
console.log(`Found ongoing session for ${requestId}. Terminating...`);
258+
259+
try {
260+
await matchedPairDb.endSession(currentMatchedPair.sessionId);
261+
console.log(`Successfully terminated session for ${requestId}`);
262+
} catch (error) {
263+
console.error(`Error while terminating session for ${requestId}:`, error);
264+
throw error;
265+
}
266+
} else {
267+
console.log(`No ongoing session found for ${requestId}`);
268+
}
269+
228270
return true;
229271
}
230272

273+
231274
module.exports = { findMatch, cancelMatch };

0 commit comments

Comments
 (0)