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, REPEAT_JOBS } 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'
13 import { processVideosViewsViews } from './handlers/video-views'
15 type CreateJobArgument =
16 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
17 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
18 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
19 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
20 { type: 'video-file-import', payload: VideoFileImportPayload } |
21 { type: 'video-file', payload: VideoFilePayload } |
22 { type: 'email', payload: EmailPayload } |
23 { type: 'video-import', payload: VideoImportPayload } |
24 { type: 'videos-views', payload: {} }
26 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
27 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
28 'activitypub-http-unicast': processActivityPubHttpUnicast,
29 'activitypub-http-fetcher': processActivityPubHttpFetcher,
30 'activitypub-follow': processActivityPubFollow,
31 'video-file-import': processVideoFileImport,
32 'video-file': processVideoFile,
33 'email': processEmail,
34 'video-import': processVideoImport,
35 'videos-views': processVideosViewsViews
38 const jobTypes: JobType[] = [
40 'activitypub-http-broadcast',
41 'activitypub-http-fetcher',
42 'activitypub-http-unicast',
52 private static instance: JobQueue
54 private queues: { [ id in JobType ]?: Bull.Queue } = {}
55 private initialized = false
56 private jobRedisPrefix: string
58 private constructor () {}
61 // Already initialized
62 if (this.initialized === true) return
63 this.initialized = true
65 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
66 const queueOptions = {
67 prefix: this.jobRedisPrefix,
68 redis: Redis.getRedisClient(),
70 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
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('Error in job queue processor %s.', handlerName, { err }))
81 queue.on('failed', (job, err) => {
82 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
85 queue.on('error', err => {
86 logger.error('Error in job queue %s.', handlerName, { err })
90 this.queues[handlerName] = queue
93 this.addRepeatableJobs()
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],
113 timeout: JOB_TTL[obj.type]
116 return queue.add(obj.payload, jobArgs)
119 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
120 let results: Bull.Job[] = []
123 for (const jobType of jobTypes) {
124 const queue = this.queues[ jobType ]
125 if (queue === undefined) {
126 logger.error('Unknown queue %s to list jobs.', jobType)
130 // FIXME: Bull queue typings does not have getJobs method
131 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
132 results = results.concat(jobs)
135 results.sort((j1: any, j2: any) => {
136 if (j1.timestamp < j2.timestamp) return -1
137 else if (j1.timestamp === j2.timestamp) return 0
142 if (asc === false) results.reverse()
144 return results.slice(start, start + count)
147 async count (state: JobState): Promise<number> {
150 for (const type of jobTypes) {
151 const queue = this.queues[ type ]
152 if (queue === undefined) {
153 logger.error('Unknown queue %s to count jobs.', type)
157 const counts = await queue.getJobCounts()
159 total += counts[ state ]
166 for (const key of Object.keys(this.queues)) {
167 const queue = this.queues[key]
168 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
172 private addRepeatableJobs () {
173 this.queues['videos-views'].add({}, {
174 repeat: REPEAT_JOBS['videos-views']
178 static get Instance () {
179 return this.instance || (this.instance = new this())
183 // ---------------------------------------------------------------------------