1 import * as Bull from 'bull'
2 import { jobStates } from '@server/helpers/custom-validators/jobs'
3 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
5 ActivitypubFollowPayload,
6 ActivitypubHttpBroadcastPayload,
7 ActivitypubHttpFetcherPayload,
8 ActivitypubHttpUnicastPayload,
13 VideoFileImportPayload,
15 VideoLiveEndingPayload,
16 VideoRedundancyPayload,
17 VideoTranscodingPayload
18 } from '../../../shared/models'
19 import { logger } from '../../helpers/logger'
20 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
21 import { Redis } from '../redis'
22 import { processActivityPubFollow } from './handlers/activitypub-follow'
23 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
24 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
25 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
26 import { refreshAPObject } from './handlers/activitypub-refresher'
27 import { processEmail } from './handlers/email'
28 import { processVideoFileImport } from './handlers/video-file-import'
29 import { processVideoImport } from './handlers/video-import'
30 import { processVideoLiveEnding } from './handlers/video-live-ending'
31 import { processVideoTranscoding } from './handlers/video-transcoding'
32 import { processVideosViews } from './handlers/video-views'
34 type CreateJobArgument =
35 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
36 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
37 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
38 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
39 { type: 'video-file-import', payload: VideoFileImportPayload } |
40 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
41 { type: 'email', payload: EmailPayload } |
42 { type: 'video-import', payload: VideoImportPayload } |
43 { type: 'activitypub-refresher', payload: RefreshPayload } |
44 { type: 'videos-views', payload: {} } |
45 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
46 { type: 'video-redundancy', payload: VideoRedundancyPayload }
48 type CreateJobOptions = {
52 const handlers: { [id in JobType]: (job: Bull.Job) => Promise<any> } = {
53 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
54 'activitypub-http-unicast': processActivityPubHttpUnicast,
55 'activitypub-http-fetcher': processActivityPubHttpFetcher,
56 'activitypub-follow': processActivityPubFollow,
57 'video-file-import': processVideoFileImport,
58 'video-transcoding': processVideoTranscoding,
59 'email': processEmail,
60 'video-import': processVideoImport,
61 'videos-views': processVideosViews,
62 'activitypub-refresher': refreshAPObject,
63 'video-live-ending': processVideoLiveEnding,
64 'video-redundancy': processVideoRedundancy
67 const jobTypes: JobType[] = [
69 'activitypub-http-broadcast',
70 'activitypub-http-fetcher',
71 'activitypub-http-unicast',
77 'activitypub-refresher',
84 private static instance: JobQueue
86 private queues: { [id in JobType]?: Bull.Queue } = {}
87 private initialized = false
88 private jobRedisPrefix: string
90 private constructor () {
94 // Already initialized
95 if (this.initialized === true) return
96 this.initialized = true
98 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
99 const queueOptions = {
100 prefix: this.jobRedisPrefix,
101 redis: Redis.getRedisClientOptions(),
103 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
107 for (const handlerName of Object.keys(handlers)) {
108 const queue = new Bull(handlerName, queueOptions)
109 const handler = handlers[handlerName]
111 queue.process(JOB_CONCURRENCY[handlerName], handler)
112 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
114 queue.on('failed', (job, err) => {
115 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
118 queue.on('error', err => {
119 logger.error('Error in job queue %s.', handlerName, { err })
122 this.queues[handlerName] = queue
125 this.addRepeatableJobs()
129 for (const queueName of Object.keys(this.queues)) {
130 const queue = this.queues[queueName]
135 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
136 this.createJobWithPromise(obj, options)
137 .catch(err => logger.error('Cannot create job.', { err, obj }))
140 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
141 const queue = this.queues[obj.type]
142 if (queue === undefined) {
143 logger.error('Unknown queue %s: cannot create job.', obj.type)
147 const jobArgs: Bull.JobOptions = {
148 backoff: { delay: 60 * 1000, type: 'exponential' },
149 attempts: JOB_ATTEMPTS[obj.type],
150 timeout: JOB_TTL[obj.type],
154 return queue.add(obj.payload, jobArgs)
157 async listForApi (options: {
163 }): Promise<Bull.Job[]> {
164 const { state, start, count, asc, jobType } = options
166 const states = state ? [ state ] : jobStates
167 let results: Bull.Job[] = []
169 const filteredJobTypes = this.filterJobTypes(jobType)
171 for (const jobType of filteredJobTypes) {
172 const queue = this.queues[jobType]
173 if (queue === undefined) {
174 logger.error('Unknown queue %s to list jobs.', jobType)
178 const jobs = await queue.getJobs(states, 0, start + count, asc)
179 results = results.concat(jobs)
182 results.sort((j1: any, j2: any) => {
183 if (j1.timestamp < j2.timestamp) return -1
184 else if (j1.timestamp === j2.timestamp) return 0
189 if (asc === false) results.reverse()
191 return results.slice(start, start + count)
194 async count (state: JobState, jobType?: JobType): Promise<number> {
195 const states = state ? [ state ] : jobStates
198 const filteredJobTypes = this.filterJobTypes(jobType)
200 for (const type of filteredJobTypes) {
201 const queue = this.queues[type]
202 if (queue === undefined) {
203 logger.error('Unknown queue %s to count jobs.', type)
207 const counts = await queue.getJobCounts()
209 for (const s of states) {
217 async removeOldJobs () {
218 for (const key of Object.keys(this.queues)) {
219 const queue = this.queues[key]
220 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
224 private addRepeatableJobs () {
225 this.queues['videos-views'].add({}, {
226 repeat: REPEAT_JOBS['videos-views']
227 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
230 private filterJobTypes (jobType?: JobType) {
231 if (!jobType) return jobTypes
233 return jobTypes.filter(t => t === jobType)
236 static get Instance () {
237 return this.instance || (this.instance = new this())
241 // ---------------------------------------------------------------------------