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 { processVideosViews } from './handlers/video-views'
14 import { refreshAPObject, RefreshPayload } from './handlers/activitypub-refresher'
16 type CreateJobArgument =
17 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
18 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
19 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
20 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
21 { type: 'video-file-import', payload: VideoFileImportPayload } |
22 { type: 'video-file', payload: VideoFilePayload } |
23 { type: 'email', payload: EmailPayload } |
24 { type: 'video-import', payload: VideoImportPayload } |
25 { type: 'activitypub-refresher', payload: RefreshPayload } |
26 { type: 'videos-views', payload: {} }
28 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
29 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
30 'activitypub-http-unicast': processActivityPubHttpUnicast,
31 'activitypub-http-fetcher': processActivityPubHttpFetcher,
32 'activitypub-follow': processActivityPubFollow,
33 'video-file-import': processVideoFileImport,
34 'video-file': processVideoFile,
35 'email': processEmail,
36 'video-import': processVideoImport,
37 'videos-views': processVideosViews,
38 'activitypub-refresher': refreshAPObject
41 const jobTypes: JobType[] = [
43 'activitypub-http-broadcast',
44 'activitypub-http-fetcher',
45 'activitypub-http-unicast',
51 'activitypub-refresher'
56 private static instance: JobQueue
58 private queues: { [ id in JobType ]?: Bull.Queue } = {}
59 private initialized = false
60 private jobRedisPrefix: string
62 private constructor () {}
65 // Already initialized
66 if (this.initialized === true) return
67 this.initialized = true
69 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
70 const queueOptions = {
71 prefix: this.jobRedisPrefix,
72 redis: Redis.getRedisClient(),
74 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
78 for (const handlerName of Object.keys(handlers)) {
79 const queue = new Bull(handlerName, queueOptions)
80 const handler = handlers[handlerName]
82 queue.process(JOB_CONCURRENCY[handlerName], handler)
83 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
85 queue.on('failed', (job, err) => {
86 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
89 queue.on('error', err => {
90 logger.error('Error in job queue %s.', handlerName, { err })
93 this.queues[handlerName] = queue
96 this.addRepeatableJobs()
100 for (const queueName of Object.keys(this.queues)) {
101 const queue = this.queues[queueName]
106 createJob (obj: CreateJobArgument) {
107 const queue = this.queues[obj.type]
108 if (queue === undefined) {
109 logger.error('Unknown queue %s: cannot create job.', obj.type)
110 throw Error('Unknown queue, cannot create job')
113 const jobArgs: Bull.JobOptions = {
114 backoff: { delay: 60 * 1000, type: 'exponential' },
115 attempts: JOB_ATTEMPTS[obj.type],
116 timeout: JOB_TTL[obj.type]
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 ]
168 async removeOldJobs () {
169 for (const key of Object.keys(this.queues)) {
170 const queue = this.queues[key]
171 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
175 private addRepeatableJobs () {
176 this.queues['videos-views'].add({}, {
177 repeat: REPEAT_JOBS['videos-views']
181 static get Instance () {
182 return this.instance || (this.instance = new this())
186 // ---------------------------------------------------------------------------