From ee898778bdd6ca2db3d76dbfd3308b5a13335a1d Mon Sep 17 00:00:00 2001 From: Rounak Agarwal Date: Tue, 22 Sep 2026 22:19:04 +0530 Subject: [PATCH] fix: snapshot room.Clients under lock to prevent data race in join handler --- backend/websocket/websocket.go | 43 +++++++++++++++++----------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/backend/websocket/websocket.go b/backend/websocket/websocket.go index 79470aba..b0cc6f8d 100644 --- a/backend/websocket/websocket.go +++ b/backend/websocket/websocket.go @@ -345,27 +345,28 @@ func WebsocketHandler(c *gin.Context) { client.SafeWriteJSON(participantsMsg) // Send existing participants' detailed info to the new client - for connRef, existing := range room.Clients { - payload := map[string]interface{}{ - "id": existing.UserID, - "username": existing.Username, - "displayName": existing.Username, - "email": existing.Email, - "avatarUrl": existing.AvatarURL, - "elo": existing.Elo, - } - detailMessage := map[string]interface{}{ - "type": "userDetails", - "userDetails": payload, - } - - if connRef == conn { - // Already sent this client's participant data; ensure they have their own detail payload too - client.SafeWriteJSON(detailMessage) - } else { - // Send existing participant info to the new client - client.SafeWriteJSON(detailMessage) - } + // Snapshot existing participants' detail payloads under the lock, + // then write outside the lock to avoid a data race on room.Clients + // and to avoid holding the mutex during network I/O. + room.Mutex.Lock() + detailMessages := make([]map[string]interface{}, 0, len(room.Clients)) + for _, existing := range room.Clients { + detailMessages = append(detailMessages, map[string]interface{}{ + "type": "userDetails", + "userDetails": map[string]interface{}{ + "id": existing.UserID, + "username": existing.Username, + "displayName": existing.Username, + "email": existing.Email, + "avatarUrl": existing.AvatarURL, + "elo": existing.Elo, + }, + }) + } + room.Mutex.Unlock() + + for _, detailMessage := range detailMessages { + client.SafeWriteJSON(detailMessage) } // Prepare detailed payload for the new client to broadcast to others