Moved email sending to the background job queue

no issue

- moves the meat of `pendingEmailHandler()` code into a new function `sendEmailJob()` that is passed over to the new job service
- lets the server keep processing email generation and sending when it receives a shutdown request rather than halting processing mid-send and ending up in a partial state
This commit is contained in:
Kevin Ansfield 2020-08-12 17:01:59 +01:00
parent 5f84f0e42c
commit c7ff4c9e93

View File

@ -7,6 +7,7 @@ const {events, i18n} = require('../../lib/common');
const logging = require('../../../shared/logging'); const logging = require('../../../shared/logging');
const membersService = require('../members'); const membersService = require('../members');
const bulkEmailService = require('../bulk-email'); const bulkEmailService = require('../bulk-email');
const jobService = require('../jobs');
const models = require('../../models'); const models = require('../../models');
const postEmailSerializer = require('./post-email-serializer'); const postEmailSerializer = require('./post-email-serializer');
@ -184,18 +185,8 @@ async function handleUnsubscribeRequest(req) {
} }
} }
async function pendingEmailHandler(emailModel, options) { async function sendEmailJob({emailModel, options}) {
// CASE: do not send email if we import a database
// TODO: refactor post.published events to never fire on importing
if (options && options.importing) {
return;
}
const postModel = await models.Post.findOne({id: emailModel.get('post_id')}, {withRelated: ['authors']}); const postModel = await models.Post.findOne({id: emailModel.get('post_id')}, {withRelated: ['authors']});
if (emailModel.get('status') !== 'pending') {
return;
}
let meta = []; let meta = [];
let error = null; let error = null;
let startEmailSend = null; let startEmailSend = null;
@ -262,7 +253,7 @@ async function pendingEmailHandler(emailModel, options) {
status: batchStatus, status: batchStatus,
meta: JSON.stringify(successes), meta: JSON.stringify(successes),
error: error, error: error,
error_data: JSON.stringify(failures) // NOTE:need to discuss how we store this error_data: JSON.stringify(failures) // NOTE: need to discuss how we store this
}, { }, {
id: emailModel.id id: emailModel.id
}); });
@ -271,6 +262,20 @@ async function pendingEmailHandler(emailModel, options) {
} }
} }
async function pendingEmailHandler(emailModel, options) {
// CASE: do not send email if we import a database
// TODO: refactor post.published events to never fire on importing
if (options && options.importing) {
return;
}
if (emailModel.get('status') !== 'pending') {
return;
}
return jobService.addJob(sendEmailJob, {emailModel, options});
}
const statusChangedHandler = (emailModel, options) => { const statusChangedHandler = (emailModel, options) => {
const emailRetried = emailModel.wasChanged() const emailRetried = emailModel.wasChanged()
&& emailModel.get('status') === 'pending' && emailModel.get('status') === 'pending'