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_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'
12 import { processVideoImport, VideoImportPayload } from './handlers/video-import'
14 type CreateJobArgument =
15 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
16 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
17 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
18 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
19 { type: 'video-file-import', payload: VideoFileImportPayload } |
20 { type: 'video-file', payload: VideoFilePayload } |
21 { type: 'email', payload: EmailPayload } |
22 { type: 'video-import', payload: VideoImportPayload }
24 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
25 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
26 'activitypub-http-unicast': processActivityPubHttpUnicast,
27 'activitypub-http-fetcher': processActivityPubHttpFetcher,
28 'activitypub-follow': processActivityPubFollow,
29 'video-file-import': processVideoFileImport,
30 'video-file': processVideoFile,
31 'email': processEmail,
32 'video-import': processVideoImport
35 const jobTypes: JobType[] = [
37 'activitypub-http-broadcast',
38 'activitypub-http-fetcher',
39 'activitypub-http-unicast',
48 private static instance: JobQueue
50 private queues: { [ id in JobType ]?: Bull.Queue } = {}
51 private initialized = false
52 private jobRedisPrefix: string
54 private constructor () {}
57 // Already initialized
58 if (this.initialized === true) return
59 this.initialized = true
61 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
62 const queueOptions = {
63 prefix: this.jobRedisPrefix,
64 redis: Redis.getRedisClient(),
66 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
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('Error in job queue processor %s.', handlerName, { err }))
77 queue.on('failed', (job, err) => {
78 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
81 queue.on('error', err => {
82 logger.error('Error in job queue %s.', handlerName, { err })
86 this.queues[handlerName] = queue
91 for (const queueName of Object.keys(this.queues)) {
92 const queue = this.queues[queueName]
97 createJob (obj: CreateJobArgument) {
98 const queue = this.queues[obj.type]
99 if (queue === undefined) {
100 logger.error('Unknown queue %s: cannot create job.', obj.type)
101 throw Error('Unknown queue, cannot create job')
104 const jobArgs: Bull.JobOptions = {
105 backoff: { delay: 60 * 1000, type: 'exponential' },
106 attempts: JOB_ATTEMPTS[obj.type],
107 timeout: JOB_TTL[obj.type]
110 return queue.add(obj.payload, jobArgs)
113 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
114 let results: Bull.Job[] = []
117 for (const jobType of jobTypes) {
118 const queue = this.queues[ jobType ]
119 if (queue === undefined) {
120 logger.error('Unknown queue %s to list jobs.', jobType)
124 // FIXME: Bull queue typings does not have getJobs method
125 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
126 results = results.concat(jobs)
129 results.sort((j1: any, j2: any) => {
130 if (j1.timestamp < j2.timestamp) return -1
131 else if (j1.timestamp === j2.timestamp) return 0
136 if (asc === false) results.reverse()
138 return results.slice(start, start + count)
141 async count (state: JobState): Promise<number> {
144 for (const type of jobTypes) {
145 const queue = this.queues[ type ]
146 if (queue === undefined) {
147 logger.error('Unknown queue %s to count jobs.', type)
151 const counts = await queue.getJobCounts()
153 total += counts[ state ]
160 for (const key of Object.keys(this.queues)) {
161 const queue = this.queues[key]
162 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
166 static get Instance () {
167 return this.instance || (this.instance = new this())
171 // ---------------------------------------------------------------------------