From cf5c64f96bd83c3af3a8ea342ee4acd8d4d125fa Mon Sep 17 00:00:00 2001 From: Simon Backx Date: Thu, 5 Jan 2023 15:29:03 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fixed=20batches=20can=20have=20a?= =?UTF-8?q?n=20empty=20"to"=20field=20(#16064)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fixes https://github.com/TryGhost/Team/issues/2246 This solution adds some retries when fetching the recipients for a batch. For an unknown reason the recipients can be empty (while they aren't in the database). This should fix the issue for now until we find more information about the root cause. --- .../bulk-email/bulk-email-processor.js | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) 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});