1 import * as kue from 'kue'
2 import { JobState, JobType } from '../../../shared/models'
3 import { logger } from '../../helpers/logger'
4 import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY } from '../../initializers'
5 import { Redis } from '../redis'
6 import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
7 import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
8 import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
9 import { EmailPayload, processEmail } from './handlers/email'
10 import { processVideoFile, VideoFilePayload } from './handlers/video-file'
12 type CreateJobArgument =
13 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
14 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
15 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
16 { type: 'video-file', payload: VideoFilePayload } |
17 { type: 'email', payload: EmailPayload }
19 const handlers: { [ id in JobType ]: (job: kue.Job) => Promise<any>} = {
20 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
21 'activitypub-http-unicast': processActivityPubHttpUnicast,
22 'activitypub-http-fetcher': processActivityPubHttpFetcher,
23 'video-file': processVideoFile,
29 private static instance: JobQueue
31 private jobQueue: kue.Queue
32 private initialized = false
33 private jobRedisPrefix: string
35 private constructor () {}
38 // Already initialized
39 if (this.initialized === true) return
40 this.initialized = true
42 this.jobRedisPrefix = 'q-' + CONFIG.WEBSERVER.HOST
44 this.jobQueue = kue.createQueue({
45 prefix: this.jobRedisPrefix,
47 host: CONFIG.REDIS.HOSTNAME,
48 port: CONFIG.REDIS.PORT,
49 auth: CONFIG.REDIS.AUTH
53 this.jobQueue.setMaxListeners(15)
55 this.jobQueue.on('error', err => {
56 logger.error('Error in job queue.', err)
59 this.jobQueue.watchStuckJobs(5000)
61 await this.reactiveStuckJobs()
63 for (const handlerName of Object.keys(handlers)) {
64 this.jobQueue.process(handlerName, JOB_CONCURRENCY[handlerName], async (job, done) => {
66 const res = await handlers[ handlerName ](job)
67 return done(null, res)
75 createJob (obj: CreateJobArgument, priority = 'normal') {
76 return new Promise((res, rej) => {
78 .create(obj.type, obj.payload)
80 .attempts(JOB_ATTEMPTS[obj.type])
81 .backoff({ delay: 60 * 1000, type: 'exponential' })
83 if (err) return rej(err)
90 async listForApi (state: JobState, start: number, count: number, sort: 'ASC' | 'DESC'): Promise<kue.Job[]> {
91 const jobStrings = await Redis.Instance.listJobs(this.jobRedisPrefix, state, 'alpha', sort, start, count)
93 const jobPromises = jobStrings
94 .map(s => s.split('|'))
95 .map(([ , jobId ]) => this.getJob(parseInt(jobId, 10)))
97 return Promise.all(jobPromises)
100 count (state: JobState) {
101 return new Promise<number>((res, rej) => {
102 this.jobQueue[state + 'Count']((err, total) => {
103 if (err) return rej(err)
111 const now = new Date().getTime()
112 kue.Job.rangeByState('complete', 0, -1, 'asc', (err, jobs) => {
114 logger.error('Cannot get jobs when removing old jobs.', err)
118 for (const job of jobs) {
119 if (now - job.created_at > JOB_COMPLETED_LIFETIME) {
126 private reactiveStuckJobs () {
127 const promises: Promise<any>[] = []
129 this.jobQueue.active((err, ids) => {
132 for (const id of ids) {
133 kue.Job.get(id, (err, job) => {
136 const p = new Promise((res, rej) => {
137 job.inactive(err => {
138 if (err) return rej(err)
148 return Promise.all(promises)
151 private getJob (id: number) {
152 return new Promise<kue.Job>((res, rej) => {
153 kue.Job.get(id, (err, job) => {
154 if (err) return rej(err)
161 static get Instance () {
162 return this.instance || (this.instance = new this())
166 // ---------------------------------------------------------------------------