2020-11-26 18:12:12 +03:00
const { parentPort } = require ( 'bthreads' ) ;
2020-11-26 16:09:38 +03:00
const debug = require ( 'ghost-ignition' ) . debug ( 'jobs:email-analytics:fetch-all' ) ;
// one-off job to fetch all available events and re-process them idempotently
// NB. can be a _very_ long job for sites with many members and frequent emails
function cancel ( ) {
2021-02-22 09:35:04 +03:00
parentPort . postMessage ( 'Email analytics fetch-all job cancelled before completion' ) ;
2020-11-26 16:09:38 +03:00
if ( parentPort ) {
parentPort . postMessage ( 'cancelled' ) ;
} else {
setTimeout ( ( ) => {
process . exit ( 0 ) ;
} , 1000 ) ;
}
}
if ( parentPort ) {
parentPort . once ( 'message' , ( message ) => {
if ( message === 'cancel' ) {
return cancel ( ) ;
}
} ) ;
}
( async ( ) => {
2020-12-07 06:43:57 +03:00
const models = require ( '../../../models' ) ;
const settingsService = require ( '../../settings' ) ;
2020-11-26 16:09:38 +03:00
2020-12-07 06:43:57 +03:00
// 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 ( ) ;
2020-11-26 16:09:38 +03:00
2020-12-07 06:43:57 +03:00
const emailAnalyticsService = require ( '../' ) ;
2020-11-26 16:09:38 +03:00
2020-12-07 06:43:57 +03:00
const fetchStartDate = new Date ( ) ;
debug ( 'Starting email analytics fetch of all available events' ) ;
const eventStats = await emailAnalyticsService . fetchAll ( ) ;
const fetchEndDate = new Date ( ) ;
debug ( ` Finished fetching ${ eventStats . totalEvents } analytics events in ${ fetchEndDate - fetchStartDate } ms ` ) ;
2020-11-26 16:09:38 +03:00
2020-12-07 06:43:57 +03:00
const aggregateStartDate = new Date ( ) ;
debug ( ` Starting email analytics aggregation for ${ eventStats . emailIds . length } emails ` ) ;
await emailAnalyticsService . aggregateStats ( eventStats ) ;
const aggregateEndDate = new Date ( ) ;
debug ( ` Finished aggregating email analytics in ${ aggregateEndDate - aggregateStartDate } ms ` ) ;
2020-11-26 16:09:38 +03:00
2021-02-22 09:35:04 +03:00
parentPort . postMessage ( ` Fetched ${ eventStats . totalEvents } events and aggregated stats for ${ eventStats . emailIds . length } emails in ${ aggregateEndDate - fetchStartDate } ms ` ) ;
2020-11-26 16:09:38 +03:00
2020-12-07 06:43:57 +03:00
if ( parentPort ) {
parentPort . postMessage ( 'done' ) ;
} else {
2020-11-26 16:09:38 +03:00
// give the logging pipes time finish writing before exit
setTimeout ( ( ) => {
2020-12-07 06:43:57 +03:00
process . exit ( 0 ) ;
2020-11-26 16:09:38 +03:00
} , 1000 ) ;
}
} ) ( ) ;