From bb3afc2bf687b2279633dad66792c908da04da6d Mon Sep 17 00:00:00 2001 From: Lamp Date: Fri, 14 Dec 2018 05:55:06 +0000 Subject: [PATCH] Fix race condition in name collector to close #14 by using a buffer and processing actions serially --- src/mppbridger/namecollector.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/mppbridger/namecollector.js b/src/mppbridger/namecollector.js index 68632bd..e51c71b 100644 --- a/src/mppbridger/namecollector.js +++ b/src/mppbridger/namecollector.js @@ -1,9 +1,15 @@ var nameCollector = module.exports = { collection: mdbClient.db('heroku_jrtfvpd9').collection('ppl'), + buffer: [], + operationPending: false, collect: async function (participant) { if (config.testmode) return; + + if (this.operationPending) { this.buffer.push(participant); return } + this.operationPending = true; + if (participant.name == "Anonymous" || participant.name == "Anonymoose") return; - + var newMsg = function(continued){ var str = `__**${participant._id}**__${continued ? ' (continued)' : ''}\n${participant.name}`; return dClient.channels.get(config.channels.name_collection).send(str); @@ -15,23 +21,25 @@ var nameCollector = module.exports = { // update person if (document.names.includes(participant.name)) return; document.names.push(participant.name); - this.collection.updateOne({_id: participant._id}, {$set:{names: document.names}}); + await this.collection.updateOne({_id: participant._id}, {$set:{names: document.names}}); let message = await dClient.channels.get(config.channels.name_collection).messages.fetch(document.discord_msg_id); try { await message.edit(message.content + ', ' + participant.name); } catch(e) { let message = await newMsg(true); - this.collection.updateOne({_id: participant._id}, {$set:{discord_msg_id: message.id}}); + await this.collection.updateOne({_id: participant._id}, {$set:{discord_msg_id: message.id}}); } } else { // add new person let message = await newMsg(); - nameCollector.collection.insertOne({ + await nameCollector.collection.insertOne({ _id: participant._id, discord_msg_id: message.id, names: [participant.name] }); } + if (this.buffer.length) this.collect(this.buffer.shift()); + else this.operationPending = false; } } \ No newline at end of file