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 { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
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 { processVideoTranscoding, VideoTranscodingPayload } from './handlers/video-transcoding'
11 import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
12 import { processVideoImport, VideoImportPayload } from './handlers/video-import'
13 import { processVideosViews } from './handlers/video-views'
14 import { refreshAPObject, RefreshPayload } from './handlers/activitypub-refresher'
15 import { processVideoFileImport, VideoFileImportPayload } from './handlers/video-file-import'
17 type CreateJobArgument =
18 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
19 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
20 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
21 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
22 { type: 'video-file-import', payload: VideoFileImportPayload } |
23 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
24 { type: 'email', payload: EmailPayload } |
25 { type: 'video-import', payload: VideoImportPayload } |
26 { type: 'activitypub-refresher', payload: RefreshPayload } |
27 { type: 'videos-views', payload: {} }
29 const handlers: { [ id in (JobType | 'video-file') ]: (job: Bull.Job) => Promise<any>} = {
30 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
31 'activitypub-http-unicast': processActivityPubHttpUnicast,
32 'activitypub-http-fetcher': processActivityPubHttpFetcher,
33 'activitypub-follow': processActivityPubFollow,
34 'video-file-import': processVideoFileImport,
35 'video-transcoding': processVideoTranscoding,
36 'video-file': processVideoTranscoding, // TODO: remove it (changed in 1.3)
37 'email': processEmail,
38 'video-import': processVideoImport,
39 'videos-views': processVideosViews,
40 'activitypub-refresher': refreshAPObject
43 const jobTypes: JobType[] = [
45 'activitypub-http-broadcast',
46 'activitypub-http-fetcher',
47 'activitypub-http-unicast',
53 'activitypub-refresher'
58 private static instance: JobQueue
60 private queues: { [ id in JobType ]?: Bull.Queue } = {}
61 private initialized = false
62 private jobRedisPrefix: string
64 private constructor () {}
67 // Already initialized
68 if (this.initialized === true) return
69 this.initialized = true
71 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
72 const queueOptions = {
73 prefix: this.jobRedisPrefix,
74 redis: Redis.getRedisClientOptions(),
76 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
80 for (const handlerName of Object.keys(handlers)) {
81 const queue = new Bull(handlerName, queueOptions)
82 const handler = handlers[handlerName]
84 queue.process(JOB_CONCURRENCY[handlerName], handler)
85 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
87 queue.on('failed', (job, err) => {
88 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
91 queue.on('error', err => {
92 logger.error('Error in job queue %s.', handlerName, { err })
95 this.queues[handlerName] = queue
98 this.addRepeatableJobs()
102 for (const queueName of Object.keys(this.queues)) {
103 const queue = this.queues[queueName]
108 createJob (obj: CreateJobArgument) {
109 const queue = this.queues[obj.type]
110 if (queue === undefined) {
111 logger.error('Unknown queue %s: cannot create job.', obj.type)
112 throw Error('Unknown queue, cannot create job')
115 const jobArgs: Bull.JobOptions = {
116 backoff: { delay: 60 * 1000, type: 'exponential' },
117 attempts: JOB_ATTEMPTS[obj.type],
118 timeout: JOB_TTL[obj.type]
121 return queue.add(obj.payload, jobArgs)
124 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
125 let results: Bull.Job[] = []
128 for (const jobType of jobTypes) {
129 const queue = this.queues[ jobType ]
130 if (queue === undefined) {
131 logger.error('Unknown queue %s to list jobs.', jobType)
135 // FIXME: Bull queue typings does not have getJobs method
136 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
137 results = results.concat(jobs)
140 results.sort((j1: any, j2: any) => {
141 if (j1.timestamp < j2.timestamp) return -1
142 else if (j1.timestamp === j2.timestamp) return 0
147 if (asc === false) results.reverse()
149 return results.slice(start, start + count)
152 async count (state: JobState): Promise<number> {
155 for (const type of jobTypes) {
156 const queue = this.queues[ type ]
157 if (queue === undefined) {
158 logger.error('Unknown queue %s to count jobs.', type)
162 const counts = await queue.getJobCounts()
164 total += counts[ state ]
170 async removeOldJobs () {
171 for (const key of Object.keys(this.queues)) {
172 const queue = this.queues[key]
173 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
177 private addRepeatableJobs () {
178 this.queues['videos-views'].add({}, {
179 repeat: REPEAT_JOBS['videos-views']
183 static get Instance () {
184 return this.instance || (this.instance = new this())
188 // ---------------------------------------------------------------------------