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'
67 export type CreateJobArgument =
68 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
69 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
70 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
71 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
72 { type: 'activitypub-http-cleaner', payload: {} } |
73 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
74 { type: 'video-file-import', payload: VideoFileImportPayload } |
75 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
76 { type: 'email', payload: EmailPayload } |
77 { type: 'video-import', payload: VideoImportPayload } |
78 { type: 'activitypub-refresher', payload: RefreshPayload } |
79 { type: 'videos-views-stats', payload: {} } |
80 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
81 { type: 'actor-keys', payload: ActorKeysPayload } |
82 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
83 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
84 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
85 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
86 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
87 { type: 'video-channel-import', payload: VideoChannelImportPayload } |
88 { type: 'after-video-channel-import', payload: AfterVideoChannelImportPayload } |
89 { type: 'notify', payload: NotifyPayload } |
90 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
91 { type: 'federate-video', payload: FederateVideoPayload }
93 export type CreateJobOptions = {
98 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
99 'activitypub-http-broadcast': processActivityPubHttpSequentialBroadcast,
100 'activitypub-http-broadcast-parallel': processActivityPubParallelHttpBroadcast,
101 'activitypub-http-unicast': processActivityPubHttpUnicast,
102 'activitypub-http-fetcher': processActivityPubHttpFetcher,
103 'activitypub-cleaner': processActivityPubCleaner,
104 'activitypub-follow': processActivityPubFollow,
105 'video-file-import': processVideoFileImport,
106 'video-transcoding': processVideoTranscoding,
107 'email': processEmail,
108 'video-import': processVideoImport,
109 'videos-views-stats': processVideosViewsStats,
110 'activitypub-refresher': refreshAPObject,
111 'video-live-ending': processVideoLiveEnding,
112 'actor-keys': processActorKeys,
113 'video-redundancy': processVideoRedundancy,
114 'move-to-object-storage': processMoveToObjectStorage,
115 'manage-video-torrent': processManageVideoTorrent,
116 'video-studio-edition': processVideoStudioEdition,
117 'video-channel-import': processVideoChannelImport,
118 'after-video-channel-import': processAfterVideoChannelImport,
119 'notify': processNotify,
120 'federate-video': processFederateVideo
123 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
124 'move-to-object-storage': onMoveToObjectStorageFailure
127 const jobTypes: JobType[] = [
128 'activitypub-follow',
129 'activitypub-http-broadcast',
130 'activitypub-http-broadcast-parallel',
131 'activitypub-http-fetcher',
132 'activitypub-http-unicast',
133 'activitypub-cleaner',
138 'videos-views-stats',
139 'activitypub-refresher',
143 'move-to-object-storage',
144 'manage-video-torrent',
145 'video-studio-edition',
146 'video-channel-import',
147 'after-video-channel-import',
152 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
156 private static instance: JobQueue
158 private workers: { [id in JobType]?: Worker } = {}
159 private queues: { [id in JobType]?: Queue } = {}
160 private queueSchedulers: { [id in JobType]?: QueueScheduler } = {}
161 private queueEvents: { [id in JobType]?: QueueEvents } = {}
163 private flowProducer: FlowProducer
165 private initialized = false
166 private jobRedisPrefix: string
168 private constructor () {
172 // Already initialized
173 if (this.initialized === true) return
174 this.initialized = true
176 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
178 for (const handlerName of (Object.keys(handlers) as JobType[])) {
179 this.buildWorker(handlerName)
180 this.buildQueue(handlerName)
181 this.buildQueueScheduler(handlerName)
182 this.buildQueueEvent(handlerName)
185 this.flowProducer = new FlowProducer({
186 connection: this.getRedisConnection(),
187 prefix: this.jobRedisPrefix
189 this.flowProducer.on('error', err => { logger.error('Error in flow producer', { err }) })
191 this.addRepeatableJobs()
194 private buildWorker (handlerName: JobType) {
195 const workerOptions: WorkerOptions = {
197 concurrency: this.getJobConcurrency(handlerName),
198 prefix: this.jobRedisPrefix,
199 connection: this.getRedisConnection()
202 const handler = function (job: Job) {
203 const timeout = JOB_TTL[handlerName]
204 const p = handlers[handlerName](job)
206 if (!timeout) return p
208 return timeoutPromise(p, timeout)
211 const processor = async (jobArg: Job<any>) => {
212 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
214 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
217 const worker = new Worker(handlerName, processor, workerOptions)
219 worker.on('failed', (job, err) => {
220 const logLevel = silentFailure.has(handlerName)
224 logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
226 if (errorHandlers[job.name]) {
227 errorHandlers[job.name](job, err)
228 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
232 worker.on('error', err => { logger.error('Error in job worker %s.', handlerName, { err }) })
234 this.workers[handlerName] = worker
237 private buildQueue (handlerName: JobType) {
238 const queueOptions: QueueOptions = {
239 connection: this.getRedisConnection(),
240 prefix: this.jobRedisPrefix
243 const queue = new Queue(handlerName, queueOptions)
244 queue.on('error', err => { logger.error('Error in job queue %s.', handlerName, { err }) })
246 this.queues[handlerName] = queue
249 private buildQueueScheduler (handlerName: JobType) {
250 const queueSchedulerOptions: QueueSchedulerOptions = {
252 connection: this.getRedisConnection(),
253 prefix: this.jobRedisPrefix,
257 const queueScheduler = new QueueScheduler(handlerName, queueSchedulerOptions)
258 queueScheduler.on('error', err => { logger.error('Error in job queue scheduler %s.', handlerName, { err }) })
260 this.queueSchedulers[handlerName] = queueScheduler
263 private buildQueueEvent (handlerName: JobType) {
264 const queueEventsOptions: QueueEventsOptions = {
266 connection: this.getRedisConnection(),
267 prefix: this.jobRedisPrefix
270 const queueEvents = new QueueEvents(handlerName, queueEventsOptions)
271 queueEvents.on('error', err => { logger.error('Error in job queue events %s.', handlerName, { err }) })
273 this.queueEvents[handlerName] = queueEvents
276 private getRedisConnection () {
278 password: CONFIG.REDIS.AUTH,
280 host: CONFIG.REDIS.HOSTNAME,
281 port: CONFIG.REDIS.PORT,
282 path: CONFIG.REDIS.SOCKET
286 // ---------------------------------------------------------------------------
289 const promises = Object.keys(this.workers)
290 .map(handlerName => {
291 const worker: Worker = this.workers[handlerName]
292 const queue: Queue = this.queues[handlerName]
293 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
294 const queueEvent: QueueEvents = this.queueEvents[handlerName]
299 queueScheduler.close(),
304 return Promise.all(promises)
308 const promises = Object.keys(this.workers)
309 .map(handlerName => {
310 const worker: Worker = this.workers[handlerName]
311 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
312 const queueEvent: QueueEvents = this.queueEvents[handlerName]
316 queueScheduler.run(),
321 return Promise.all(promises)
325 for (const handlerName of Object.keys(this.workers)) {
326 const worker: Worker = this.workers[handlerName]
333 for (const handlerName of Object.keys(this.workers)) {
334 const worker: Worker = this.workers[handlerName]
340 // ---------------------------------------------------------------------------
342 createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
343 this.createJob(options)
344 .catch(err => logger.error('Cannot create job.', { err, options }))
347 createJob (options: CreateJobArgument & CreateJobOptions) {
348 const queue: Queue = this.queues[options.type]
349 if (queue === undefined) {
350 logger.error('Unknown queue %s: cannot create job.', options.type)
354 const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
356 return queue.add('job', options.payload, jobOptions)
359 createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
362 for (const job of jobs) {
366 ...this.buildJobFlowOption(job),
374 return this.flowProducer.add(lastJob)
377 createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) {
378 return this.flowProducer.add({
379 ...this.buildJobFlowOption(parent),
381 children: children.map(c => this.buildJobFlowOption(c))
385 private buildJobFlowOption (job: CreateJobArgument & CreateJobOptions) {
390 opts: this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay' ]))
394 private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
396 backoff: { delay: 60 * 1000, type: 'exponential' },
397 attempts: JOB_ATTEMPTS[type],
398 priority: options.priority,
403 // ---------------------------------------------------------------------------
405 async listForApi (options: {
412 const { state, start, count, asc, jobType } = options
414 const states = this.buildStateFilter(state)
415 const filteredJobTypes = this.buildTypeFilter(jobType)
417 let results: Job[] = []
419 for (const jobType of filteredJobTypes) {
420 const queue: Queue = this.queues[jobType]
422 if (queue === undefined) {
423 logger.error('Unknown queue %s to list jobs.', jobType)
427 const jobs = await queue.getJobs(states, 0, start + count, asc)
428 results = results.concat(jobs)
431 results.sort((j1: any, j2: any) => {
432 if (j1.timestamp < j2.timestamp) return -1
433 else if (j1.timestamp === j2.timestamp) return 0
438 if (asc === false) results.reverse()
440 return results.slice(start, start + count)
443 async count (state: JobState, jobType?: JobType): Promise<number> {
444 const states = state ? [ state ] : jobStates
445 const filteredJobTypes = this.buildTypeFilter(jobType)
449 for (const type of filteredJobTypes) {
450 const queue = this.queues[type]
451 if (queue === undefined) {
452 logger.error('Unknown queue %s to count jobs.', type)
456 const counts = await queue.getJobCounts()
458 for (const s of states) {
466 private buildStateFilter (state?: JobState) {
467 if (!state) return jobStates
469 const states = [ state ]
471 // Include parent if filtering on waiting
472 if (state === 'waiting') states.push('waiting-children')
477 private buildTypeFilter (jobType?: JobType) {
478 if (!jobType) return jobTypes
480 return jobTypes.filter(t => t === jobType)
484 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
486 return Promise.all(promises)
489 // ---------------------------------------------------------------------------
491 async removeOldJobs () {
492 for (const key of Object.keys(this.queues)) {
493 const queue: Queue = this.queues[key]
494 await queue.clean(JOB_COMPLETED_LIFETIME, 100, 'completed')
498 private addRepeatableJobs () {
499 this.queues['videos-views-stats'].add('job', {}, {
500 repeat: REPEAT_JOBS['videos-views-stats']
501 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
503 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
504 this.queues['activitypub-cleaner'].add('job', {}, {
505 repeat: REPEAT_JOBS['activitypub-cleaner']
506 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
510 private getJobConcurrency (jobType: JobType) {
511 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
512 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
514 return JOB_CONCURRENCY[jobType]
517 static get Instance () {
518 return this.instance || (this.instance = new this())
522 // ---------------------------------------------------------------------------