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 DeleteResumableUploadMetaFilePayload,
30 ManageVideoTorrentPayload,
31 MoveObjectStoragePayload,
34 VideoFileImportPayload,
36 VideoLiveEndingPayload,
37 VideoRedundancyPayload,
38 VideoStudioEditionPayload,
39 VideoTranscodingPayload
40 } from '../../../shared/models'
41 import { logger } from '../../helpers/logger'
42 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
43 import { Hooks } from '../plugins/hooks'
44 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
45 import { processActivityPubFollow } from './handlers/activitypub-follow'
46 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
47 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
48 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
49 import { refreshAPObject } from './handlers/activitypub-refresher'
50 import { processActorKeys } from './handlers/actor-keys'
51 import { processEmail } from './handlers/email'
52 import { processFederateVideo } from './handlers/federate-video'
53 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
54 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
55 import { processNotify } from './handlers/notify'
56 import { processVideoFileImport } from './handlers/video-file-import'
57 import { processVideoImport } from './handlers/video-import'
58 import { processVideoLiveEnding } from './handlers/video-live-ending'
59 import { processVideoStudioEdition } from './handlers/video-studio-edition'
60 import { processVideoTranscoding } from './handlers/video-transcoding'
61 import { processVideosViewsStats } from './handlers/video-views-stats'
63 export type CreateJobArgument =
64 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
65 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
66 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
67 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
68 { type: 'activitypub-http-cleaner', payload: {} } |
69 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
70 { type: 'video-file-import', payload: VideoFileImportPayload } |
71 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
72 { type: 'email', payload: EmailPayload } |
73 { type: 'video-import', payload: VideoImportPayload } |
74 { type: 'activitypub-refresher', payload: RefreshPayload } |
75 { type: 'videos-views-stats', payload: {} } |
76 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
77 { type: 'actor-keys', payload: ActorKeysPayload } |
78 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
79 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
80 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
81 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
82 { type: 'notify', payload: NotifyPayload } |
83 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
84 { type: 'federate-video', payload: FederateVideoPayload }
86 export type CreateJobOptions = {
91 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
92 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
93 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
94 'activitypub-http-unicast': processActivityPubHttpUnicast,
95 'activitypub-http-fetcher': processActivityPubHttpFetcher,
96 'activitypub-cleaner': processActivityPubCleaner,
97 'activitypub-follow': processActivityPubFollow,
98 'video-file-import': processVideoFileImport,
99 'video-transcoding': processVideoTranscoding,
100 'email': processEmail,
101 'video-import': processVideoImport,
102 'videos-views-stats': processVideosViewsStats,
103 'activitypub-refresher': refreshAPObject,
104 'video-live-ending': processVideoLiveEnding,
105 'actor-keys': processActorKeys,
106 'video-redundancy': processVideoRedundancy,
107 'move-to-object-storage': processMoveToObjectStorage,
108 'manage-video-torrent': processManageVideoTorrent,
109 'notify': processNotify,
110 'video-studio-edition': processVideoStudioEdition,
111 'federate-video': processFederateVideo
114 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
115 'move-to-object-storage': onMoveToObjectStorageFailure
118 const jobTypes: JobType[] = [
119 'activitypub-follow',
120 'activitypub-http-broadcast',
121 'activitypub-http-broadcast-parallel',
122 'activitypub-http-fetcher',
123 'activitypub-http-unicast',
124 'activitypub-cleaner',
129 'videos-views-stats',
130 'activitypub-refresher',
134 'move-to-object-storage',
135 'manage-video-torrent',
136 'video-studio-edition',
141 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
145 private static instance: JobQueue
147 private workers: { [id in JobType]?: Worker } = {}
148 private queues: { [id in JobType]?: Queue } = {}
149 private queueSchedulers: { [id in JobType]?: QueueScheduler } = {}
150 private queueEvents: { [id in JobType]?: QueueEvents } = {}
152 private flowProducer: FlowProducer
154 private initialized = false
155 private jobRedisPrefix: string
157 private constructor () {
160 init (produceOnly = false) {
161 // Already initialized
162 if (this.initialized === true) return
163 this.initialized = true
165 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
167 for (const handlerName of (Object.keys(handlers) as JobType[])) {
168 this.buildWorker(handlerName, produceOnly)
169 this.buildQueue(handlerName)
170 this.buildQueueScheduler(handlerName, produceOnly)
171 this.buildQueueEvent(handlerName, produceOnly)
174 this.flowProducer = new FlowProducer({
175 connection: this.getRedisConnection(),
176 prefix: this.jobRedisPrefix
179 this.addRepeatableJobs()
182 private buildWorker (handlerName: JobType, produceOnly: boolean) {
183 const workerOptions: WorkerOptions = {
184 autorun: !produceOnly,
185 concurrency: this.getJobConcurrency(handlerName),
186 prefix: this.jobRedisPrefix,
187 connection: this.getRedisConnection()
190 const handler = function (job: Job) {
191 const timeout = JOB_TTL[handlerName]
192 const p = handlers[handlerName](job)
194 if (!timeout) return p
196 return timeoutPromise(p, timeout)
199 const processor = async (jobArg: Job<any>) => {
200 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
202 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
205 const worker = new Worker(handlerName, processor, workerOptions)
207 worker.on('failed', (job, err) => {
208 const logLevel = silentFailure.has(handlerName)
212 logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
214 if (errorHandlers[job.name]) {
215 errorHandlers[job.name](job, err)
216 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
220 worker.on('error', err => {
221 logger.error('Error in job queue %s.', handlerName, { err })
224 this.workers[handlerName] = worker
227 private buildQueue (handlerName: JobType) {
228 const queueOptions: QueueOptions = {
229 connection: this.getRedisConnection(),
230 prefix: this.jobRedisPrefix
233 this.queues[handlerName] = new Queue(handlerName, queueOptions)
236 private buildQueueScheduler (handlerName: JobType, produceOnly: boolean) {
237 const queueSchedulerOptions: QueueSchedulerOptions = {
238 autorun: !produceOnly,
239 connection: this.getRedisConnection(),
240 prefix: this.jobRedisPrefix,
243 this.queueSchedulers[handlerName] = new QueueScheduler(handlerName, queueSchedulerOptions)
246 private buildQueueEvent (handlerName: JobType, produceOnly: boolean) {
247 const queueEventsOptions: QueueEventsOptions = {
248 autorun: !produceOnly,
249 connection: this.getRedisConnection(),
250 prefix: this.jobRedisPrefix
252 this.queueEvents[handlerName] = new QueueEvents(handlerName, queueEventsOptions)
255 private getRedisConnection () {
257 password: CONFIG.REDIS.AUTH,
259 host: CONFIG.REDIS.HOSTNAME,
260 port: CONFIG.REDIS.PORT,
261 path: CONFIG.REDIS.SOCKET
265 // ---------------------------------------------------------------------------
268 const promises = Object.keys(this.workers)
269 .map(handlerName => {
270 const worker: Worker = this.workers[handlerName]
271 const queue: Queue = this.queues[handlerName]
272 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
273 const queueEvent: QueueEvents = this.queueEvents[handlerName]
278 queueScheduler.close(),
283 return Promise.all(promises)
287 for (const handlerName of Object.keys(this.workers)) {
288 const worker: Worker = this.workers[handlerName]
295 for (const handlerName of Object.keys(this.workers)) {
296 const worker: Worker = this.workers[handlerName]
302 // ---------------------------------------------------------------------------
304 createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
305 this.createJob(options)
306 .catch(err => logger.error('Cannot create job.', { err, options }))
309 async createJob (options: CreateJobArgument & CreateJobOptions) {
310 const queue: Queue = this.queues[options.type]
311 if (queue === undefined) {
312 logger.error('Unknown queue %s: cannot create job.', options.type)
316 const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
318 return queue.add('job', options.payload, jobOptions)
321 async createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
324 for (const job of jobs) {
328 ...this.buildJobFlowOption(job),
336 return this.flowProducer.add(lastJob)
339 async createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) {
340 return this.flowProducer.add({
341 ...this.buildJobFlowOption(parent),
343 children: children.map(c => this.buildJobFlowOption(c))
347 private buildJobFlowOption (job: CreateJobArgument & CreateJobOptions) {
352 opts: this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay' ]))
356 private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
358 backoff: { delay: 60 * 1000, type: 'exponential' },
359 attempts: JOB_ATTEMPTS[type],
360 priority: options.priority,
365 // ---------------------------------------------------------------------------
367 async listForApi (options: {
374 const { state, start, count, asc, jobType } = options
376 const states = this.buildStateFilter(state)
377 const filteredJobTypes = this.buildTypeFilter(jobType)
379 let results: Job[] = []
381 for (const jobType of filteredJobTypes) {
382 const queue: Queue = this.queues[jobType]
384 if (queue === undefined) {
385 logger.error('Unknown queue %s to list jobs.', jobType)
389 const jobs = await queue.getJobs(states, 0, start + count, asc)
390 results = results.concat(jobs)
393 results.sort((j1: any, j2: any) => {
394 if (j1.timestamp < j2.timestamp) return -1
395 else if (j1.timestamp === j2.timestamp) return 0
400 if (asc === false) results.reverse()
402 return results.slice(start, start + count)
405 async count (state: JobState, jobType?: JobType): Promise<number> {
406 const states = state ? [ state ] : jobStates
407 const filteredJobTypes = this.buildTypeFilter(jobType)
411 for (const type of filteredJobTypes) {
412 const queue = this.queues[type]
413 if (queue === undefined) {
414 logger.error('Unknown queue %s to count jobs.', type)
418 const counts = await queue.getJobCounts()
420 for (const s of states) {
428 private buildStateFilter (state?: JobState) {
429 if (!state) return jobStates
431 const states = [ state ]
433 // Include parent if filtering on waiting
434 if (state === 'waiting') states.push('waiting-children')
439 private buildTypeFilter (jobType?: JobType) {
440 if (!jobType) return jobTypes
442 return jobTypes.filter(t => t === jobType)
446 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
448 return Promise.all(promises)
451 // ---------------------------------------------------------------------------
453 async removeOldJobs () {
454 for (const key of Object.keys(this.queues)) {
455 const queue: Queue = this.queues[key]
456 await queue.clean(JOB_COMPLETED_LIFETIME, 100, 'completed')
460 private addRepeatableJobs () {
461 this.queues['videos-views-stats'].add('job', {}, {
462 repeat: REPEAT_JOBS['videos-views-stats']
463 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
465 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
466 this.queues['activitypub-cleaner'].add('job', {}, {
467 repeat: REPEAT_JOBS['activitypub-cleaner']
468 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
472 private getJobConcurrency (jobType: JobType) {
473 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
474 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
476 return JOB_CONCURRENCY[jobType]
479 static get Instance () {
480 return this.instance || (this.instance = new this())
484 // ---------------------------------------------------------------------------