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'
11 import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
13 type CreateJobArgument =
14 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
15 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
16 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
17 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
18 { type: 'video-file', payload: VideoFilePayload } |
19 { type: 'email', payload: EmailPayload }
21 const handlers: { [ id in JobType ]: (job: kue.Job) => Promise<any>} = {
22 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
23 'activitypub-http-unicast': processActivityPubHttpUnicast,
24 'activitypub-http-fetcher': processActivityPubHttpFetcher,
25 'activitypub-follow': processActivityPubFollow,
26 'video-file': processVideoFile,
32 private static instance: JobQueue
34 private jobQueue: kue.Queue
35 private initialized = false
36 private jobRedisPrefix: string
38 private constructor () {}
41 // Already initialized
42 if (this.initialized === true) return
43 this.initialized = true
45 this.jobRedisPrefix = 'q-' + CONFIG.WEBSERVER.HOST
47 this.jobQueue = kue.createQueue({
48 prefix: this.jobRedisPrefix,
50 host: CONFIG.REDIS.HOSTNAME,
51 port: CONFIG.REDIS.PORT,
52 auth: CONFIG.REDIS.AUTH
56 this.jobQueue.setMaxListeners(20)
58 this.jobQueue.on('error', err => {
59 logger.error('Error in job queue.', { err })
62 this.jobQueue.watchStuckJobs(5000)
64 await this.reactiveStuckJobs()
66 for (const handlerName of Object.keys(handlers)) {
67 this.jobQueue.process(handlerName, JOB_CONCURRENCY[handlerName], async (job, done) => {
69 const res = await handlers[ handlerName ](job)
70 return done(null, res)
78 createJob (obj: CreateJobArgument, priority = 'normal') {
79 return new Promise((res, rej) => {
81 .create(obj.type, obj.payload)
83 .attempts(JOB_ATTEMPTS[obj.type])
84 .backoff({ delay: 60 * 1000, type: 'exponential' })
86 if (err) return rej(err)
93 async listForApi (state: JobState, start: number, count: number, sort: 'ASC' | 'DESC'): Promise<kue.Job[]> {
94 const jobStrings = await Redis.Instance.listJobs(this.jobRedisPrefix, state, 'alpha', sort, start, count)
96 const jobPromises = jobStrings
97 .map(s => s.split('|'))
98 .map(([ , jobId ]) => this.getJob(parseInt(jobId, 10)))
100 return Promise.all(jobPromises)
103 count (state: JobState) {
104 return new Promise<number>((res, rej) => {
105 this.jobQueue[state + 'Count']((err, total) => {
106 if (err) return rej(err)
114 const now = new Date().getTime()
115 kue.Job.rangeByState('complete', 0, -1, 'asc', (err, jobs) => {
117 logger.error('Cannot get jobs when removing old jobs.', { err })
121 for (const job of jobs) {
122 if (now - job.created_at > JOB_COMPLETED_LIFETIME) {
129 private reactiveStuckJobs () {
130 const promises: Promise<any>[] = []
132 this.jobQueue.active((err, ids) => {
135 for (const id of ids) {
136 kue.Job.get(id, (err, job) => {
139 const p = new Promise((res, rej) => {
140 job.inactive(err => {
141 if (err) return rej(err)
151 return Promise.all(promises)
154 private getJob (id: number) {
155 return new Promise<kue.Job>((res, rej) => {
156 kue.Job.get(id, (err, job) => {
157 if (err) return rej(err)
164 static get Instance () {
165 return this.instance || (this.instance = new this())
169 // ---------------------------------------------------------------------------