diff --git a/ghost/core/core/server/services/bulk-email/bulk-email-processor.js b/ghost/core/core/server/services/bulk-email/bulk-email-processor.js index 1bb3ec47ea..c6b52b1898 100644 --- a/ghost/core/core/server/services/bulk-email/bulk-email-processor.js +++ b/ghost/core/core/server/services/bulk-email/bulk-email-processor.js @@ -12,6 +12,12 @@ const postEmailSerializer = require('../mega/post-email-serializer'); const configService = require('../../../shared/config'); const settingsCache = require('../../../shared/settings-cache'); +async function sleep(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + const messages = { error: 'The email service received an error from mailgun and was unable to send.' }; @@ -145,14 +151,27 @@ module.exports = { }); } - // get recipient rows via knex to avoid costly bookshelf model instantiation - const recipientRows = await models.EmailRecipient - .getFilteredCollectionQuery({filter: `batch_id:${emailBatchId}`}); - // Patch to prevent saving the related email model await emailBatchModel.save({status: 'submitting'}, {...knexOptions, patch: true}); try { + // get recipient rows via knex to avoid costly bookshelf model instantiation + let recipientRows = await models.EmailRecipient.getFilteredCollectionQuery({filter: `batch_id:${emailBatchId}`}, knexOptions); + + // For an unknown reason, the returned recipient rows is sometimes an empty array + // refs https://github.com/TryGhost/Team/issues/2246 + let counter = 0; + while (recipientRows.length === 0 && counter < 5) { + logging.info('[sendEmailJob] Found zero recipients [retries:' + counter + '] for email batch ' + emailBatchId); + + counter += 1; + await sleep(200); + recipientRows = await models.EmailRecipient.getFilteredCollectionQuery({filter: `batch_id:${emailBatchId}`}, knexOptions); + } + if (counter > 0) { + logging.info('[sendEmailJob] Recovered recipients [retries:' + counter + '] for email batch ' + emailBatchId + ' - ' + recipientRows.length + ' recipients found'); + } + // Load newsletter data on email await emailBatchModel.relations.email.getLazyRelation('newsletter', {require: false, ...knexOptions});