1 import * as Bull from 'bull'
2 import { JobState, JobType } from '../../../shared/models'
3 import { logger } from '../../helpers/logger'
4 import { Redis } from '../redis'
5 import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
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, processVideoFileImport, VideoFileImportPayload, 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-import', payload: VideoFileImportPayload } |
19 { type: 'video-file', payload: VideoFilePayload } |
20 { type: 'email', payload: EmailPayload }
22 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
23 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
24 'activitypub-http-unicast': processActivityPubHttpUnicast,
25 'activitypub-http-fetcher': processActivityPubHttpFetcher,
26 'activitypub-follow': processActivityPubFollow,
27 'video-file-import': processVideoFileImport,
28 'video-file': processVideoFile,
32 const jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
33 'activitypub-http-broadcast': true,
34 'activitypub-http-unicast': true,
35 'activitypub-http-fetcher': true,
36 'activitypub-follow': true
39 const jobTypes: JobType[] = [
41 'activitypub-http-broadcast',
42 'activitypub-http-fetcher',
43 'activitypub-http-unicast',
51 private static instance: JobQueue
53 private queues: { [ id in JobType ]?: Bull.Queue } = {}
54 private initialized = false
55 private jobRedisPrefix: string
57 private constructor () {}
60 // Already initialized
61 if (this.initialized === true) return
62 this.initialized = true
64 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
65 const queueOptions = {
66 prefix: this.jobRedisPrefix,
67 redis: Redis.getRedisClient()
70 for (const handlerName of Object.keys(handlers)) {
71 const queue = new Bull(handlerName, queueOptions)
72 const handler = handlers[handlerName]
74 queue.process(JOB_CONCURRENCY[handlerName], handler)
75 .catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
77 queue.on('error', err => {
78 logger.error('Error in job queue %s.', handlerName, { err })
82 this.queues[handlerName] = queue
87 for (const queueName of Object.keys(this.queues)) {
88 const queue = this.queues[queueName]
93 createJob (obj: CreateJobArgument) {
94 const queue = this.queues[obj.type]
95 if (queue === undefined) {
96 logger.error('Unknown queue %s: cannot create job.', obj.type)
97 throw Error('Unknown queue, cannot create job')
100 const jobArgs: Bull.JobOptions = {
101 backoff: { delay: 60 * 1000, type: 'exponential' },
102 attempts: JOB_ATTEMPTS[obj.type]
105 if (jobsWithRequestTimeout[obj.type] === true) {
106 jobArgs.timeout = JOB_REQUEST_TTL
109 return queue.add(obj.payload, jobArgs)
112 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
113 let results: Bull.Job[] = []
116 for (const jobType of jobTypes) {
117 const queue = this.queues[ jobType ]
118 if (queue === undefined) {
119 logger.error('Unknown queue %s to list jobs.', jobType)
123 // FIXME: Bull queue typings does not have getJobs method
124 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
125 results = results.concat(jobs)
128 results.sort((j1: any, j2: any) => {
129 if (j1.timestamp < j2.timestamp) return -1
130 else if (j1.timestamp === j2.timestamp) return 0
135 if (asc === false) results.reverse()
137 return results.slice(start, start + count)
140 async count (state: JobState): Promise<number> {
143 for (const type of jobTypes) {
144 const queue = this.queues[ type ]
145 if (queue === undefined) {
146 logger.error('Unknown queue %s to count jobs.', type)
150 const counts = await queue.getJobCounts()
152 total += counts[ state ]
159 for (const key of Object.keys(this.queues)) {
160 const queue = this.queues[key]
161 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
165 static get Instance () {
166 return this.instance || (this.instance = new this())
170 // ---------------------------------------------------------------------------