1 import * as Bull from 'bull'
2 import { JobState, JobType } from '../../../shared/models'
3 import { logger } from '../../helpers/logger'
4 import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
5 import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
6 import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
7 import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
8 import { EmailPayload, processEmail } from './handlers/email'
9 import { processVideoFile, processVideoFileImport, VideoFileImportPayload, VideoFilePayload } from './handlers/video-file'
10 import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
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: 'activitypub-follow', payload: ActivitypubFollowPayload } |
17 { type: 'video-file-import', payload: VideoFileImportPayload } |
18 { type: 'video-file', payload: VideoFilePayload } |
19 { type: 'email', payload: EmailPayload }
21 const handlers: { [ id in JobType ]: (job: Bull.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-import': processVideoFileImport,
27 'video-file': processVideoFile,
31 const jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
32 'activitypub-http-broadcast': true,
33 'activitypub-http-unicast': true,
34 'activitypub-http-fetcher': true,
35 'activitypub-follow': true
38 const jobTypes: JobType[] = [
40 'activitypub-http-broadcast',
41 'activitypub-http-fetcher',
42 'activitypub-http-unicast',
50 private static instance: JobQueue
52 private queues: { [ id in JobType ]?: Bull.Queue } = {}
53 private initialized = false
54 private jobRedisPrefix: string
56 private constructor () {}
59 // Already initialized
60 if (this.initialized === true) return
61 this.initialized = true
63 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
64 const queueOptions = {
65 prefix: this.jobRedisPrefix,
67 host: CONFIG.REDIS.HOSTNAME,
68 port: CONFIG.REDIS.PORT,
69 auth: CONFIG.REDIS.AUTH,
74 for (const handlerName of Object.keys(handlers)) {
75 const queue = new Bull(handlerName, queueOptions)
76 const handler = handlers[handlerName]
78 queue.process(JOB_CONCURRENCY[handlerName], handler)
79 .catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
81 queue.on('error', err => {
82 logger.error('Error in job queue %s.', handlerName, { err })
86 this.queues[handlerName] = queue
90 createJob (obj: CreateJobArgument) {
91 const queue = this.queues[obj.type]
92 if (queue === undefined) {
93 logger.error('Unknown queue %s: cannot create job.', obj.type)
97 const jobArgs: Bull.JobOptions = {
98 backoff: { delay: 60 * 1000, type: 'exponential' },
99 attempts: JOB_ATTEMPTS[obj.type]
102 if (jobsWithRequestTimeout[obj.type] === true) {
103 jobArgs.timeout = JOB_REQUEST_TTL
106 return queue.add(obj.payload, jobArgs)
109 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
110 let results: Bull.Job[] = []
113 for (const jobType of jobTypes) {
114 const queue = this.queues[ jobType ]
115 if (queue === undefined) {
116 logger.error('Unknown queue %s to list jobs.', jobType)
120 // FIXME: Bull queue typings does not have getJobs method
121 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
122 results = results.concat(jobs)
125 results.sort((j1: any, j2: any) => {
126 if (j1.timestamp < j2.timestamp) return -1
127 else if (j1.timestamp === j2.timestamp) return 0
132 if (asc === false) results.reverse()
134 return results.slice(start, start + count)
137 async count (state: JobState): Promise<number> {
140 for (const type of jobTypes) {
141 const queue = this.queues[ type ]
142 if (queue === undefined) {
143 logger.error('Unknown queue %s to count jobs.', type)
147 const counts = await queue.getJobCounts()
149 total += counts[ state ]
156 for (const key of Object.keys(this.queues)) {
157 const queue = this.queues[key]
158 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
162 static get Instance () {
163 return this.instance || (this.instance = new this())
167 // ---------------------------------------------------------------------------