1 import * as Bull from 'bull'
2 import { jobStates } from '@server/helpers/custom-validators/jobs'
3 import { CONFIG } from '@server/initializers/config'
4 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
6 ActivitypubFollowPayload,
7 ActivitypubHttpBroadcastPayload,
8 ActivitypubHttpFetcherPayload,
9 ActivitypubHttpUnicastPayload,
15 VideoFileImportPayload,
17 VideoLiveEndingPayload,
18 VideoRedundancyPayload,
19 VideoTranscodingPayload
20 } from '../../../shared/models'
21 import { logger } from '../../helpers/logger'
22 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
23 import { Redis } from '../redis'
24 import { processActivityPubFollow } from './handlers/activitypub-follow'
25 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
26 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
27 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
28 import { refreshAPObject } from './handlers/activitypub-refresher'
29 import { processActorKeys } from './handlers/actor-keys'
30 import { processEmail } from './handlers/email'
31 import { processVideoFileImport } from './handlers/video-file-import'
32 import { processVideoImport } from './handlers/video-import'
33 import { processVideoLiveEnding } from './handlers/video-live-ending'
34 import { processVideoTranscoding } from './handlers/video-transcoding'
35 import { processVideosViews } from './handlers/video-views'
37 type CreateJobArgument =
38 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
39 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
40 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
41 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
42 { type: 'video-file-import', payload: VideoFileImportPayload } |
43 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
44 { type: 'email', payload: EmailPayload } |
45 { type: 'video-import', payload: VideoImportPayload } |
46 { type: 'activitypub-refresher', payload: RefreshPayload } |
47 { type: 'videos-views', payload: {} } |
48 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
49 { type: 'actor-keys', payload: ActorKeysPayload } |
50 { type: 'video-redundancy', payload: VideoRedundancyPayload }
52 type CreateJobOptions = {
57 const handlers: { [id in JobType]: (job: Bull.Job) => Promise<any> } = {
58 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
59 'activitypub-http-unicast': processActivityPubHttpUnicast,
60 'activitypub-http-fetcher': processActivityPubHttpFetcher,
61 'activitypub-follow': processActivityPubFollow,
62 'video-file-import': processVideoFileImport,
63 'video-transcoding': processVideoTranscoding,
64 'email': processEmail,
65 'video-import': processVideoImport,
66 'videos-views': processVideosViews,
67 'activitypub-refresher': refreshAPObject,
68 'video-live-ending': processVideoLiveEnding,
69 'actor-keys': processActorKeys,
70 'video-redundancy': processVideoRedundancy
73 const jobTypes: JobType[] = [
75 'activitypub-http-broadcast',
76 'activitypub-http-fetcher',
77 'activitypub-http-unicast',
83 'activitypub-refresher',
91 private static instance: JobQueue
93 private queues: { [id in JobType]?: Bull.Queue } = {}
94 private initialized = false
95 private jobRedisPrefix: string
97 private constructor () {
101 // Already initialized
102 if (this.initialized === true) return
103 this.initialized = true
105 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
106 const queueOptions = {
107 prefix: this.jobRedisPrefix,
108 redis: Redis.getRedisClientOptions(),
110 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
114 for (const handlerName of (Object.keys(handlers) as JobType[])) {
115 const queue = new Bull(handlerName, queueOptions)
116 const handler = handlers[handlerName]
118 queue.process(this.getJobConcurrency(handlerName), handler)
119 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
121 queue.on('failed', (job, err) => {
122 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
125 queue.on('error', err => {
126 logger.error('Error in job queue %s.', handlerName, { err })
129 this.queues[handlerName] = queue
132 this.addRepeatableJobs()
136 for (const queueName of Object.keys(this.queues)) {
137 const queue = this.queues[queueName]
142 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
143 this.createJobWithPromise(obj, options)
144 .catch(err => logger.error('Cannot create job.', { err, obj }))
147 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
148 const queue = this.queues[obj.type]
149 if (queue === undefined) {
150 logger.error('Unknown queue %s: cannot create job.', obj.type)
154 const jobArgs: Bull.JobOptions = {
155 backoff: { delay: 60 * 1000, type: 'exponential' },
156 attempts: JOB_ATTEMPTS[obj.type],
157 timeout: JOB_TTL[obj.type],
158 priority: options.priority,
162 return queue.add(obj.payload, jobArgs)
165 async listForApi (options: {
171 }): Promise<Bull.Job[]> {
172 const { state, start, count, asc, jobType } = options
174 const states = state ? [ state ] : jobStates
175 let results: Bull.Job[] = []
177 const filteredJobTypes = this.filterJobTypes(jobType)
179 for (const jobType of filteredJobTypes) {
180 const queue = this.queues[jobType]
181 if (queue === undefined) {
182 logger.error('Unknown queue %s to list jobs.', jobType)
186 const jobs = await queue.getJobs(states, 0, start + count, asc)
187 results = results.concat(jobs)
190 results.sort((j1: any, j2: any) => {
191 if (j1.timestamp < j2.timestamp) return -1
192 else if (j1.timestamp === j2.timestamp) return 0
197 if (asc === false) results.reverse()
199 return results.slice(start, start + count)
202 async count (state: JobState, jobType?: JobType): Promise<number> {
203 const states = state ? [ state ] : jobStates
206 const filteredJobTypes = this.filterJobTypes(jobType)
208 for (const type of filteredJobTypes) {
209 const queue = this.queues[type]
210 if (queue === undefined) {
211 logger.error('Unknown queue %s to count jobs.', type)
215 const counts = await queue.getJobCounts()
217 for (const s of states) {
225 async removeOldJobs () {
226 for (const key of Object.keys(this.queues)) {
227 const queue = this.queues[key]
228 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
232 private addRepeatableJobs () {
233 this.queues['videos-views'].add({}, {
234 repeat: REPEAT_JOBS['videos-views']
235 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
238 private filterJobTypes (jobType?: JobType) {
239 if (!jobType) return jobTypes
241 return jobTypes.filter(t => t === jobType)
244 private getJobConcurrency (jobType: JobType) {
245 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
246 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
248 return JOB_CONCURRENCY[jobType]
251 static get Instance () {
252 return this.instance || (this.instance = new this())
256 // ---------------------------------------------------------------------------