Skip to content

Commit

Permalink
show queue status when changed
Browse files Browse the repository at this point in the history
  • Loading branch information
abstxn committed Oct 20, 2024
1 parent 23a0043 commit 1af9aeb
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 48 deletions.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ services:
- ALLOW_PLAINTEXT_LISTENER=yes
- KAFKA_CFG_NODE_ID=1
- KAFKA_AUTO_CREATE_TOPICS_ENABLE=true

kafka-setup:
image: node:22-alpine
volumes:
Expand Down
20 changes: 0 additions & 20 deletions frontend-service/components/matchmaking/Countdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,26 +57,6 @@ const Countdown: React.FC<CountdownProps> = ({
return () => clearTimeout(timerId);
}, [seconds]);

// TODO: update with matching-service backend
// const checkForMatch = async () => {
// setIsCheckingMatch(true); // Start checking for match
// try {
// const response = await fetch("");
// const data = await response.json();

// if (response.ok && data.matchFound) {
// onSuccess(); // If match found, trigger success callback
// } else {
// onFailure(); // If no match found, trigger failure callback
// }
// } catch (error) {
// console.error("Error checking for match:", error);
// onFailure();
// } finally {
// setIsCheckingMatch(false); // End checking for match
// }
// };

const handleCancel = () => {
setIsDialogOpen(true);
};
Expand Down
36 changes: 13 additions & 23 deletions frontend-service/src/pages/MatchingPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ const MatchingPage: React.FC = () => {
const [stage, setStage] = useState(STAGE.MATCHME);
const [selectedTopic, setSelectedTopic] = useState("");
const [selectedDifficulty, setSelectedDifficulty] = useState("");
const [loading, setLoading] = useState(false); // New loading state
const navigate = useNavigate();

// Helper function to handle fetch requests with error handling
// Helper function to handle authenticated fetch requests with error handling
const fetchWithAuth = async (url: string, options: RequestInit = {}) => {
const token = localStorage.getItem("token");
const headers = {
Expand All @@ -41,32 +40,24 @@ const MatchingPage: React.FC = () => {

// Trigger handlers according to match status in server
const checkMatchStatus = async () => {
// setLoading(true); // Indicate loading
try {
const result = await fetchWithAuth("http://localhost:3002/match-status");
const matchStatus = result.matchStatus;
console.log(matchStatus);
handleMatchStatusReceived(matchStatus);
if (matchStatus == "isNotMatching") {
setStage(STAGE.MATCHME);
} else if (matchStatus == "isMatching") {
setStage(STAGE.COUNTDOWN);
} else if (matchStatus == "isMatched") {
handleMatchFound();
} else if (matchStatus == "unsuccessful") {
handleMatchUnsuccess();
}
} catch {
console.error("Failed to check match status.");
} finally {
// setLoading(false); // Remove loading
}
};

const handleMatchStatusReceived = (matchStatus: string) => {
if (matchStatus == "isNotMatching") {
setStage(STAGE.MATCHME);
} else if (matchStatus == "isMatching") {
setStage(STAGE.COUNTDOWN);
} else if (matchStatus == "isMatched") {
handleMatchFound();
} else if (matchStatus == "unsuccessful") {
handleMatchUnsuccess();
}
};

// Simply send a find match request to be put in the queue
// Send a find match request to be put in the queue
const handleMatchMe = async () => {
setStage(STAGE.COUNTDOWN);
try {
Expand All @@ -87,8 +78,8 @@ const MatchingPage: React.FC = () => {
setStage(STAGE.UNSUCCESSFUL);
};

// Reset match request status in matching-service
const handleRetry = async () => {
// setStage(STAGE.COUNTDOWN);
try {
await fetchWithAuth("http://localhost:3002/reset-status", { method: "POST" });
} catch (error) {
Expand All @@ -97,6 +88,7 @@ const MatchingPage: React.FC = () => {
setStage(STAGE.MATCHME);
};

// Reset match request status in matching-service
const handleCancel = async () => {
try {
await fetchWithAuth("http://localhost:3002/cancel-matching", { method: "POST" });
Expand All @@ -122,8 +114,6 @@ const MatchingPage: React.FC = () => {

return (
<div>
{loading && <p>Loading...</p>} {/* Show loading message */}

{stage === STAGE.MATCHME && (
<MatchMe
onMatchMe={handleMatchMe}
Expand Down
10 changes: 6 additions & 4 deletions matching-service/dequeue-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ interface TimerData {

const timersMap = new Map<string, TimerData>();

const TIMEOUT_DURATION = 20000;

// Start Kafka Producer
(async () => {
await kafkaProducer.connect();
Expand All @@ -40,7 +42,7 @@ const timersMap = new Map<string, TimerData>();

console.log(`Received match-event for user: ${userID}, topic: ${topic}`);

// Start a timer for this match (e.g., 30 seconds)
// Start a timer for this match
const timerID = setTimeout(async () => {
console.log(`Timer up for user: ${userID}, topic: ${topic}. Producing dequeue-event.`);

Expand All @@ -52,7 +54,7 @@ const timersMap = new Map<string, TimerData>();

// Remove the timer reference
timersMap.delete(userID);
}, 20000);
}, TIMEOUT_DURATION);

// Store the timer reference and topic in the map
timersMap.set(userID, { userID, topic, timerID });
Expand All @@ -79,7 +81,7 @@ const timersMap = new Map<string, TimerData>();
if (timerData) {
clearTimeout(timerData.timerID); // Clear the timer
timersMap.delete(userID); // Remove from the map
console.log(`Cleared timer for user: ${userID}`);
console.log(`Cleared timer for user: ${userID}, reason: match found for user`);
}
}
});
Expand Down Expand Up @@ -111,7 +113,7 @@ const timersMap = new Map<string, TimerData>();
if (timerData) {
clearTimeout(timerData.timerID); // Clear the timer
timersMap.delete(userID); // Remove from the map
console.log(`Cleared timer for canceled user: ${userID}`);
console.log(`Cleared timer for canceled user: ${userID}, reason: user cancelled matching`);
}
}
},
Expand Down
21 changes: 21 additions & 0 deletions matching-service/matcher-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ interface MatchRequestData {
// Use a Map to store a queue per topic
const matchRequestsByTopic: Map<string, MatchRequestData[]> = new Map();

// Helper function to print the current state of topic queues
const printTopicQueues = () => {
console.log("Current match requests by topic:");
for (const [topic, queue] of matchRequestsByTopic.entries()) {
console.log(`Topic: ${topic}, Queue Length: ${queue.length}`);
queue.forEach(request => {
console.log(` - userID: ${request.userID}, difficulty: ${request.difficulty}`);
});
}
console.log("------------------------------------------------");
};

// Start the Kafka Consumer, listen to match events.
(async () => {
await kafkaConsumer.connect();
Expand All @@ -38,6 +50,9 @@ const matchRequestsByTopic: Map<string, MatchRequestData[]> = new Map();
matchRequestsByTopic.set(topic, []); // Create a queue for the topic if not exists
}
matchRequestsByTopic.get(topic)?.push(matchRequestData); // Push the request to the topic queue

// Print the current state of the topic queues
printTopicQueues();
},
});
})();
Expand All @@ -59,6 +74,9 @@ const matchRequestsByTopic: Map<string, MatchRequestData[]> = new Map();
matchRequestsByTopic.get(topic)?.filter(request => request.userID !== userID) || []
);
console.log(`User ${userID} removed from match queue for topic: ${topic}.`);

// Print the current state of the topic queues
printTopicQueues();
}
},
});
Expand Down Expand Up @@ -86,6 +104,9 @@ const runMatchingAlgorithm = async () => {
topic: 'match-found-events',
messages: [{ value: JSON.stringify(matchResult) }],
});

// Print the current state of the topic queues
printTopicQueues();
}
}
}
Expand Down

0 comments on commit 1af9aeb

Please sign in to comment.