Skip to content

Commit

Permalink
Update connection.js to support a "shutdown" command
Browse files Browse the repository at this point in the history
This change adds a shutdown method that indicates to socketDrained that it should close connections once there are no more notifications to send. The side effect is that the node process will end. I've tested the change both with all successful messages, as well as when a few messages can't be sent. In both cases, the program does not shutdown until all messages that can be successfully sent our sent.
  • Loading branch information
ejc3 committed Oct 30, 2013
1 parent 3089bb5 commit 212697a
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/connection.js
Expand Up @@ -84,6 +84,9 @@ function Connection (options) {

this.socketId = 0;

// when true, we end all sockets after the pending notifications reach 0
this.shutdownPending = false;

events.EventEmitter.call(this);
}

Expand All @@ -99,7 +102,7 @@ Connection.prototype.checkInitialized = function () {
};

/**
* You should never need to call this method, initialisation and connection is handled by {@link Connection#sendNotification}
* You should never need to call this method, initialization and connection is handled by {@link Connection#sendNotification}
* @private
*/
Connection.prototype.initialize = function () {
Expand Down Expand Up @@ -346,7 +349,7 @@ Connection.prototype.socketDrained = function(socket, serviceBuffer) {
socket.busy = false;
if(this.options.enhanced) {
var notification = socket.cachedNotifications[socket.cachedNotifications.length - 1];
this.emit('transmitted', notification.notification, notification.recipient);
this.emit('transmitted', notification.notification, notification.recipient, socket);
}
if(serviceBuffer === true && !this.runningOnNextTick) {
// There is a possibility that this could add multiple invocations to the
Expand All @@ -362,6 +365,12 @@ Connection.prototype.socketDrained = function(socket, serviceBuffer) {
}
this.runningOnNextTick = true;
}
if (this.notificationBuffer.length === 0 && this.shutdownPending) {
debug("closing connections");
for (var i = this.sockets.length - 1; i >= 0; i--) {
this.sockets[i].end();
}
}
};

/**
Expand Down Expand Up @@ -704,4 +713,11 @@ Connection.prototype.sendNotification = function (notification) {
return this.pushNotification(notification, notification.device);
};

/**
* End connetions with APNS once we've finished sending all notifications
*/
Connection.prototype.shutdown = function () {
this.shutdownPending = true;
};

module.exports = Connection;

0 comments on commit 212697a

Please sign in to comment.