I'm trying to create a simple node app utilizing socket.io rooms where users can play a 1v1 game against other users. The system I have in place at the moment is when a user clicks the play button they are put into a queue. Once the queue reaches 2 players the first 2 players in the queue are matched and redirected to a game.
function socketHandler(socket){
const db=dbGetter.getDb()
socket.on('joinQueue',()=>{
queue.push(socket)
if(queue.length>=2){
playerOneSocket=queue.shift()
playerTwoSocket=queue.shift()
CreateGameBySockets(playerOneSocket,playerTwoSocket,db,(game)=>{
//redirects players to game not yet implemented
})
}
})
}
This code works as intended as far as I can tell (Once the queue reaches 2 createGameBySockets is triggered and queue is cleared). However, I have concerns about how it will function with many users joining the queue in quick succession. For instance, say ten users attempt to join the queue simultaneously. I worry that the queue.shift() lines won't be triggered fast enough and multiple games will be created between the first 2 players in the queue before they are removed from the queue
I'm not sure of a way that I can test for such a scenario. Looking for advice on how to prevent this scenario from occurring and how I could test to see how this scenario would be handled.