Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frontend-Backend matching integration #178

Merged
merged 10 commits into from
Oct 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 147 additions & 9 deletions frontend/components/matching/find-match.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@ import { MatchForm } from "@/components/matching/matching-form";
import { SearchProgress } from "@/components/matching/search-progress";
import { SelectionSummary } from "@/components/matching/selection-summary";
import { useToast } from "@/components/hooks/use-toast";
import { useAuth } from "@/app/auth/auth-context";
import { joinMatchQueue } from "@/lib/join-match-queue";
import { leaveMatchQueue } from "@/lib/leave-match-queue";
import { subscribeMatch } from "@/lib/subscribe-match";

export default function FindMatch() {
const [selectedDifficulty, setSelectedDifficulty] = useState<string>("");
const [selectedTopic, setSelectedTopic] = useState<string>("");
const [isSearching, setIsSearching] = useState<boolean>(false);
const [waitTime, setWaitTime] = useState<number>(0);
const { toast } = useToast();
const auth = useAuth();

const waitTimeout = 60000;

useEffect(() => {
let interval: NodeJS.Timeout | undefined;
Expand All @@ -21,24 +28,155 @@ export default function FindMatch() {
} else {
setWaitTime(0);
}
return () => clearInterval(interval);

return () => {
clearInterval(interval);
};
}, [isSearching]);

const handleSearch = () => {
if (selectedDifficulty && selectedTopic) {
setIsSearching(true);
} else {
const handleSearch = async () => {
if (!selectedDifficulty || !selectedTopic) {
toast({
title: "Invalid Selection",
description: "Please select both a difficulty level and a topic",
variant: "destructive",
});
return;
}

if (!auth || !auth.token) {
toast({
title: "Access denied",
description: "No authentication token found",
variant: "destructive",
});
return;
}

if (!auth.user) {
toast({
title: "Access denied",
description: "Not logged in",
variant: "destructive",
});
return;
}

const response = await joinMatchQueue(
auth.token,
auth?.user?.id,
selectedTopic,
selectedDifficulty
);
switch (response.status) {
case 201:
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
return;
case 202:
case 304:
setIsSearching(true);
const ws = await subscribeMatch(
auth?.user.id,
selectedTopic,
selectedDifficulty
);
const queueTimeout = setTimeout(() => {
handleCancel(true);
}, waitTimeout);
ws.onmessage = () => {
setIsSearching(false);
clearTimeout(queueTimeout);
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
ws.onclose = () => null;
};
ws.onclose = () => {
setIsSearching(false);
clearTimeout(queueTimeout);
toast({
title: "Matching Stopped",
description: "Matching has been stopped",
variant: "destructive",
});
};
return;
default:
toast({
title: "Unknown Error",
description: "An unexpected error has occured",
variant: "destructive",
});
return;
}
};

const handleCancel = () => {
setIsSearching(false);
setWaitTime(0);
const handleCancel = async (timedOut: boolean) => {
if (!selectedDifficulty || !selectedTopic) {
toast({
title: "Invalid Selection",
description: "Please select both a difficulty level and a topic",
variant: "destructive",
});
return;
}

if (!auth || !auth.token) {
toast({
title: "Access denied",
description: "No authentication token found",
variant: "destructive",
});
return;
}

if (!auth.user) {
toast({
title: "Access denied",
description: "Not logged in",
variant: "destructive",
});
return;
}

const response = await leaveMatchQueue(
auth.token,
auth.user?.id,
selectedTopic,
selectedDifficulty
);
switch (response.status) {
case 200:
setIsSearching(false);
setWaitTime(0);
if (timedOut) {
toast({
title: "Timed Out",
description: "Matching has been stopped",
variant: "destructive",
});
} else {
toast({
title: "Matching Stopped",
description: "Matching has been stopped",
variant: "destructive",
});
}
return;
default:
toast({
title: "Unknown Error",
description: "An unexpected error has occured",
variant: "destructive",
});
return;
}
};

return (
Expand All @@ -50,7 +188,7 @@ export default function FindMatch() {
setSelectedTopic={setSelectedTopic}
handleSearch={handleSearch}
isSearching={isSearching}
handleCancel={handleCancel}
handleCancel={() => handleCancel(false)}
/>

{isSearching && <SearchProgress waitTime={waitTime} />}
Expand Down
7 changes: 7 additions & 0 deletions frontend/lib/api-uri.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
const constructUri = (baseUri: string, port: string | undefined) =>
`http://${process.env.NEXT_PUBLIC_BASE_URI || baseUri}:${port}`;

const constructWebSockUri = (baseUri: string, port: string | undefined) =>
`ws://${process.env.NEXT_PUBLIC_BASE_URI || baseUri}:${port}`;

export const userServiceUri: (baseUri: string) => string = (baseUri) =>
constructUri(baseUri, process.env.NEXT_PUBLIC_USER_SVC_PORT);
export const questionServiceUri: (baseUri: string) => string = (baseUri) =>
constructUri(baseUri, process.env.NEXT_PUBLIC_QUESTION_SVC_PORT);
export const matchingServiceUri: (baseUri: string) => string = (baseUri) =>
constructUri(baseUri, process.env.NEXT_PUBLIC_MATCHING_SVC_PORT);

export const matchingServiceWebSockUri: (baseUri: string) => string = (
baseUri
) => constructWebSockUri(baseUri, process.env.NEXT_PUBLIC_MATCHING_SVC_PORT);
24 changes: 24 additions & 0 deletions frontend/lib/join-match-queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { matchingServiceUri } from "@/lib/api-uri";

export const joinMatchQueue = async (
jwtToken: string,
userId: string,
category: string,
complexity: string
) => {
const params = new URLSearchParams({
topic: category,
difficulty: complexity,
}).toString();
const response = await fetch(
`${matchingServiceUri(window.location.hostname)}/match/queue/${userId}?${params}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
}
);
return response;
};
24 changes: 24 additions & 0 deletions frontend/lib/leave-match-queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { matchingServiceUri } from "@/lib/api-uri";

export const leaveMatchQueue = async (
jwtToken: string,
userId: string,
category: string,
complexity: string
) => {
const params = new URLSearchParams({
topic: category,
difficulty: complexity,
}).toString();
const response = await fetch(
`${matchingServiceUri(window.location.hostname)}/match/queue/${userId}?${params}`,
{
method: "DELETE",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
}
);
return response;
};
15 changes: 15 additions & 0 deletions frontend/lib/subscribe-match.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { matchingServiceWebSockUri } from "@/lib/api-uri";

export const subscribeMatch = async (
userId: string,
category: string,
complexity: string
) => {
const params = new URLSearchParams({
topic: category,
difficulty: complexity,
});
return new WebSocket(
`${matchingServiceWebSockUri(window.location.hostname)}/match/subscribe/${userId}?${params}`
);
};
71 changes: 71 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions matching-service/app/exceptions/socket_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class NoExistingConnectionException(Exception):
pass
9 changes: 9 additions & 0 deletions matching-service/app/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import logging
import sys

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler(sys.stdout)
log_formatter = logging.Formatter("%(levelname)s: %(message)s")
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)
Loading