Skip to content

Commit 7228473

Browse files
committed
Fix error with matchmaking service
1 parent 58f9b3b commit 7228473

File tree

2 files changed

+47
-17
lines changed

2 files changed

+47
-17
lines changed

apps/matching-service/handlers/websocket.go

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ var (
2424
activeConnections = make(map[string]*websocket.Conn)
2525
// A map to hold user's match ctx cancel function
2626
matchContexts = make(map[string]context.CancelFunc)
27-
mu sync.Mutex // Mutex for thread-safe access to activeConnections
27+
// A map to hold user's match channels
28+
matchFoundChannels = make(map[string]chan models.MatchFound)
29+
mu sync.Mutex // Mutex for thread-safe access to activeConnections
2830
)
2931

3032
// handleConnections manages WebSocket connections and matching logic.
@@ -67,6 +69,9 @@ func HandleWebSocketConnections(w http.ResponseWriter, r *http.Request) {
6769
activeConnections[matchRequest.Username] = ws
6870
matchCtx, matchCancel := context.WithCancel(context.Background())
6971
matchContexts[matchRequest.Username] = matchCancel
72+
73+
matchFoundChan := make(chan models.MatchFound)
74+
matchFoundChannels[matchRequest.Username] = matchFoundChan
7075
mu.Unlock()
7176

7277
// Create a context for cancellation
@@ -84,11 +89,9 @@ func HandleWebSocketConnections(w http.ResponseWriter, r *http.Request) {
8489
}
8590
defer timeoutCancel()
8691

87-
matchFoundChan := make(chan models.MatchFound)
88-
8992
// Start goroutines for handling messages and performing matching.
9093
go processes.ReadMessages(ws, ctx, cancel)
91-
go processes.PerformMatching(matchRequest, ctx, matchFoundChan) // Perform matching
94+
go processes.PerformMatching(matchRequest, context.Background(), matchFoundChannels) // Perform matching
9295

9396
// Wait for a match, timeout, or cancellation.
9497
waitForResult(ws, ctx, timeoutCtx, matchCtx, matchFoundChan, matchRequest.Username)
@@ -127,29 +130,47 @@ func waitForResult(ws *websocket.Conn, ctx, timeoutCtx, matchCtx context.Context
127130
log.Println("Matching cancelled")
128131
// Cleanup Redis
129132
processes.CleanUpUser(processes.GetRedisClient(), username, context.Background())
133+
// Remove the match context and active
134+
if _, exists := matchContexts[username]; exists {
135+
delete(matchContexts, username)
136+
}
137+
if _, exists := activeConnections[username]; exists {
138+
delete(activeConnections, username)
139+
}
140+
if _, exists := matchFoundChannels[username]; exists {
141+
delete(matchFoundChannels, username)
142+
}
143+
130144
return
131145
case <-timeoutCtx.Done():
132146
log.Println("Connection timed out")
133147
// Cleanup Redis
134148
processes.CleanUpUser(processes.GetRedisClient(), username, context.Background())
149+
// Remove the match context and active
150+
if _, exists := matchContexts[username]; exists {
151+
delete(matchContexts, username)
152+
}
153+
if _, exists := activeConnections[username]; exists {
154+
delete(activeConnections, username)
155+
}
156+
if _, exists := matchFoundChannels[username]; exists {
157+
delete(matchFoundChannels, username)
158+
}
159+
135160
sendTimeoutResponse(ws)
136161
return
137162
case <-matchCtx.Done():
138-
log.Println("Match found for user HEREEE: " + username)
163+
log.Println("Match found for user: " + username)
139164
return
140165
case result, ok := <-matchFoundChan:
141166
if !ok {
142167
// Channel closed without a match, possibly due to context cancellation
143168
log.Println("Match channel closed without finding a match")
144169
return
145170
}
146-
log.Println("Match found for user: " + result.User)
171+
log.Println("Match found for user: " + username)
147172
// Notify the users about the match
148173
notifyMatch(result.User, result.MatchedUser, result)
149-
150-
// if err := ws.WriteJSON(result); err != nil {
151-
// log.Printf("write error: %v", err)
152-
// }
153174
return
154175
}
155176
}
@@ -185,13 +206,22 @@ func notifyMatch(username, matchedUsername string, result models.MatchFound) {
185206
}
186207

187208
// Remove the match context for both users and cancel for matched user
188-
if _, exists := matchContexts[username]; exists {
209+
if cancelFunc, exists := matchContexts[username]; exists {
210+
cancelFunc()
189211
delete(matchContexts, username)
190212
}
191213

192-
if cancelFunc, exists := matchContexts[matchedUsername]; exists {
214+
if cancelFunc2, exists := matchContexts[matchedUsername]; exists {
215+
cancelFunc2()
193216
delete(matchContexts, matchedUsername)
194-
defer cancelFunc() // TODO: CancelFunction here is not causing the matchCtx to be done
217+
}
218+
219+
// Remove the match channels
220+
if _, exists := matchFoundChannels[username]; exists {
221+
delete(matchFoundChannels, username)
222+
}
223+
if _, exists := matchFoundChannels[matchedUsername]; exists {
224+
delete(matchFoundChannels, matchedUsername)
195225
}
196226

197227
// Remove users from the activeConnections map

apps/matching-service/processes/match.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func getPortNumber(addr string) (int64, error) {
4545
return port, nil
4646
}
4747

48-
func PerformMatching(matchRequest models.MatchRequest, ctx context.Context, matchFoundChan chan models.MatchFound) {
48+
func PerformMatching(matchRequest models.MatchRequest, ctx context.Context, matchFoundChannels map[string]chan models.MatchFound) {
4949
// Acquire mutex
5050
mu.Lock()
5151
// Defer unlocking the mutex
@@ -73,15 +73,15 @@ func PerformMatching(matchRequest models.MatchRequest, ctx context.Context, matc
7373
// Peek at the user queue
7474
username, err := redisClient.LIndex(context.Background(), "matchmaking_queue", 0).Result()
7575
if err != nil {
76-
// log.Println("Error peeking user from queue:", err)
76+
log.Println("Error peeking user from queue:", err)
7777
time.Sleep(1 * time.Second)
7878
continue
7979
}
8080

8181
// log.Printf("Performing matching for user: %s", username)
8282
matchedUsername, matchedTopic, matchedDifficulty, err := FindMatchingUser(redisClient, username, ctx)
8383
if err != nil {
84-
// log.Println("Error finding matching user:", err)
84+
log.Println("Error finding matching user:", err)
8585
time.Sleep(1 * time.Second)
8686
continue
8787
}
@@ -111,7 +111,7 @@ func PerformMatching(matchRequest models.MatchRequest, ctx context.Context, matc
111111
}
112112

113113
// Signal that a match has been found
114-
matchFoundChan <- models.MatchFound{
114+
matchFoundChannels[username] <- models.MatchFound{
115115
Type: "match_found",
116116
MatchID: matchId,
117117
User: username,

0 commit comments

Comments
 (0)