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,
14 VideoFileImportPayload,
16 VideoLiveEndingPayload,
17 VideoRedundancyPayload,
18 VideoTranscodingPayload
19 } from '../../../shared/models'
20 import { logger } from '../../helpers/logger'
21 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
22 import { Redis } from '../redis'
23 import { processActivityPubFollow } from './handlers/activitypub-follow'
24 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
25 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
26 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
27 import { refreshAPObject } from './handlers/activitypub-refresher'
28 import { processEmail } from './handlers/email'
29 import { processVideoFileImport } from './handlers/video-file-import'
30 import { processVideoImport } from './handlers/video-import'
31 import { processVideoLiveEnding } from './handlers/video-live-ending'
32 import { processVideoTranscoding } from './handlers/video-transcoding'
33 import { processVideosViews } from './handlers/video-views'
35 type CreateJobArgument =
36 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
37 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
38 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
39 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
40 { type: 'video-file-import', payload: VideoFileImportPayload } |
41 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
42 { type: 'email', payload: EmailPayload } |
43 { type: 'video-import', payload: VideoImportPayload } |
44 { type: 'activitypub-refresher', payload: RefreshPayload } |
45 { type: 'videos-views', payload: {} } |
46 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
47 { type: 'video-redundancy', payload: VideoRedundancyPayload }
49 type CreateJobOptions = {
54 const handlers: { [id in JobType]: (job: Bull.Job) => Promise<any> } = {
55 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
56 'activitypub-http-unicast': processActivityPubHttpUnicast,
57 'activitypub-http-fetcher': processActivityPubHttpFetcher,
58 'activitypub-follow': processActivityPubFollow,
59 'video-file-import': processVideoFileImport,
60 'video-transcoding': processVideoTranscoding,
61 'email': processEmail,
62 'video-import': processVideoImport,
63 'videos-views': processVideosViews,
64 'activitypub-refresher': refreshAPObject,
65 'video-live-ending': processVideoLiveEnding,
66 'video-redundancy': processVideoRedundancy
69 const jobTypes: JobType[] = [
71 'activitypub-http-broadcast',
72 'activitypub-http-fetcher',
73 'activitypub-http-unicast',
79 'activitypub-refresher',
86 private static instance: JobQueue
88 private queues: { [id in JobType]?: Bull.Queue } = {}
89 private initialized = false
90 private jobRedisPrefix: string
92 private constructor () {
96 // Already initialized
97 if (this.initialized === true) return
98 this.initialized = true
100 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
101 const queueOptions = {
102 prefix: this.jobRedisPrefix,
103 redis: Redis.getRedisClientOptions(),
105 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
109 for (const handlerName of (Object.keys(handlers) as JobType[])) {
110 const queue = new Bull(handlerName, queueOptions)
111 const handler = handlers[handlerName]
113 queue.process(this.getJobConcurrency(handlerName), handler)
114 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
116 queue.on('failed', (job, err) => {
117 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
120 queue.on('error', err => {
121 logger.error('Error in job queue %s.', handlerName, { err })
124 this.queues[handlerName] = queue
127 this.addRepeatableJobs()
131 for (const queueName of Object.keys(this.queues)) {
132 const queue = this.queues[queueName]
137 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
138 this.createJobWithPromise(obj, options)
139 .catch(err => logger.error('Cannot create job.', { err, obj }))
142 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
143 const queue = this.queues[obj.type]
144 if (queue === undefined) {
145 logger.error('Unknown queue %s: cannot create job.', obj.type)
149 const jobArgs: Bull.JobOptions = {
150 backoff: { delay: 60 * 1000, type: 'exponential' },
151 attempts: JOB_ATTEMPTS[obj.type],
152 timeout: JOB_TTL[obj.type],
153 priority: options.priority,
157 return queue.add(obj.payload, jobArgs)
160 async listForApi (options: {
166 }): Promise<Bull.Job[]> {
167 const { state, start, count, asc, jobType } = options
169 const states = state ? [ state ] : jobStates
170 let results: Bull.Job[] = []
172 const filteredJobTypes = this.filterJobTypes(jobType)
174 for (const jobType of filteredJobTypes) {
175 const queue = this.queues[jobType]
176 if (queue === undefined) {
177 logger.error('Unknown queue %s to list jobs.', jobType)
181 const jobs = await queue.getJobs(states, 0, start + count, asc)
182 results = results.concat(jobs)
185 results.sort((j1: any, j2: any) => {
186 if (j1.timestamp < j2.timestamp) return -1
187 else if (j1.timestamp === j2.timestamp) return 0
192 if (asc === false) results.reverse()
194 return results.slice(start, start + count)
197 async count (state: JobState, jobType?: JobType): Promise<number> {
198 const states = state ? [ state ] : jobStates
201 const filteredJobTypes = this.filterJobTypes(jobType)
203 for (const type of filteredJobTypes) {
204 const queue = this.queues[type]
205 if (queue === undefined) {
206 logger.error('Unknown queue %s to count jobs.', type)
210 const counts = await queue.getJobCounts()
212 for (const s of states) {
220 async removeOldJobs () {
221 for (const key of Object.keys(this.queues)) {
222 const queue = this.queues[key]
223 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
227 private addRepeatableJobs () {
228 this.queues['videos-views'].add({}, {
229 repeat: REPEAT_JOBS['videos-views']
230 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
233 private filterJobTypes (jobType?: JobType) {
234 if (!jobType) return jobTypes
236 return jobTypes.filter(t => t === jobType)
239 private getJobConcurrency (jobType: JobType) {
240 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
241 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
243 return JOB_CONCURRENCY[jobType]
246 static get Instance () {
247 return this.instance || (this.instance = new this())
251 // ---------------------------------------------------------------------------