Added support for throttling

This commit is contained in:
Andris Reinman 2016-07-05 19:31:57 +03:00
parent 10bd4614ef
commit cf0042c50a
9 changed files with 67 additions and 20 deletions

View file

@ -116,7 +116,7 @@ function getTemplate(template, callback) {
}
function createMailer(callback) {
settings.list(['smtpHostname', 'smtpPort', 'smtpEncryption', 'smtpUser', 'smtpPass', 'smtpLog', 'smtpDisableAuth', 'smtpMaxConnections', 'smtpMaxMessages', 'smtpSelfSigned', 'pgpPrivateKey', 'pgpPassphrase'], (err, configItems) => {
settings.list(['smtpHostname', 'smtpPort', 'smtpEncryption', 'smtpUser', 'smtpPass', 'smtpLog', 'smtpDisableAuth', 'smtpMaxConnections', 'smtpMaxMessages', 'smtpSelfSigned', 'pgpPrivateKey', 'pgpPassphrase', 'smtpThrottling'], (err, configItems) => {
if (err) {
return callback(err);
}
@ -126,6 +126,7 @@ function createMailer(callback) {
oldListeners = module.exports.transport.listeners('idle');
module.exports.transport.removeAllListeners('idle');
module.exports.transport.removeAllListeners('stream');
module.exports.transport.checkThrottling = null;
}
module.exports.transport = nodemailer.createTransport({
@ -160,6 +161,27 @@ function createMailer(callback) {
oldListeners.forEach(listener => module.exports.transport.on('idle', listener));
}
let throttling = Number(configItems.smtpThrottling) || 0;
if (throttling) {
// convert to messages/second
throttling = 1 / (throttling / (3600 * 1000));
}
let lastCheck = Date.now();
module.exports.transport.checkThrottling = function (next) {
if (!throttling) {
return next();
}
let nextCheck = Date.now();
let checkDiff = (nextCheck - lastCheck);
lastCheck = nextCheck;
if (checkDiff < throttling) {
log.verbose('Mail', 'Throttling next message in %s sec.', (throttling - checkDiff) / 1000);
setTimeout(next, throttling - checkDiff);
} else {
next();
}
};
caches.cache.delete('sender queue');
return callback(null, module.exports.transport);
});