2024-07-12 19:07:59 -04:00
import { getWebScraperQueue } from "../queue-service" ;
import { sendSlackWebhook } from "./slack" ;
export function initAlerts() {
2024-07-12 19:12:56 -04:00
try {
if (
process . env . SLACK_WEBHOOK_URL &&
process . env . ENV === "production" &&
process . env . ALERT_NUM_ACTIVE_JOBS &&
process . env . ALERT_NUM_WAITING_JOBS
) {
console . info ( "Initializing alerts" ) ;
const checkActiveJobs = async ( ) = > {
try {
const webScraperQueue = getWebScraperQueue ( ) ;
const activeJobs = await webScraperQueue . getActiveCount ( ) ;
if ( activeJobs > Number ( process . env . ALERT_NUM_ACTIVE_JOBS ) ) {
console . warn (
` Alert: Number of active jobs is over ${ process . env . ALERT_NUM_ACTIVE_JOBS } . Current active jobs: ${ activeJobs } . `
) ;
sendSlackWebhook (
` Alert: Number of active jobs is over ${ process . env . ALERT_NUM_ACTIVE_JOBS } . Current active jobs: ${ activeJobs } ` ,
true
) ;
} else {
console . info (
` Number of active jobs is under ${ process . env . ALERT_NUM_ACTIVE_JOBS } . Current active jobs: ${ activeJobs } `
) ;
}
} catch ( error ) {
console . error ( "Failed to check active jobs:" , error ) ;
}
} ;
const checkWaitingQueue = async ( ) = > {
2024-07-12 19:07:59 -04:00
const webScraperQueue = getWebScraperQueue ( ) ;
2024-07-12 19:12:56 -04:00
const waitingJobs = await webScraperQueue . getWaitingCount ( ) ;
if ( waitingJobs > Number ( process . env . ALERT_NUM_WAITING_JOBS ) ) {
2024-07-12 19:07:59 -04:00
console . warn (
2024-07-12 19:12:56 -04:00
` Alert: Number of waiting jobs is over ${ process . env . ALERT_NUM_WAITING_JOBS } . Current waiting jobs: ${ waitingJobs } . `
2024-07-12 19:07:59 -04:00
) ;
sendSlackWebhook (
2024-07-12 19:12:56 -04:00
` Alert: Number of waiting jobs is over ${ process . env . ALERT_NUM_WAITING_JOBS } . Current waiting jobs: ${ waitingJobs } . Scale up the number of workers with fly scale count worker=20 ` ,
2024-07-12 19:07:59 -04:00
true
) ;
}
2024-07-12 19:12:56 -04:00
} ;
2024-07-12 19:07:59 -04:00
2024-07-12 19:12:56 -04:00
const checkAll = async ( ) = > {
await checkActiveJobs ( ) ;
await checkWaitingQueue ( ) ;
} ;
2024-07-12 19:07:59 -04:00
2024-07-12 19:12:56 -04:00
setInterval ( checkAll , 5 * 60 * 1000 ) ; // Run every 5 minutes
}
} catch ( error ) {
console . error ( "Failed to initialize alerts:" , error ) ;
2024-07-12 19:07:59 -04:00
}
}