1 import Bull, { Job, JobOptions, Queue } 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 MoveObjectStoragePayload,
16 VideoFileImportPayload,
18 VideoLiveEndingPayload,
19 VideoRedundancyPayload,
20 VideoTranscodingPayload
21 } from '../../../shared/models'
22 import { logger } from '../../helpers/logger'
23 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
24 import { Redis } from '../redis'
25 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
26 import { processActivityPubFollow } from './handlers/activitypub-follow'
27 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
28 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
29 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
30 import { refreshAPObject } from './handlers/activitypub-refresher'
31 import { processActorKeys } from './handlers/actor-keys'
32 import { processEmail } from './handlers/email'
33 import { processMoveToObjectStorage } from './handlers/move-to-object-storage'
34 import { processVideoFileImport } from './handlers/video-file-import'
35 import { processVideoImport } from './handlers/video-import'
36 import { processVideoLiveEnding } from './handlers/video-live-ending'
37 import { processVideoTranscoding } from './handlers/video-transcoding'
38 import { processVideosViews } from './handlers/video-views'
40 type CreateJobArgument =
41 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
42 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
43 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
44 { type: 'activitypub-http-cleaner', payload: {} } |
45 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
46 { type: 'video-file-import', payload: VideoFileImportPayload } |
47 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
48 { type: 'email', payload: EmailPayload } |
49 { type: 'video-import', payload: VideoImportPayload } |
50 { type: 'activitypub-refresher', payload: RefreshPayload } |
51 { type: 'videos-views', payload: {} } |
52 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
53 { type: 'actor-keys', payload: ActorKeysPayload } |
54 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
55 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
57 export type CreateJobOptions = {
62 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
63 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
64 'activitypub-http-unicast': processActivityPubHttpUnicast,
65 'activitypub-http-fetcher': processActivityPubHttpFetcher,
66 'activitypub-cleaner': processActivityPubCleaner,
67 'activitypub-follow': processActivityPubFollow,
68 'video-file-import': processVideoFileImport,
69 'video-transcoding': processVideoTranscoding,
70 'email': processEmail,
71 'video-import': processVideoImport,
72 'videos-views': processVideosViews,
73 'activitypub-refresher': refreshAPObject,
74 'video-live-ending': processVideoLiveEnding,
75 'actor-keys': processActorKeys,
76 'video-redundancy': processVideoRedundancy,
77 'move-to-object-storage': processMoveToObjectStorage
80 const jobTypes: JobType[] = [
82 'activitypub-http-broadcast',
83 'activitypub-http-fetcher',
84 'activitypub-http-unicast',
85 'activitypub-cleaner',
91 'activitypub-refresher',
95 'move-to-object-storage'
100 private static instance: JobQueue
102 private queues: { [id in JobType]?: Queue } = {}
103 private initialized = false
104 private jobRedisPrefix: string
106 private constructor () {
110 // Already initialized
111 if (this.initialized === true) return
112 this.initialized = true
114 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
115 const queueOptions = {
116 prefix: this.jobRedisPrefix,
117 redis: Redis.getRedisClientOptions(),
119 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
123 for (const handlerName of (Object.keys(handlers) as JobType[])) {
124 const queue = new Bull(handlerName, queueOptions)
125 const handler = handlers[handlerName]
127 queue.process(this.getJobConcurrency(handlerName), handler)
128 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
130 queue.on('failed', (job, err) => {
131 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
134 queue.on('error', err => {
135 logger.error('Error in job queue %s.', handlerName, { err })
138 this.queues[handlerName] = queue
141 this.addRepeatableJobs()
145 for (const queueName of Object.keys(this.queues)) {
146 const queue = this.queues[queueName]
151 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
152 this.createJobWithPromise(obj, options)
153 .catch(err => logger.error('Cannot create job.', { err, obj }))
156 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
157 const queue = this.queues[obj.type]
158 if (queue === undefined) {
159 logger.error('Unknown queue %s: cannot create job.', obj.type)
163 const jobArgs: JobOptions = {
164 backoff: { delay: 60 * 1000, type: 'exponential' },
165 attempts: JOB_ATTEMPTS[obj.type],
166 timeout: JOB_TTL[obj.type],
167 priority: options.priority,
171 return queue.add(obj.payload, jobArgs)
174 async listForApi (options: {
181 const { state, start, count, asc, jobType } = options
183 const states = state ? [ state ] : jobStates
184 let results: Job[] = []
186 const filteredJobTypes = this.filterJobTypes(jobType)
188 for (const jobType of filteredJobTypes) {
189 const queue = this.queues[jobType]
190 if (queue === undefined) {
191 logger.error('Unknown queue %s to list jobs.', jobType)
195 const jobs = await queue.getJobs(states, 0, start + count, asc)
196 results = results.concat(jobs)
199 results.sort((j1: any, j2: any) => {
200 if (j1.timestamp < j2.timestamp) return -1
201 else if (j1.timestamp === j2.timestamp) return 0
206 if (asc === false) results.reverse()
208 return results.slice(start, start + count)
211 async count (state: JobState, jobType?: JobType): Promise<number> {
212 const states = state ? [ state ] : jobStates
215 const filteredJobTypes = this.filterJobTypes(jobType)
217 for (const type of filteredJobTypes) {
218 const queue = this.queues[type]
219 if (queue === undefined) {
220 logger.error('Unknown queue %s to count jobs.', type)
224 const counts = await queue.getJobCounts()
226 for (const s of states) {
234 async removeOldJobs () {
235 for (const key of Object.keys(this.queues)) {
236 const queue = this.queues[key]
237 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
241 private addRepeatableJobs () {
242 this.queues['videos-views'].add({}, {
243 repeat: REPEAT_JOBS['videos-views']
244 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
246 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
247 this.queues['activitypub-cleaner'].add({}, {
248 repeat: REPEAT_JOBS['activitypub-cleaner']
249 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
253 private filterJobTypes (jobType?: JobType) {
254 if (!jobType) return jobTypes
256 return jobTypes.filter(t => t === jobType)
259 private getJobConcurrency (jobType: JobType) {
260 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
261 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
263 return JOB_CONCURRENCY[jobType]
266 static get Instance () {
267 return this.instance || (this.instance = new this())
271 // ---------------------------------------------------------------------------