Skip to content

Commit

Permalink
Limit inProgress using maxItems (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
fathyb authored and f2prateek committed Jul 16, 2018
1 parent 9eebb5e commit 5d34c90
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ Queue.prototype._processHead = function() {
});
}

while (queue.length && queue[0].time <= now) {
var inProgressSize = Object.keys(inProgress).length;

while (queue.length && queue[0].time <= now && inProgressSize++ < self.maxItems) {
var el = queue.shift();
var id = uuid();

Expand Down
57 changes: 57 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,63 @@ describe('Queue', function() {
assert(call === queue.maxAttempts + 1);
});
});

it('should limit inProgress using maxItems', function() {
var waiting = [];
var i;

queue.maxItems = 100;
queue.maxAttempts = 2;
queue.fn = function(_, done) {
waiting.push(done);
};

// add maxItems * 2 items
for (i = 0; i < queue.maxItems * 2; i++) {
queue.addItem({ index: i });
}

// the queue should be full
assert(size(queue).queue === queue.maxItems);

queue.start();
// the queue is now empty and everything is in progress
assert(size(queue).queue === 0);
assert(size(queue).inProgress === queue.maxItems);

// while the items are in progress let's add maxItems times two items
for (i = 0; i < queue.maxItems * 2; i++) {
queue.addItem({ index: i });
}

// inProgress and queue should be full
assert(size(queue).queue === queue.maxItems);
assert(size(queue).inProgress === queue.maxItems);
assert(waiting.length === queue.maxItems);

// resolved all waiting items
while (waiting.length) {
waiting.pop()();
}

// inProgress should now be empty
assert(size(queue).queue === queue.maxItems);
assert(size(queue).inProgress === 0);

// wait for the queue to be processed
clock.tick(queue.getDelay(0));

// items should now be in progress
assert(size(queue).queue === 0);
assert(size(queue).inProgress === queue.maxItems);

function size(queue) {
return {
queue: queue._store.get(queue.keys.QUEUE).length,
inProgress: Object.keys(queue._store.get(queue.keys.IN_PROGRESS) || {}).length
};
}
});
});

describe('events', function() {
Expand Down

0 comments on commit 5d34c90

Please sign in to comment.