From 10c2874d19f6821ff546fbbdf5bc4492c72cddb6 Mon Sep 17 00:00:00 2001 From: Scott Nonnenberg Date: Fri, 26 May 2017 15:33:50 -0700 Subject: [PATCH] Fix race condition: Pull from database after add to conversation Also add some console logs to help us determine whether this ever happens to people in the wild. FREEBIE --- js/models/conversations.js | 3 +++ js/models/messages.js | 21 +++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/js/models/conversations.js b/js/models/conversations.js index 59e0aa60c8..669969506b 100644 --- a/js/models/conversations.js +++ b/js/models/conversations.js @@ -303,6 +303,9 @@ var read = unreadMessages.map(function(m) { if (this.messageCollection.get(m.id)) { m = this.messageCollection.get(m.id); + } else { + console.log('Marked a message as read in the database, but ' + + 'it was not in messageCollection.'); } m.markRead(); return { diff --git a/js/models/messages.js b/js/models/messages.js index dbc5e56bb4..c8a42bff12 100644 --- a/js/models/messages.js +++ b/js/models/messages.js @@ -468,10 +468,23 @@ message.save().then(function() { conversation.save().then(function() { conversation.trigger('newmessage', message); - if (message.get('unread')) { - conversation.notify(message); - } - resolve(); + // We fetch() here because, between the message.save() above and the previous + // line's trigger() call, we might have marked all messages unread in the + // database. This message might already be read! + var previousUnread = message.get('unread'); + message.fetch().then(function() { + if (previousUnread !== message.get('unread')) { + console.log('Caught race condition on new message read state! ' + + 'Manually starting timers.'); + // We call markRead() even though the message is already marked read + // because we need to start expiration timers, etc. + message.markRead(); + } + if (message.get('unread')) { + conversation.notify(message); + } + resolve(); + }); }); }); });