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,
11 DeleteResumableUploadMetaFilePayload,
15 ManageVideoTorrentPayload,
16 MoveObjectStoragePayload,
18 VideoFileImportPayload,
20 VideoLiveEndingPayload,
21 VideoRedundancyPayload,
22 VideoStudioEditionPayload,
23 VideoTranscodingPayload
24 } from '../../../shared/models'
25 import { logger } from '../../helpers/logger'
26 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
27 import { Hooks } from '../plugins/hooks'
28 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
29 import { processActivityPubFollow } from './handlers/activitypub-follow'
30 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
31 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
32 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
33 import { refreshAPObject } from './handlers/activitypub-refresher'
34 import { processActorKeys } from './handlers/actor-keys'
35 import { processEmail } from './handlers/email'
36 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
37 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
38 import { processVideoFileImport } from './handlers/video-file-import'
39 import { processVideoImport } from './handlers/video-import'
40 import { processVideoLiveEnding } from './handlers/video-live-ending'
41 import { processVideoStudioEdition } from './handlers/video-studio-edition'
42 import { processVideoTranscoding } from './handlers/video-transcoding'
43 import { processVideosViewsStats } from './handlers/video-views-stats'
45 type CreateJobArgument =
46 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
47 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
48 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
49 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
50 { type: 'activitypub-http-cleaner', payload: {} } |
51 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
52 { type: 'video-file-import', payload: VideoFileImportPayload } |
53 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
54 { type: 'email', payload: EmailPayload } |
55 { type: 'video-import', payload: VideoImportPayload } |
56 { type: 'activitypub-refresher', payload: RefreshPayload } |
57 { type: 'videos-views-stats', payload: {} } |
58 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
59 { type: 'actor-keys', payload: ActorKeysPayload } |
60 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
61 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
62 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
63 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
64 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
66 export type CreateJobOptions = {
71 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
72 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
73 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
74 'activitypub-http-unicast': processActivityPubHttpUnicast,
75 'activitypub-http-fetcher': processActivityPubHttpFetcher,
76 'activitypub-cleaner': processActivityPubCleaner,
77 'activitypub-follow': processActivityPubFollow,
78 'video-file-import': processVideoFileImport,
79 'video-transcoding': processVideoTranscoding,
80 'email': processEmail,
81 'video-import': processVideoImport,
82 'videos-views-stats': processVideosViewsStats,
83 'activitypub-refresher': refreshAPObject,
84 'video-live-ending': processVideoLiveEnding,
85 'actor-keys': processActorKeys,
86 'video-redundancy': processVideoRedundancy,
87 'move-to-object-storage': processMoveToObjectStorage,
88 'manage-video-torrent': processManageVideoTorrent,
89 'video-studio-edition': processVideoStudioEdition
92 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
93 'move-to-object-storage': onMoveToObjectStorageFailure
96 const jobTypes: JobType[] = [
98 'activitypub-http-broadcast',
99 'activitypub-http-broadcast-parallel',
100 'activitypub-http-fetcher',
101 'activitypub-http-unicast',
102 'activitypub-cleaner',
107 'videos-views-stats',
108 'activitypub-refresher',
112 'move-to-object-storage',
113 'manage-video-torrent',
114 'video-studio-edition'
117 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
121 private static instance: JobQueue
123 private queues: { [id in JobType]?: Queue } = {}
124 private initialized = false
125 private jobRedisPrefix: string
127 private constructor () {
130 init (produceOnly = false) {
131 // Already initialized
132 if (this.initialized === true) return
133 this.initialized = true
135 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
137 const queueOptions: Bull.QueueOptions = {
138 prefix: this.jobRedisPrefix,
140 password: CONFIG.REDIS.AUTH,
142 host: CONFIG.REDIS.HOSTNAME,
143 port: CONFIG.REDIS.PORT,
144 path: CONFIG.REDIS.SOCKET
147 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
151 for (const handlerName of (Object.keys(handlers) as JobType[])) {
152 const queue = new Bull(handlerName, queueOptions)
156 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
159 const handler = handlers[handlerName]
161 queue.process(this.getJobConcurrency(handlerName), async (jobArg: Job<any>) => {
162 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
164 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
165 }).catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
167 queue.on('failed', (job, err) => {
168 const logLevel = silentFailure.has(handlerName)
172 logger.log(logLevel, 'Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
174 if (errorHandlers[job.name]) {
175 errorHandlers[job.name](job, err)
176 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
180 queue.on('error', err => {
181 logger.error('Error in job queue %s.', handlerName, { err })
184 this.queues[handlerName] = queue
187 this.addRepeatableJobs()
191 for (const queueName of Object.keys(this.queues)) {
192 const queue = this.queues[queueName]
198 for (const handler of Object.keys(this.queues)) {
199 await this.queues[handler].pause(true)
204 for (const handler of Object.keys(this.queues)) {
205 await this.queues[handler].resume(true)
209 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
210 this.createJobWithPromise(obj, options)
211 .catch(err => logger.error('Cannot create job.', { err, obj }))
214 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
215 const queue: Queue = this.queues[obj.type]
216 if (queue === undefined) {
217 logger.error('Unknown queue %s: cannot create job.', obj.type)
221 const jobArgs: JobOptions = {
222 backoff: { delay: 60 * 1000, type: 'exponential' },
223 attempts: JOB_ATTEMPTS[obj.type],
224 timeout: JOB_TTL[obj.type],
225 priority: options.priority,
229 return queue.add(obj.payload, jobArgs)
232 async listForApi (options: {
239 const { state, start, count, asc, jobType } = options
241 const states = state ? [ state ] : jobStates
242 let results: Job[] = []
244 const filteredJobTypes = this.filterJobTypes(jobType)
246 for (const jobType of filteredJobTypes) {
247 const queue = this.queues[jobType]
248 if (queue === undefined) {
249 logger.error('Unknown queue %s to list jobs.', jobType)
253 const jobs = await queue.getJobs(states, 0, start + count, asc)
254 results = results.concat(jobs)
257 results.sort((j1: any, j2: any) => {
258 if (j1.timestamp < j2.timestamp) return -1
259 else if (j1.timestamp === j2.timestamp) return 0
264 if (asc === false) results.reverse()
266 return results.slice(start, start + count)
269 async count (state: JobState, jobType?: JobType): Promise<number> {
270 const states = state ? [ state ] : jobStates
273 const filteredJobTypes = this.filterJobTypes(jobType)
275 for (const type of filteredJobTypes) {
276 const queue = this.queues[type]
277 if (queue === undefined) {
278 logger.error('Unknown queue %s to count jobs.', type)
282 const counts = await queue.getJobCounts()
284 for (const s of states) {
293 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
295 return Promise.all(promises)
298 async removeOldJobs () {
299 for (const key of Object.keys(this.queues)) {
300 const queue = this.queues[key]
301 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
305 private addRepeatableJobs () {
306 this.queues['videos-views-stats'].add({}, {
307 repeat: REPEAT_JOBS['videos-views-stats']
308 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
310 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
311 this.queues['activitypub-cleaner'].add({}, {
312 repeat: REPEAT_JOBS['activitypub-cleaner']
313 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
317 private filterJobTypes (jobType?: JobType) {
318 if (!jobType) return jobTypes
320 return jobTypes.filter(t => t === jobType)
323 private getJobConcurrency (jobType: JobType) {
324 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
325 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
327 return JOB_CONCURRENCY[jobType]
330 static get Instance () {
331 return this.instance || (this.instance = new this())
335 // ---------------------------------------------------------------------------