From 23dc250098b233f3e84ca8a20c672d06de56c09f Mon Sep 17 00:00:00 2001 From: Ben Moore Date: Wed, 20 Jul 2016 12:18:34 +0100 Subject: [PATCH] Fix - large numbers of undispatched events This resolves an issue where the maximum call stack size could be hit when processing 1000s of undispatched events on startup --- lib/eventDispatcher.js | 5 +++++ test/eventDispatcherTest.js | 40 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/lib/eventDispatcher.js b/lib/eventDispatcher.js index 53acb9aa..46ba435c 100644 --- a/lib/eventDispatcher.js +++ b/lib/eventDispatcher.js @@ -112,8 +112,13 @@ EventDispatcher.prototype = { } if (events) { + for (var i = 0, len = events.length; i < len; i++) { self.undispatchedEventsQueue.push(events[i]); + // If there are a lot of events then we can hit issues with the call stack size when processing in one go + if(i % 1000 === 0){ + trigger(self); + } } } diff --git a/test/eventDispatcherTest.js b/test/eventDispatcherTest.js index 9bba76bb..129da510 100644 --- a/test/eventDispatcherTest.js +++ b/test/eventDispatcherTest.js @@ -92,6 +92,46 @@ describe('EventDispatcher', function () { }); + it('should not crash when there are lots of pending events', function (done) { + + var eventsInStore = []; + + for(var i = 0; i < 10000; i++){ + eventsInStore.push({ + payload: { + index: i + } + }); + } + + function getUndispatchedEvents (callback) { + callback(null, eventsInStore); + } + + var publishedEvents = []; + + function publisher (evt) { + publishedEvents.push(evt); + check(); + } + + function check () { + if (publishedEvents.length === eventsInStore.length) { + done(); + } + } + + var eventDispatcher = new EventDispatcher(publisher, { + getUndispatchedEvents: getUndispatchedEvents, + setEventToDispatched: function (evt, callback) { callback(null); }}); + expect(eventDispatcher.undispatchedEventsQueue.length).to.eql(0); + + eventDispatcher.start(function(err) { + expect(err).not.to.be.ok(); + }); + + }); + }); describe('and calling addUndispatchedEvents', function () {