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'
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 jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
36 'activitypub-http-broadcast': true,
37 'activitypub-http-unicast': true,
38 'activitypub-http-fetcher': true,
39 'activitypub-follow': true
42 const jobTypes: JobType[] = [
44 'activitypub-http-broadcast',
45 'activitypub-http-fetcher',
46 'activitypub-http-unicast',
55 private static instance: JobQueue
57 private queues: { [ id in JobType ]?: Bull.Queue } = {}
58 private initialized = false
59 private jobRedisPrefix: string
61 private constructor () {}
64 // Already initialized
65 if (this.initialized === true) return
66 this.initialized = true
68 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
69 const queueOptions = {
70 prefix: this.jobRedisPrefix,
71 redis: Redis.getRedisClient(),
73 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
77 for (const handlerName of Object.keys(handlers)) {
78 const queue = new Bull(handlerName, queueOptions)
79 const handler = handlers[handlerName]
81 queue.process(JOB_CONCURRENCY[handlerName], handler)
83 queue.on('failed', (job, err) => {
84 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
87 queue.on('error', err => {
88 logger.error('Error in job queue %s.', handlerName, { err })
92 this.queues[handlerName] = queue
97 for (const queueName of Object.keys(this.queues)) {
98 const queue = this.queues[queueName]
103 createJob (obj: CreateJobArgument) {
104 const queue = this.queues[obj.type]
105 if (queue === undefined) {
106 logger.error('Unknown queue %s: cannot create job.', obj.type)
107 throw Error('Unknown queue, cannot create job')
110 const jobArgs: Bull.JobOptions = {
111 backoff: { delay: 60 * 1000, type: 'exponential' },
112 attempts: JOB_ATTEMPTS[obj.type]
115 if (jobsWithRequestTimeout[obj.type] === true) {
116 jobArgs.timeout = JOB_REQUEST_TTL
119 return queue.add(obj.payload, jobArgs)
122 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
123 let results: Bull.Job[] = []
126 for (const jobType of jobTypes) {
127 const queue = this.queues[ jobType ]
128 if (queue === undefined) {
129 logger.error('Unknown queue %s to list jobs.', jobType)
133 // FIXME: Bull queue typings does not have getJobs method
134 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
135 results = results.concat(jobs)
138 results.sort((j1: any, j2: any) => {
139 if (j1.timestamp < j2.timestamp) return -1
140 else if (j1.timestamp === j2.timestamp) return 0
145 if (asc === false) results.reverse()
147 return results.slice(start, start + count)
150 async count (state: JobState): Promise<number> {
153 for (const type of jobTypes) {
154 const queue = this.queues[ type ]
155 if (queue === undefined) {
156 logger.error('Unknown queue %s to count jobs.', type)
160 const counts = await queue.getJobCounts()
162 total += counts[ state ]
169 for (const key of Object.keys(this.queues)) {
170 const queue = this.queues[key]
171 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
175 static get Instance () {
176 return this.instance || (this.instance = new this())
180 // ---------------------------------------------------------------------------