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

Set up common room logic in preparation for collaboration service #182

Merged
merged 2 commits into from
Oct 31, 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
104 changes: 84 additions & 20 deletions frontend/components/matching/find-match.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ 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";
import { useRouter } from "next/navigation";

export default function FindMatch() {
const router = useRouter();
const [selectedDifficulty, setSelectedDifficulty] = useState<string>("");
const [selectedTopic, setSelectedTopic] = useState<string>("");
const [isSearching, setIsSearching] = useState<boolean>(false);
Expand Down Expand Up @@ -62,6 +64,8 @@ export default function FindMatch() {
return;
}

let isMatched = false;

const response = await joinMatchQueue(
auth.token,
auth?.user?.id,
Expand All @@ -70,12 +74,41 @@ export default function FindMatch() {
);
switch (response.status) {
case 201:
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
return;
const initialResponseData = await response.json();
let responseData;
if (typeof initialResponseData === "string") {
try {
responseData = JSON.parse(initialResponseData);
} catch (error) {
toast({
title: "Error",
description: "Unexpected error occured, please try again",
variant: "destructive",
});
return;
}
} else {
responseData = initialResponseData;
}

if (responseData.room_id) {
isMatched = true;
const roomId = responseData.room_id;
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
router.push(`/collaboration/${roomId}`);
} else {
toast({
title: "Error",
description: "Room ID not found",
variant: "destructive",
});
}
break;

case 202:
case 304:
setIsSearching(true);
Expand All @@ -87,24 +120,55 @@ export default function FindMatch() {
const queueTimeout = setTimeout(() => {
handleCancel(true);
}, waitTimeout);
ws.onmessage = () => {
setIsSearching(false);
clearTimeout(queueTimeout);
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
ws.onclose = () => null;

ws.onmessage = (event) => {
let responseData;

try {
responseData = JSON.parse(event.data);
if (typeof responseData === "string") {
responseData = JSON.parse(responseData);
}
} catch (error) {
toast({
title: "Error",
description: "Unexpected error occured, please try again",
variant: "destructive",
});
return;
}

const roomId = responseData.room_id;
if (roomId) {
isMatched = true;
setIsSearching(false);
clearTimeout(queueTimeout);
toast({
title: "Matched",
description: "Successfully matched",
variant: "success",
});
router.push(`/collaboration/${roomId}`);
} else {
toast({
title: "Error",
description: "Room ID not found",
variant: "destructive",
});
}
};

ws.onclose = () => {
setIsSearching(false);
clearTimeout(queueTimeout);
toast({
title: "Matching Stopped",
description: "Matching has been stopped",
variant: "destructive",
});
if (!isMatched) {
// Only show this toast if no match was made
toast({
title: "Matching Stopped",
description: "Matching has been stopped",
variant: "destructive",
});
}
};
return;
default:
Expand Down
15 changes: 14 additions & 1 deletion matching-service/app/logic/matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from typing import Union

from logger import logger
from models.match import MatchModel, MessageModel
from models.match import MatchModel
from utils.redis import acquire_lock, redis_client, release_lock
from utils.socketmanager import manager
import hashlib

async def find_match_else_enqueue(
user_id: str,
Expand Down Expand Up @@ -40,11 +41,15 @@ async def find_match_else_enqueue(
queue = await redis_client.lrange(queue_key, 0, -1)
logger.debug(_get_queue_state_message(topic, difficulty, queue, False))
await release_lock(redis_client, queue_key)

room_id = generate_room_id(matched_user, user_id)

response = MatchModel(
user1=matched_user,
user2=user_id,
topic=topic,
difficulty=difficulty,
room_id=room_id,
)
await manager.broadcast(matched_user, topic, difficulty, response.json())
await manager.disconnect_all(matched_user, topic, difficulty)
Expand Down Expand Up @@ -87,3 +92,11 @@ def _get_queue_state_message(topic, difficulty, queue, before: bool):
if before:
return "Before - " + postfix
return "After - " + postfix

# Generate room ID for matched users
def generate_room_id(user1_id: str, user2_id: str) -> str:
# Ensure consistency of room ID by ordering user IDs alphabetically
sorted_users = sorted([user1_id, user2_id])
concatenated_ids = f"{sorted_users[0]}-{sorted_users[1]}"
return hashlib.sha256(concatenated_ids.encode()).hexdigest()[:10]

1 change: 1 addition & 0 deletions matching-service/app/models/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class MatchModel(BaseModel):
user2: str
topic: str
difficulty: str
room_id: str

class MessageModel(BaseModel):
message: str