Skip to content

Commit f8cd07f

Browse files
committed
Reuse socket
1 parent d95ffd5 commit f8cd07f

File tree

7 files changed

+117
-57
lines changed

7 files changed

+117
-57
lines changed

backend/matching-service/src/handlers/matchHandler.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { v4 as uuidv4 } from "uuid";
44
import {
55
MATCH_ACCEPTANCE_TIMEOUT,
66
MATCH_FOUND,
7+
MATCH_IN_PROGRESS,
78
MATCH_SUCCESSFUL,
89
MATCH_TIMEOUT,
910
MATCH_UNSUCCESSFUL,
@@ -30,7 +31,10 @@ export const createMatchItem = (socket: Socket, matchRequest: MatchRequest) => {
3031
acceptedMatch: false,
3132
};
3233

33-
appendToMatchQueue(matchQueueItem);
34+
const result = appendToMatchQueue(matchQueueItem);
35+
if (!result) {
36+
socket.emit(MATCH_IN_PROGRESS);
37+
}
3438
};
3539

3640
export const createMatch = (matchItems: MatchItem[]) => {
@@ -96,3 +100,9 @@ export const handleMatchDecline = (matchId: string) => {
96100
io.to(matchId).emit(MATCH_UNSUCCESSFUL);
97101
delete matches[matchId];
98102
};
103+
104+
export const isUserMatched = (userId: string): boolean => {
105+
return !!Object.values(matches).find(
106+
(match) => match.item1.user.id === userId || match.item2.user.id === userId
107+
);
108+
};

backend/matching-service/src/handlers/queueHandler.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { MatchItem } from "../types/matchTypes";
2-
import { createMatch } from "./matchHandler";
2+
import { createMatch, isUserMatched } from "./matchHandler";
33

44
/* Basic queue set-up for websocket testing (feel free to replace with the actual queueing mechanism) */
55

@@ -10,6 +10,9 @@ setInterval(() => {
1010
}, 5000);
1111

1212
const findMatch = () => {
13+
matchQueue.forEach((item) =>
14+
console.log(`${item.user.username} is ${item.socket.connected}`)
15+
);
1316
if (matchQueue.length < 2) {
1417
return;
1518
}
@@ -30,7 +33,17 @@ const findMatch = () => {
3033
};
3134

3235
export const appendToMatchQueue = (item: MatchItem) => {
33-
if (!matchQueue.find((queueItem) => queueItem.user.id === item.user.id)) {
34-
matchQueue.push(item);
36+
if (
37+
matchQueue.find(
38+
(queueItem) =>
39+
queueItem.user.id === item.user.id && queueItem.socket.connected
40+
) ||
41+
isUserMatched(item.user.id)
42+
) {
43+
return false;
3544
}
45+
46+
console.log(item.user.username);
47+
matchQueue.push(item);
48+
return true;
3649
};

backend/matching-service/src/utils/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
export const MATCH_REQUEST = "match_request";
33
export const MATCH_TIMEOUT = "match_timeout";
44
export const MATCH_FOUND = "match_found";
5+
export const MATCH_IN_PROGRESS = "match_in_progress";
56
export const MATCH_RECEIVED = "match_received";
67
export const MATCH_ACCEPTED = "match_accepted";
78
export const MATCH_DECLINED = "match_declined";
Lines changed: 68 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { io, Socket } from "socket.io-client";
21
import {
32
MATCH_ACCEPTED,
43
MATCH_DECLINED,
54
MATCH_FOUND,
5+
MATCH_IN_PROGRESS,
66
MATCH_RECEIVED,
77
MATCH_REQUEST,
88
MATCH_SUCCESSFUL,
@@ -11,88 +11,114 @@ import {
1111
SOCKET_CLIENT_DISCONNECT,
1212
SOCKET_DISCONNECT,
1313
SOCKET_RECONNECT_FAILED,
14+
SOCKET_RECONNECT_SUCCESS,
1415
} from "../utils/constants";
15-
import { User } from "../types/types";
16+
import { matchSocket } from "../utils/matchSocket";
1617

17-
const SOCKET_URL = "http://localhost:3002";
18+
interface MatchUser {
19+
id: string;
20+
username: string;
21+
profile?: string;
22+
}
1823

1924
export class MatchHandler {
20-
socket: Socket;
2125
matchId?: string;
26+
user: MatchUser;
27+
partner?: MatchUser;
2228

23-
constructor() {
24-
this.socket = io(SOCKET_URL, {
25-
reconnectionAttempts: 3,
26-
});
29+
constructor(user: MatchUser) {
30+
this.user = user;
2731
}
2832

29-
findMatch = (
30-
user: User,
31-
complexities: string[],
32-
categories: string[],
33-
languages: string[],
34-
timeout: number
33+
private setMatchDetails = (
34+
matchId: string,
35+
user1: MatchUser,
36+
user2: MatchUser
3537
) => {
36-
this.socket.emit(MATCH_REQUEST, {
37-
user: {
38-
id: user.id,
39-
username: user.username,
40-
profile: user.profilePictureUrl,
41-
},
42-
complexities: complexities,
43-
categories: categories,
44-
languages: languages,
45-
timeout: timeout,
38+
this.matchId = matchId;
39+
user1.id !== this.user.id ? (this.partner = user1) : (this.partner = user2);
40+
41+
console.log(`Match ID: ${this.matchId}`);
42+
console.log(`User: ${this.user!.username}`);
43+
console.log(`Partner: ${this.partner!.username}`);
44+
};
45+
46+
private openConnection = () => {
47+
matchSocket.removeAllListeners();
48+
this.initSocketListeners();
49+
matchSocket.connect();
50+
};
51+
52+
private closeConnection = () => {
53+
matchSocket.removeAllListeners();
54+
matchSocket.disconnect();
55+
};
56+
57+
private initSocketListeners = () => {
58+
matchSocket.on(MATCH_FOUND, ({ matchId, user1, user2 }) => {
59+
this.setMatchDetails(matchId, user1, user2);
60+
matchSocket.emit(MATCH_RECEIVED, this.matchId);
4661
});
4762

48-
this.socket.on(MATCH_FOUND, ({ matchId, user1, user2 }) => {
49-
console.log(`Match ID: ${matchId}`);
50-
console.log(`User 1: ${user1.username}`);
51-
console.log(`User 2: ${user2.username}`);
52-
this.matchId = matchId;
53-
this.socket.emit(MATCH_RECEIVED, this.matchId);
63+
matchSocket.on(MATCH_IN_PROGRESS, () => {
64+
console.log("Matching in progress... / Match already found!");
5465
});
5566

56-
this.socket.on(MATCH_SUCCESSFUL, () => {
67+
matchSocket.on(MATCH_SUCCESSFUL, () => {
5768
console.log("Match successful");
5869
this.closeConnection();
5970
});
6071

61-
this.socket.on(MATCH_UNSUCCESSFUL, () => {
72+
matchSocket.on(MATCH_UNSUCCESSFUL, () => {
6273
console.log("Match unsuccessful");
6374
this.closeConnection();
6475
});
6576

66-
this.socket.on(MATCH_TIMEOUT, () => {
77+
matchSocket.on(MATCH_TIMEOUT, () => {
6778
console.log("Match timeout");
6879
this.closeConnection();
6980
});
7081

71-
this.socket.on(SOCKET_DISCONNECT, (reason) => {
82+
matchSocket.on(SOCKET_DISCONNECT, (reason) => {
7283
if (reason !== SOCKET_CLIENT_DISCONNECT) {
7384
console.log("Oops, something went wrong! Reconnecting...");
7485
}
7586
});
7687

77-
this.socket.io.on(SOCKET_RECONNECT_FAILED, () => {
88+
matchSocket.io.on(SOCKET_RECONNECT_SUCCESS, () => {
89+
console.log("Reconnected!");
90+
});
91+
92+
matchSocket.io.on(SOCKET_RECONNECT_FAILED, () => {
7893
console.log("Oops, something went wrong! Please try again later.");
7994
});
8095
};
8196

97+
findMatch = (
98+
complexities: string[],
99+
categories: string[],
100+
languages: string[],
101+
timeout: number
102+
) => {
103+
this.openConnection();
104+
matchSocket.emit(MATCH_REQUEST, {
105+
user: this.user,
106+
complexities: complexities,
107+
categories: categories,
108+
languages: languages,
109+
timeout: timeout,
110+
});
111+
};
112+
82113
acceptMatch = () => {
83-
this.socket.emit(MATCH_ACCEPTED, this.matchId);
114+
matchSocket.emit(MATCH_ACCEPTED, this.matchId);
84115
};
85116

86117
declineMatch = () => {
87-
this.socket.emit(MATCH_DECLINED, this.matchId);
118+
matchSocket.emit(MATCH_DECLINED, this.matchId);
88119
};
89120

90121
stopMatch = () => {
91122
this.closeConnection();
92123
};
93-
94-
closeConnection = () => {
95-
this.socket.removeAllListeners();
96-
this.socket.disconnect();
97-
};
98124
}

frontend/src/pages/Home/index.tsx

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,20 @@ import { User } from "../../types/types";
2929
import { MatchHandler } from "../../handlers/matchHandler";
3030

3131
const Home: React.FC = () => {
32-
const user = useOutletContext<User>();
3332
const [complexities, setComplexities] = useState<string[]>([]);
3433
const [categories, setCategories] = useState<string[]>([]);
3534
const [languages, setLanguages] = useState<string[]>([]);
3635
const [timeout, setTimeout] = useState<number>(30);
3736

3837
const [state, dispatch] = useReducer(reducer, initialState);
3938

39+
const user = useOutletContext<User>();
40+
const matchHandler = new MatchHandler({
41+
id: user.id,
42+
username: user.username,
43+
profile: user.profilePictureUrl,
44+
});
45+
4046
useEffect(() => {
4147
getQuestionCategories(dispatch);
4248
}, []);
@@ -265,19 +271,14 @@ const Home: React.FC = () => {
265271
// categories.length == 0 ||
266272
// languages.length == 0
267273
// }
268-
onClick={() => {
269-
const matchHandler = new MatchHandler();
270-
matchHandler.findMatch(
271-
user,
272-
complexities,
273-
categories,
274-
languages,
275-
timeout
276-
);
277-
}}
274+
onClick={() =>
275+
matchHandler.findMatch(complexities, categories, languages, timeout)
276+
}
278277
>
279278
Find my match!
280279
</Button>
280+
<Button onClick={() => matchHandler.acceptMatch()}>Accept</Button>
281+
<Button onClick={() => matchHandler.declineMatch()}>Decline</Button>
281282
</Card>
282283
</AppMargin>
283284
);

frontend/src/utils/constants.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,14 @@ export const COLLABORATIVE_EDITOR_PATH = "/collaborative_editor.png";
8686
// Socket Events
8787
export const SOCKET_DISCONNECT = "disconnect";
8888
export const SOCKET_CLIENT_DISCONNECT = "io client disconnect";
89+
export const SOCKET_RECONNECT_SUCCESS = "reconnect";
8990
export const SOCKET_RECONNECT_FAILED = "reconnect_failed";
9091

9192
// Match Events
9293
export const MATCH_REQUEST = "match_request";
9394
export const MATCH_TIMEOUT = "match_timeout";
9495
export const MATCH_FOUND = "match_found";
96+
export const MATCH_IN_PROGRESS = "match_in_progress";
9597
export const MATCH_RECEIVED = "match_received";
9698
export const MATCH_ACCEPTED = "match_accepted";
9799
export const MATCH_DECLINED = "match_declined";

frontend/src/utils/matchSocket.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { io } from "socket.io-client";
2+
3+
const MATCH_SOCKET_URL = "http://localhost:3002";
4+
5+
export const matchSocket = io(MATCH_SOCKET_URL, {
6+
reconnectionAttempts: 3,
7+
});

0 commit comments

Comments
 (0)