Skip to content

Commit

Permalink
Proxy collaboration and match service through gateway (#165)
Browse files Browse the repository at this point in the history
  • Loading branch information
yhtMinceraft1010X authored Oct 24, 2023
1 parent 7aa23c6 commit c9ab65b
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 82 deletions.
37 changes: 23 additions & 14 deletions frontend/providers/MatchmakingProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import React, {
import { io, Socket } from "socket.io-client";
import { Match } from "@prisma/client";
import { AuthContext } from "@/contexts/AuthContext";
import {matchSocketAddress} from "@/gateway-address/gateway-address";

const SERVER_URL = "http://localhost:5002";
const SERVER_URL = matchSocketAddress;

interface MatchmakingContextValue {
socket: Socket | null;
Expand Down Expand Up @@ -48,19 +49,27 @@ export const MatchmakingProvider: React.FC<MatchmakingProviderProps> = ({
// Initialize socket connection
useEffect(() => {
if (currentUser) {
const newSocket = io(SERVER_URL, {
autoConnect: false,
// query: { username: currentUser?.email },
query: { username: generateRandomNumber() },
});
setSocket(newSocket);
newSocket.connect();

console.log("Socket connected");

return () => {
newSocket.close();
};
currentUser.getIdToken(true).then(
(token) => {
const newSocket = io(SERVER_URL, {
autoConnect: false,
// query: { username: currentUser?.email },
query: { username: generateRandomNumber() },
extraHeaders: {
"User-Id-Token": token
},
path: "/match/socket.io"
});
setSocket(newSocket);
newSocket.connect();

console.log("Socket connected");

return () => {
newSocket.close();
};
}
)
}
}, [currentUser]);

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/firebase-client/useDeleteOwnAccount.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { auth } from "./firebase_config";
import { AuthContext } from "../contexts/AuthContext";
import { useContext } from "react";
import { userApiPathAddress } from "@/firebase-client/gateway-address";
import { userApiPathAddress } from "@/gateway-address/gateway-address";

export const useDeleteOwnAccount = () => {
const { dispatch } = useContext(AuthContext);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/firebase-client/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GithubAuthProvider, signInWithPopup, User } from "firebase/auth";
import { auth } from "./firebase_config";
import { AuthContext } from "../contexts/AuthContext";
import { useContext, useState } from "react";
import {userApiPathAddress} from "@/firebase-client/gateway-address";
import {userApiPathAddress} from "@/gateway-address/gateway-address";

export const useLogin = () => {
const [error, setError] = useState<string | null>(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ const gatewayAddress = process.env.NEXT_PUBLIC_GATEWAY_ADDRESS || "http://localh

export const userApiPathAddress = gatewayAddress + "api/user-service/";
export const questionApiPathAddress = gatewayAddress + "api/question-service/";

export const collaborationSocketAddress = gatewayAddress + "collaboration/socket.io";
export const matchSocketAddress = gatewayAddress + "match/socket.io";
142 changes: 78 additions & 64 deletions frontend/src/hooks/useCollaboration.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState, useRef, use } from "react";
import {useEffect, useState, useRef, use, useContext} from "react";
import { io, Socket } from "socket.io-client";
import { debounce } from "lodash";
import {
Expand All @@ -7,6 +7,8 @@ import {
} from "../../../utils/shared-ot";
import { TextOp } from "ot-text-unicode";
import { Room, connect } from "twilio-video";
import {collaborationSocketAddress} from "@/gateway-address/gateway-address";
import {AuthContext} from "@/contexts/AuthContext";

type UseCollaborationProps = {
roomId: string;
Expand Down Expand Up @@ -39,72 +41,84 @@ const useCollaboration = ({ roomId, userId, disableVideo }: UseCollaborationProp
const awaitingSync = useRef<boolean>(false); // synced with server
const twilioTokenRef = useRef<string>("");
const questionId = "1";
const { user: currentUser, authIsReady } = useContext(AuthContext);

useEffect(() => {
const socketConnection = io("http://localhost:5003/");
setSocket(socketConnection);

socketConnection.emit(SocketEvents.ROOM_JOIN, roomId, userId);
socketConnection.emit(SocketEvents.QUESTION_SET, questionId);

socketConnection.on("twilio-token", (token: string) => {
twilioTokenRef.current = token;
if (disableVideo) return;
connect(token, {
name: roomId, audio: true,
video: { width: 640, height: 480, frameRate: 24 }
}).then((room) => {
console.log("Connected to Room");
setRoom(room);
}).catch(err => {
console.log(err, token, userId, roomId);
});
});

socketConnection.on(
SocketEvents.ROOM_UPDATE,
({
version,
text,
cursor,
}: {
version: number;
text: string;
cursor: number | undefined | null;
}) => {
prevCursorRef.current = cursorRef.current;
console.log("prevCursor: " + prevCursorRef.current);

console.log("cursor: " + cursor);

console.log("Update vers to " + version);
vers = version;

if (awaitingAck.current) return;

textRef.current = text;
prevTextRef.current = text;
setText(text);
if (cursor && cursor > -1) {
console.log("Update cursor to " + cursor);
cursorRef.current = cursor;
setCursor(cursor);
} else {
cursorRef.current = prevCursorRef.current;
cursor = prevCursorRef.current;
console.log("Update cursor to " + prevCursorRef.current);
setCursor(prevCursorRef.current);
if (currentUser) {
currentUser.getIdToken(true).then(
(token) => {
const socketConnection = io(collaborationSocketAddress, {
extraHeaders: {
"User-Id-Token": token
},
path: "/collaboration/socket.io"
});
setSocket(socketConnection);

socketConnection.emit(SocketEvents.ROOM_JOIN, roomId, userId);
socketConnection.emit(SocketEvents.QUESTION_SET, questionId);

socketConnection.on("twilio-token", (token: string) => {
twilioTokenRef.current = token;
if (disableVideo) return;
connect(token, {
name: roomId, audio: true,
video: {width: 640, height: 480, frameRate: 24}
}).then((room) => {
console.log("Connected to Room");
setRoom(room);
}).catch(err => {
console.log(err, token, userId, roomId);
});
});

socketConnection.on(
SocketEvents.ROOM_UPDATE,
({
version,
text,
cursor,
}: {
version: number;
text: string;
cursor: number | undefined | null;
}) => {
prevCursorRef.current = cursorRef.current;
console.log("prevCursor: " + prevCursorRef.current);

console.log("cursor: " + cursor);

console.log("Update vers to " + version);
vers = version;

if (awaitingAck.current) return;

textRef.current = text;
prevTextRef.current = text;
setText(text);
if (cursor && cursor > -1) {
console.log("Update cursor to " + cursor);
cursorRef.current = cursor;
setCursor(cursor);
} else {
cursorRef.current = prevCursorRef.current;
cursor = prevCursorRef.current;
console.log("Update cursor to " + prevCursorRef.current);
setCursor(prevCursorRef.current);
}
awaitingSync.current = false;
}
);

return () => {
socketConnection.disconnect();
if (room) {
room.disconnect();
}
}
}
awaitingSync.current = false;
}
);

return () => {
socketConnection.disconnect();
if (room) {
room.disconnect();
}
};
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomId, userId]);

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/api/questionHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { questionApiPathAddress } from "@/firebase-client/gateway-address";
import { questionApiPathAddress } from "@/gateway-address/gateway-address";
import { Difficulty, Question } from "../../types/QuestionTypes";
import { formSchema } from "../questions/_form";
import { z } from "zod";
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/api/userHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { userApiPathAddress } from "@/firebase-client/gateway-address";
import { userApiPathAddress } from "@/gateway-address/gateway-address";
import { EditableUser } from "@/types/UserTypes";

export const updateUserByUid = async (user: EditableUser, currentUser: any) => {
Expand Down
24 changes: 24 additions & 0 deletions services/gateway/src/proxied_routes/proxied_routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,28 @@ export const proxied_routes: ProxiedRoute[] = [
changeOrigin: true,
},
},
{
url: "/collaboration/socket.io",
admin_required_methods: [],
user_match_required_methods: [], // No need for exact user match here
proxy: {
target: collaborationServiceAddress,
changeOrigin: true,
pathRewrite: {
"^/collaboration/socket.io": "socket.io",
},
},
},
{
url: "/match/socket.io",
admin_required_methods: [],
user_match_required_methods: [], // No need for exact user match here
proxy: {
target: matchingServiceAddress,
changeOrigin: true,
pathRewrite: {
"^/match/socket.io": "socket.io",
},
},
},
];

0 comments on commit c9ab65b

Please sign in to comment.