11 QueueSchedulerOptions,
15 import { jobStates } from '@server/helpers/custom-validators/jobs'
16 import { CONFIG } from '@server/initializers/config'
17 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
18 import { pick, timeoutPromise } from '@shared/core-utils'
20 ActivitypubFollowPayload,
21 ActivitypubHttpBroadcastPayload,
22 ActivitypubHttpFetcherPayload,
23 ActivitypubHttpUnicastPayload,
25 AfterVideoChannelImportPayload,
26 DeleteResumableUploadMetaFilePayload,
31 ManageVideoTorrentPayload,
32 MoveObjectStoragePayload,
35 VideoChannelImportPayload,
36 VideoFileImportPayload,
38 VideoLiveEndingPayload,
39 VideoRedundancyPayload,
40 VideoStudioEditionPayload,
41 VideoTranscodingPayload
42 } from '../../../shared/models'
43 import { logger } from '../../helpers/logger'
44 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
45 import { Hooks } from '../plugins/hooks'
46 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
47 import { processActivityPubFollow } from './handlers/activitypub-follow'
48 import { processActivityPubHttpSequentialBroadcast, processActivityPubParallelHttpBroadcast } from './handlers/activitypub-http-broadcast'
49 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
50 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
51 import { refreshAPObject } from './handlers/activitypub-refresher'
52 import { processActorKeys } from './handlers/actor-keys'
53 import { processAfterVideoChannelImport } from './handlers/after-video-channel-import'
54 import { processEmail } from './handlers/email'
55 import { processFederateVideo } from './handlers/federate-video'
56 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
57 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
58 import { processNotify } from './handlers/notify'
59 import { processVideoChannelImport } from './handlers/video-channel-import'
60 import { processVideoFileImport } from './handlers/video-file-import'
61 import { processVideoImport } from './handlers/video-import'
62 import { processVideoLiveEnding } from './handlers/video-live-ending'
63 import { processVideoStudioEdition } from './handlers/video-studio-edition'
64 import { processVideoTranscoding } from './handlers/video-transcoding'
65 import { processVideosViewsStats } from './handlers/video-views-stats'
66 import { Redis } from '../redis'
68 export type CreateJobArgument =
69 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
70 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
71 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
72 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
73 { type: 'activitypub-http-cleaner', payload: {} } |
74 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
75 { type: 'video-file-import', payload: VideoFileImportPayload } |
76 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
77 { type: 'email', payload: EmailPayload } |
78 { type: 'video-import', payload: VideoImportPayload } |
79 { type: 'activitypub-refresher', payload: RefreshPayload } |
80 { type: 'videos-views-stats', payload: {} } |
81 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
82 { type: 'actor-keys', payload: ActorKeysPayload } |
83 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
84 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
85 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
86 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
87 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
88 { type: 'video-channel-import', payload: VideoChannelImportPayload } |
89 { type: 'after-video-channel-import', payload: AfterVideoChannelImportPayload } |
90 { type: 'notify', payload: NotifyPayload } |
91 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
92 { type: 'federate-video', payload: FederateVideoPayload }
94 export type CreateJobOptions = {
99 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
100 'activitypub-http-broadcast': processActivityPubHttpSequentialBroadcast,
101 'activitypub-http-broadcast-parallel': processActivityPubParallelHttpBroadcast,
102 'activitypub-http-unicast': processActivityPubHttpUnicast,
103 'activitypub-http-fetcher': processActivityPubHttpFetcher,
104 'activitypub-cleaner': processActivityPubCleaner,
105 'activitypub-follow': processActivityPubFollow,
106 'video-file-import': processVideoFileImport,
107 'video-transcoding': processVideoTranscoding,
108 'email': processEmail,
109 'video-import': processVideoImport,
110 'videos-views-stats': processVideosViewsStats,
111 'activitypub-refresher': refreshAPObject,
112 'video-live-ending': processVideoLiveEnding,
113 'actor-keys': processActorKeys,
114 'video-redundancy': processVideoRedundancy,
115 'move-to-object-storage': processMoveToObjectStorage,
116 'manage-video-torrent': processManageVideoTorrent,
117 'video-studio-edition': processVideoStudioEdition,
118 'video-channel-import': processVideoChannelImport,
119 'after-video-channel-import': processAfterVideoChannelImport,
120 'notify': processNotify,
121 'federate-video': processFederateVideo
124 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
125 'move-to-object-storage': onMoveToObjectStorageFailure
128 const jobTypes: JobType[] = [
129 'activitypub-follow',
130 'activitypub-http-broadcast',
131 'activitypub-http-broadcast-parallel',
132 'activitypub-http-fetcher',
133 'activitypub-http-unicast',
134 'activitypub-cleaner',
139 'videos-views-stats',
140 'activitypub-refresher',
144 'move-to-object-storage',
145 'manage-video-torrent',
146 'video-studio-edition',
147 'video-channel-import',
148 'after-video-channel-import',
153 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
157 private static instance: JobQueue
159 private workers: { [id in JobType]?: Worker } = {}
160 private queues: { [id in JobType]?: Queue } = {}
161 private queueSchedulers: { [id in JobType]?: QueueScheduler } = {}
162 private queueEvents: { [id in JobType]?: QueueEvents } = {}
164 private flowProducer: FlowProducer
166 private initialized = false
167 private jobRedisPrefix: string
169 private constructor () {
173 // Already initialized
174 if (this.initialized === true) return
175 this.initialized = true
177 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
179 for (const handlerName of (Object.keys(handlers) as JobType[])) {
180 this.buildWorker(handlerName)
181 this.buildQueue(handlerName)
182 this.buildQueueScheduler(handlerName)
183 this.buildQueueEvent(handlerName)
186 this.flowProducer = new FlowProducer({
187 connection: Redis.getRedisClientOptions('FlowProducer'),
188 prefix: this.jobRedisPrefix
190 this.flowProducer.on('error', err => { logger.error('Error in flow producer', { err }) })
192 this.addRepeatableJobs()
195 private buildWorker (handlerName: JobType) {
196 const workerOptions: WorkerOptions = {
198 concurrency: this.getJobConcurrency(handlerName),
199 prefix: this.jobRedisPrefix,
200 connection: Redis.getRedisClientOptions('Worker')
203 const handler = function (job: Job) {
204 const timeout = JOB_TTL[handlerName]
205 const p = handlers[handlerName](job)
207 if (!timeout) return p
209 return timeoutPromise(p, timeout)
212 const processor = async (jobArg: Job<any>) => {
213 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
215 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
218 const worker = new Worker(handlerName, processor, workerOptions)
220 worker.on('failed', (job, err) => {
221 const logLevel = silentFailure.has(handlerName)
225 logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
227 if (errorHandlers[job.name]) {
228 errorHandlers[job.name](job, err)
229 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
233 worker.on('error', err => { logger.error('Error in job worker %s.', handlerName, { err }) })
235 this.workers[handlerName] = worker
238 private buildQueue (handlerName: JobType) {
239 const queueOptions: QueueOptions = {
240 connection: Redis.getRedisClientOptions('Queue'),
241 prefix: this.jobRedisPrefix
244 const queue = new Queue(handlerName, queueOptions)
245 queue.on('error', err => { logger.error('Error in job queue %s.', handlerName, { err }) })
247 this.queues[handlerName] = queue
250 private buildQueueScheduler (handlerName: JobType) {
251 const queueSchedulerOptions: QueueSchedulerOptions = {
253 connection: Redis.getRedisClientOptions('QueueScheduler'),
254 prefix: this.jobRedisPrefix,
258 const queueScheduler = new QueueScheduler(handlerName, queueSchedulerOptions)
259 queueScheduler.on('error', err => { logger.error('Error in job queue scheduler %s.', handlerName, { err }) })
261 this.queueSchedulers[handlerName] = queueScheduler
264 private buildQueueEvent (handlerName: JobType) {
265 const queueEventsOptions: QueueEventsOptions = {
267 connection: Redis.getRedisClientOptions('QueueEvent'),
268 prefix: this.jobRedisPrefix
271 const queueEvents = new QueueEvents(handlerName, queueEventsOptions)
272 queueEvents.on('error', err => { logger.error('Error in job queue events %s.', handlerName, { err }) })
274 this.queueEvents[handlerName] = queueEvents
277 // ---------------------------------------------------------------------------
280 const promises = Object.keys(this.workers)
281 .map(handlerName => {
282 const worker: Worker = this.workers[handlerName]
283 const queue: Queue = this.queues[handlerName]
284 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
285 const queueEvent: QueueEvents = this.queueEvents[handlerName]
290 queueScheduler.close(),
295 return Promise.all(promises)
299 const promises = Object.keys(this.workers)
300 .map(handlerName => {
301 const worker: Worker = this.workers[handlerName]
302 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
303 const queueEvent: QueueEvents = this.queueEvents[handlerName]
307 queueScheduler.run(),
312 return Promise.all(promises)
316 for (const handlerName of Object.keys(this.workers)) {
317 const worker: Worker = this.workers[handlerName]
324 for (const handlerName of Object.keys(this.workers)) {
325 const worker: Worker = this.workers[handlerName]
331 // ---------------------------------------------------------------------------
333 createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
334 this.createJob(options)
335 .catch(err => logger.error('Cannot create job.', { err, options }))
338 createJob (options: CreateJobArgument & CreateJobOptions) {
339 const queue: Queue = this.queues[options.type]
340 if (queue === undefined) {
341 logger.error('Unknown queue %s: cannot create job.', options.type)
345 const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
347 return queue.add('job', options.payload, jobOptions)
350 createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
353 for (const job of jobs) {
357 ...this.buildJobFlowOption(job),
365 return this.flowProducer.add(lastJob)
368 createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) {
369 return this.flowProducer.add({
370 ...this.buildJobFlowOption(parent),
372 children: children.map(c => this.buildJobFlowOption(c))
376 private buildJobFlowOption (job: CreateJobArgument & CreateJobOptions) {
381 opts: this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay' ]))
385 private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
387 backoff: { delay: 60 * 1000, type: 'exponential' },
388 attempts: JOB_ATTEMPTS[type],
389 priority: options.priority,
394 // ---------------------------------------------------------------------------
396 async listForApi (options: {
403 const { state, start, count, asc, jobType } = options
405 const states = this.buildStateFilter(state)
406 const filteredJobTypes = this.buildTypeFilter(jobType)
408 let results: Job[] = []
410 for (const jobType of filteredJobTypes) {
411 const queue: Queue = this.queues[jobType]
413 if (queue === undefined) {
414 logger.error('Unknown queue %s to list jobs.', jobType)
418 const jobs = await queue.getJobs(states, 0, start + count, asc)
419 results = results.concat(jobs)
422 results.sort((j1: any, j2: any) => {
423 if (j1.timestamp < j2.timestamp) return -1
424 else if (j1.timestamp === j2.timestamp) return 0
429 if (asc === false) results.reverse()
431 return results.slice(start, start + count)
434 async count (state: JobState, jobType?: JobType): Promise<number> {
435 const states = state ? [ state ] : jobStates
436 const filteredJobTypes = this.buildTypeFilter(jobType)
440 for (const type of filteredJobTypes) {
441 const queue = this.queues[type]
442 if (queue === undefined) {
443 logger.error('Unknown queue %s to count jobs.', type)
447 const counts = await queue.getJobCounts()
449 for (const s of states) {
457 private buildStateFilter (state?: JobState) {
458 if (!state) return jobStates
460 const states = [ state ]
462 // Include parent if filtering on waiting
463 if (state === 'waiting') states.push('waiting-children')
468 private buildTypeFilter (jobType?: JobType) {
469 if (!jobType) return jobTypes
471 return jobTypes.filter(t => t === jobType)
475 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
477 return Promise.all(promises)
480 // ---------------------------------------------------------------------------
482 async removeOldJobs () {
483 for (const key of Object.keys(this.queues)) {
484 const queue: Queue = this.queues[key]
485 await queue.clean(JOB_COMPLETED_LIFETIME, 100, 'completed')
489 private addRepeatableJobs () {
490 this.queues['videos-views-stats'].add('job', {}, {
491 repeat: REPEAT_JOBS['videos-views-stats']
492 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
494 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
495 this.queues['activitypub-cleaner'].add('job', {}, {
496 repeat: REPEAT_JOBS['activitypub-cleaner']
497 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
501 private getJobConcurrency (jobType: JobType) {
502 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
503 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
505 return JOB_CONCURRENCY[jobType]
508 static get Instance () {
509 return this.instance || (this.instance = new this())
513 // ---------------------------------------------------------------------------