-
Notifications
You must be signed in to change notification settings - Fork 81
/
pool.js
374 lines (320 loc) · 11.6 KB
/
pool.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
'use strict';
var simplesmtp = require('../index'),
EventEmitter = require('events').EventEmitter,
utillib = require('util'),
xoauth2 = require('xoauth2');
// expose to the world
module.exports = function(port, host, options) {
var pool = new SMTPConnectionPool(port, host, options);
return pool;
};
/**
* <p>Creates a SMTP connection pool</p>
*
* <p>Optional options object takes the following possible properties:</p>
* <ul>
* <li><b>secureConnection</b> - use SSL</li>
* <li><b>name</b> - the name of the client server</li>
* <li><b>auth</b> - authentication object <code>{user:'...', pass:'...'}</code>
* <li><b>ignoreTLS</b> - ignore server support for STARTTLS</li>
* <li><b>tls</b> - options for createCredentials</li>
* <li><b>debug</b> - output client and server messages to console</li>
* <li><b>maxConnections</b> - how many connections to keep in the pool</li>
* </ul>
*
* @constructor
* @namespace SMTP Client Pool module
* @param {Number} [port=25] The port number to connecto to
* @param {String} [host='localhost'] THe hostname to connect to
* @param {Object} [options] optional options object
*/
function SMTPConnectionPool(port, host, options) {
EventEmitter.call(this);
/**
* Port number to connect to
* @public
*/
this.port = port || 25;
/**
* Hostname to connect to
* @public
*/
this.host = host || 'localhost';
/**
* Options object
* @public
*/
this.options = options || {};
this.options.maxConnections = this.options.maxConnections || 5;
this.options.maxMessages = this.options.maxMessages || Infinity;
/**
* An array of connections that are currently idle
* @private
*/
this._connectionsAvailable = [];
/**
* An array of connections that are currently in use
* @private
*/
this._connectionsInUse = [];
/**
* Message queue (FIFO)
* @private
*/
this._messageQueue = [];
/**
* Counter for generating ID values for debugging
* @private
*/
this._idgen = 0;
// Initialize XOAUTH2 if needed
if (this.options.auth && typeof this.options.auth.XOAuth2 == 'object') {
if (!this.options.auth.XOAuth2.user && this.options.auth.user) {
this.options.auth.XOAuth2.user = this.options.auth.user;
}
this.options.auth.XOAuth2 = xoauth2.createXOAuth2Generator(this.options.auth.XOAuth2);
}
}
utillib.inherits(SMTPConnectionPool, EventEmitter);
/**
* <p>Sends a message. If there's any idling connections available
* use one to send the message immediatelly, otherwise add to queue.</p>
*
* @param {Object} message MailComposer object
* @param {Function} callback Callback function to run on finish, gets an
* <code>error</code> object as a parameter if the sending failed
* and on success an object with <code>failedRecipients</code> array as
* a list of addresses that were rejected (if any) and
* <code>message</code> which indicates the last message received from
* the server
*/
SMTPConnectionPool.prototype.sendMail = function(message, callback) {
var connection;
message.returnCallback = callback;
if (this._connectionsAvailable.length) {
// if available connections pick one
connection = this._connectionsAvailable.pop();
this._connectionsInUse.push(connection);
this._processMessage(message, connection);
} else {
this._messageQueue.push(message);
if (this._connectionsAvailable.length + this._connectionsInUse.length < this.options.maxConnections) {
this._createConnection();
}
}
};
/**
* <p>Closes all connections</p>
*/
SMTPConnectionPool.prototype.close = function(callback) {
var connection;
// for some reason destroying the connections seem to be the only way :S
while (this._connectionsAvailable.length) {
connection = this._connectionsAvailable.pop();
connection.quit();
}
while (this._connectionsInUse.length) {
connection = this._connectionsInUse.pop();
connection.quit();
}
if (callback) {
if (typeof setImmediate == 'function') {
setImmediate(callback);
} else {
process.nextTick(callback);
}
}
};
/**
* <p>Initiates a connection to the SMTP server and adds it to the pool</p>
*/
SMTPConnectionPool.prototype._createConnection = function() {
var connectionOptions = {
instanceId: ++this._idgen,
debug: !! this.options.debug,
logFile: this.options.logFile,
ignoreTLS: !! this.options.ignoreTLS,
tls: this.options.tls || false,
auth: this.options.auth || false,
authMethod: this.options.authMethod,
name: this.options.name || false,
secureConnection: !! this.options.secureConnection
},
connection;
if ('greetingTimeout' in this.options) {
connectionOptions.greetingTimeout = this.options.greetingTimeout;
}
if ('socketTimeout' in this.options) {
connectionOptions.socketTimeout = this.options.socketTimeout;
}
if ('connectionTimeout' in this.options) {
connectionOptions.connectionTimeout = this.options.connectionTimeout;
}
if ('rejectUnathorized' in this.options) {
connectionOptions.rejectUnathorized = this.options.rejectUnathorized;
}
if ('localAddress' in this.options) {
connectionOptions.localAddress = this.options.localAddress;
}
connection = simplesmtp.connect(this.port, this.host, connectionOptions);
connection._messagesProcessed = 0;
connection.on('idle', this._onConnectionIdle.bind(this, connection));
connection.on('message', this._onConnectionMessage.bind(this, connection));
connection.on('ready', this._onConnectionReady.bind(this, connection));
connection.on('error', this._onConnectionError.bind(this, connection));
connection.on('end', this._onConnectionEnd.bind(this, connection));
connection.on('rcptFailed', this._onConnectionRCPTFailed.bind(this, connection));
this.emit('connectionCreated', connection);
// as the connection is not ready yet, add to 'in use' queue
this._connectionsInUse.push(connection);
};
/**
* <p>Processes a message by assigning it to a connection object and initiating
* the sending process by setting the envelope</p>
*
* @param {Object} message MailComposer message object
* @param {Object} connection <code>simplesmtp.connect</code> connection
*/
SMTPConnectionPool.prototype._processMessage = function(message, connection) {
connection.currentMessage = message;
message.currentConnection = connection;
connection._messagesProcessed++;
// send envelope
connection.useEnvelope(message.getEnvelope());
};
/**
* <p>Will be fired on <code>'idle'</code> events by the connection, if
* there's a message currently in queue</p>
*
* @event
* @param {Object} connection Connection object that fired the event
*/
SMTPConnectionPool.prototype._onConnectionIdle = function(connection) {
var message = this._messageQueue.shift();
if (message) {
this._processMessage(message, connection);
} else {
for (var i = 0, len = this._connectionsInUse.length; i < len; i++) {
if (this._connectionsInUse[i] == connection) {
this._connectionsInUse.splice(i, 1); // remove from list
break;
}
}
this._connectionsAvailable.push(connection);
}
};
/**
* <p>Will be called when not all recipients were accepted</p>
*
* @event
* @param {Object} connection Connection object that fired the event
* @param {Array} addresses Failed addresses as an array of strings
*/
SMTPConnectionPool.prototype._onConnectionRCPTFailed = function(connection, addresses) {
if (connection.currentMessage) {
connection.currentMessage.failedRecipients = addresses;
}
};
/**
* <p>Will be called when the client is waiting for a message to deliver</p>
*
* @event
* @param {Object} connection Connection object that fired the event
*/
SMTPConnectionPool.prototype._onConnectionMessage = function(connection) {
if (connection.currentMessage) {
connection.currentMessage.streamMessage();
connection.currentMessage.pipe(connection);
}
};
/**
* <p>Will be called when a message has been delivered</p>
*
* @event
* @param {Object} connection Connection object that fired the event
* @param {Boolean} success True if the message was queued by the SMTP server
* @param {String} message Last message received from the server
*/
SMTPConnectionPool.prototype._onConnectionReady = function(connection, success, message) {
var error, responseObj = {};
if (connection._messagesProcessed >= this.options.maxMessages && connection.socket) {
connection.emit('end');
connection.removeAllListeners();
if (connection.socket) {
connection.socket.destroy();
}
this.emit('released', connection);
}
if (connection.currentMessage && connection.currentMessage.returnCallback) {
if (success) {
if (connection.currentMessage.failedRecipients) {
responseObj.failedRecipients = connection.currentMessage.failedRecipients;
}
if (message) {
responseObj.message = message;
}
if (connection.currentMessage._messageId) {
responseObj.messageId = connection.currentMessage._messageId;
}
connection.currentMessage.returnCallback(null, responseObj);
} else {
error = new Error('Message delivery failed' + (message ? ': ' + message : ''));
error.name = 'DeliveryError';
error.data = message;
connection.currentMessage.returnCallback(error);
}
}
connection.currentMessage = false;
};
/**
* <p>Will be called when an error occurs</p>
*
* @event
* @param {Object} connection Connection object that fired the event
* @param {Object} error Error object
*/
SMTPConnectionPool.prototype._onConnectionError = function(connection, error) {
var message = connection.currentMessage;
connection.currentMessage = false;
// clear a first message from the list, otherwise an infinite loop will emerge
if (!message) {
message = this._messageQueue.shift();
}
if (message && message.returnCallback) {
message.returnCallback(error);
}
};
/**
* <p>Will be called when a connection to the client is closed</p>
*
* @event
* @param {Object} connection Connection object that fired the event
*/
SMTPConnectionPool.prototype._onConnectionEnd = function(connection) {
var removed = false,
i, len;
// if in 'available' list, remove
for (i = 0, len = this._connectionsAvailable.length; i < len; i++) {
if (this._connectionsAvailable[i] == connection) {
this._connectionsAvailable.splice(i, 1); // remove from list
removed = true;
break;
}
}
if (!removed) {
// if in 'in use' list, remove
for (i = 0, len = this._connectionsInUse.length; i < len; i++) {
if (this._connectionsInUse[i] == connection) {
this._connectionsInUse.splice(i, 1); // remove from list
removed = true;
break;
}
}
}
// if there's still unprocessed mail and available connection slots, create
// a new connection
if (this._messageQueue.length &&
this._connectionsInUse.length + this._connectionsAvailable.length < this.options.maxConnections) {
this._createConnection();
}
};