From 42e452b1274597325bd2c5a95060f6eb1898847e Mon Sep 17 00:00:00 2001 From: Kevin Ansfield Date: Mon, 22 Feb 2021 12:10:19 +0000 Subject: [PATCH] Removed models require from analytics job (#12689) refs https://github.com/TryGhost/Ghost/issues/12496 By requiring the models layer the shared logging util was being required as a side-effect causing the open file descriptors problem to continue. Removing logging from the models layer isn't feasible due to deep require chains spreading across the codebase, it's much quicker to remove the need for models in the analytics job. - models layer was only needed because it's used by the session service - updated analytics job to create it's own instance of `EmailAnalyticsService` rather than the default instance in order to pass in custom dependencies - pass in custom `logging` object that uses `parentPort.postMessage` as a way of writing log output - pass in custom `settings` object that returns settings that have been manually fetched and cached during job instantiation --- .../email-analytics/jobs/fetch-latest.js | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/core/server/services/email-analytics/jobs/fetch-latest.js b/core/server/services/email-analytics/jobs/fetch-latest.js index dfb312c654..70f97761f3 100644 --- a/core/server/services/email-analytics/jobs/fetch-latest.js +++ b/core/server/services/email-analytics/jobs/fetch-latest.js @@ -26,15 +26,44 @@ if (parentPort) { } (async () => { - const models = require('../../../models'); - const settingsService = require('../../settings'); + const config = require('../../../../shared/config'); + const db = require('../../../data/db'); - // must be initialized before emailAnalyticsService is required otherwise - // requires are in the wrong order and settingsCache will always be empty - await models.init(); - await settingsService.init(); + const logging = { + info(message) { + parentPort.postMessage(message); + }, + warn(message) { + parentPort.postMessage(message); + }, + error(message) { + parentPort.postMessage(message); + } + }; - const emailAnalyticsService = require('../'); + const settingsRows = await db.knex('settings') + .whereIn('key', ['mailgun_api_key', 'mailgun_domain', 'mailgun_base_url']); + + const settingsCache = {}; + + settingsRows.forEach((row) => { + settingsCache[row.key] = row.value; + }); + + const settings = { + get(key) { + return settingsCache[key]; + } + }; + + const EmailAnalyticsService = require('../email-analytics'); + + const emailAnalyticsService = new EmailAnalyticsService({ + config, + db, + settings, + logging + }); const fetchStartDate = new Date(); debug('Starting email analytics fetch of latest events');