2022-10-13 18:27:04 +02:00
|
|
|
import env from "../environment"
|
|
|
|
import { getRedisOptions } from "../redis/utils"
|
|
|
|
import { JobQueue } from "./constants"
|
|
|
|
import InMemoryQueue from "./inMemoryQueue"
|
2022-10-13 18:55:05 +02:00
|
|
|
import BullQueue from "bull"
|
|
|
|
import { addListeners, StalledFn } from "./listeners"
|
2022-10-13 18:27:04 +02:00
|
|
|
const { opts, redisProtocolUrl } = getRedisOptions()
|
|
|
|
|
|
|
|
const CLEANUP_PERIOD_MS = 60 * 1000
|
|
|
|
let QUEUES: BullQueue.Queue[] | InMemoryQueue[] = []
|
|
|
|
let cleanupInterval: NodeJS.Timeout
|
|
|
|
|
|
|
|
async function cleanup() {
|
|
|
|
for (let queue of QUEUES) {
|
|
|
|
await queue.clean(CLEANUP_PERIOD_MS, "completed")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-14 20:24:03 +02:00
|
|
|
export function createQueue<T>(
|
2022-10-13 18:55:05 +02:00
|
|
|
jobQueue: JobQueue,
|
2022-10-24 11:04:14 +02:00
|
|
|
opts: { removeStalledCb?: StalledFn }
|
2022-10-14 20:24:03 +02:00
|
|
|
): BullQueue.Queue<T> {
|
2022-10-13 18:27:04 +02:00
|
|
|
const queueConfig: any = redisProtocolUrl || { redis: opts }
|
|
|
|
let queue: any
|
2022-10-21 17:02:13 +02:00
|
|
|
if (!env.isTest()) {
|
2022-10-13 18:27:04 +02:00
|
|
|
queue = new BullQueue(jobQueue, queueConfig)
|
|
|
|
} else {
|
2022-10-13 18:55:05 +02:00
|
|
|
queue = new InMemoryQueue(jobQueue, queueConfig)
|
2022-10-13 18:27:04 +02:00
|
|
|
}
|
2022-10-24 11:04:14 +02:00
|
|
|
addListeners(queue, jobQueue, opts?.removeStalledCb)
|
2022-10-13 18:27:04 +02:00
|
|
|
QUEUES.push(queue)
|
|
|
|
if (!cleanupInterval) {
|
|
|
|
cleanupInterval = setInterval(cleanup, CLEANUP_PERIOD_MS)
|
|
|
|
// fire off an initial cleanup
|
|
|
|
cleanup().catch(err => {
|
|
|
|
console.error(`Unable to cleanup automation queue initially - ${err}`)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return queue
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.shutdown = async () => {
|
|
|
|
if (QUEUES.length) {
|
|
|
|
clearInterval(cleanupInterval)
|
|
|
|
for (let queue of QUEUES) {
|
|
|
|
await queue.close()
|
|
|
|
}
|
|
|
|
QUEUES = []
|
|
|
|
}
|
|
|
|
console.log("Queues shutdown")
|
|
|
|
}
|