I have a webservice running with node.js and express which receives a series of game related messages. These messages are mainly intended to be logged away and the order isn't terribly important, except for one case:
When the game ends, there is a method relying on these logged messages. And this is were I am running in a race condition: Sometimes all messages are logged away just fine and sometimes some are logged after the processing has already taken place. The clients won't send messages afther sending the "ended" message, but node.js will mess up the order the events are processed.
Is there a way to process only one message at the time for each document, queueing the rest? Or if its not possible on document level, maybe at least for the whole function?
For further reference:
exports.updateGameById = function(req, res) {
// Make sure the Id is provided
var id = checkGetParameter('id', req, res);
if (!id) {
return;
}
// Extract the action and timestamp it
var action = req.body;
action.timestamp = new Date();
// Retrieve game from database
queries.findGame(res, { '_id': new ObjectID(id) }, function(res, game, collection) {
// Games are updateable under the following conditions
// 1) The game isn't fixed
if (!game.fixed) {
// Log request
collection.update({ _id : game._id}, { $push : { actionLog : action }});
// Do the correct update
switch(action.type) {
case 'started':
logic.handleUpdateStarted(game, collection, action, res);
break;
case 'ended':
// *** RACE CONDITION ***
// Requires that all previous messages have been logged
logic.handleUpdateEnded(game, collection, action, res);
break;
/* ... */
default:
// Entry is logged away, thats fine :)
res.send(200);
break;
}
} else {
// Inform user about problem
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.send(403, "Can't update: fixed = " + game.fixed + ", state = " + game.state);
}
});
};