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 MoveObjectStoragePayload,
17 VideoFileImportPayload,
19 VideoLiveEndingPayload,
20 VideoRedundancyPayload,
21 VideoTranscodingPayload
22 } from '../../../shared/models'
23 import { logger } from '../../helpers/logger'
24 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
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 { processVideosViewsStats } from './handlers/video-views-stats'
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-stats', payload: {} } |
52 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
53 { type: 'actor-keys', payload: ActorKeysPayload } |
54 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
55 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
56 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
58 export type CreateJobOptions = {
63 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
64 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
65 'activitypub-http-unicast': processActivityPubHttpUnicast,
66 'activitypub-http-fetcher': processActivityPubHttpFetcher,
67 'activitypub-cleaner': processActivityPubCleaner,
68 'activitypub-follow': processActivityPubFollow,
69 'video-file-import': processVideoFileImport,
70 'video-transcoding': processVideoTranscoding,
71 'email': processEmail,
72 'video-import': processVideoImport,
73 'videos-views-stats': processVideosViewsStats,
74 'activitypub-refresher': refreshAPObject,
75 'video-live-ending': processVideoLiveEnding,
76 'actor-keys': processActorKeys,
77 'video-redundancy': processVideoRedundancy,
78 'move-to-object-storage': processMoveToObjectStorage
81 const jobTypes: JobType[] = [
83 'activitypub-http-broadcast',
84 'activitypub-http-fetcher',
85 'activitypub-http-unicast',
86 'activitypub-cleaner',
92 'activitypub-refresher',
96 'move-to-object-storage'
101 private static instance: JobQueue
103 private queues: { [id in JobType]?: Queue } = {}
104 private initialized = false
105 private jobRedisPrefix: string
107 private constructor () {
110 init (produceOnly = false) {
111 // Already initialized
112 if (this.initialized === true) return
113 this.initialized = true
115 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
117 const queueOptions: Bull.QueueOptions = {
118 prefix: this.jobRedisPrefix,
120 password: CONFIG.REDIS.AUTH,
122 host: CONFIG.REDIS.HOSTNAME,
123 port: CONFIG.REDIS.PORT,
124 path: CONFIG.REDIS.SOCKET
127 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
131 for (const handlerName of (Object.keys(handlers) as JobType[])) {
132 const queue = new Bull(handlerName, queueOptions)
136 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
139 const handler = handlers[handlerName]
141 queue.process(this.getJobConcurrency(handlerName), handler)
142 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
144 queue.on('failed', (job, err) => {
145 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
148 queue.on('error', err => {
149 logger.error('Error in job queue %s.', handlerName, { err })
152 this.queues[handlerName] = queue
155 this.addRepeatableJobs()
159 for (const queueName of Object.keys(this.queues)) {
160 const queue = this.queues[queueName]
166 for (const handler of Object.keys(this.queues)) {
167 await this.queues[handler].pause(true)
172 for (const handler of Object.keys(this.queues)) {
173 await this.queues[handler].resume(true)
177 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
178 this.createJobWithPromise(obj, options)
179 .catch(err => logger.error('Cannot create job.', { err, obj }))
182 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
183 const queue = this.queues[obj.type]
184 if (queue === undefined) {
185 logger.error('Unknown queue %s: cannot create job.', obj.type)
189 const jobArgs: JobOptions = {
190 backoff: { delay: 60 * 1000, type: 'exponential' },
191 attempts: JOB_ATTEMPTS[obj.type],
192 timeout: JOB_TTL[obj.type],
193 priority: options.priority,
197 return queue.add(obj.payload, jobArgs)
200 async listForApi (options: {
207 const { state, start, count, asc, jobType } = options
209 const states = state ? [ state ] : jobStates
210 let results: Job[] = []
212 const filteredJobTypes = this.filterJobTypes(jobType)
214 for (const jobType of filteredJobTypes) {
215 const queue = this.queues[jobType]
216 if (queue === undefined) {
217 logger.error('Unknown queue %s to list jobs.', jobType)
221 const jobs = await queue.getJobs(states, 0, start + count, asc)
222 results = results.concat(jobs)
225 results.sort((j1: any, j2: any) => {
226 if (j1.timestamp < j2.timestamp) return -1
227 else if (j1.timestamp === j2.timestamp) return 0
232 if (asc === false) results.reverse()
234 return results.slice(start, start + count)
237 async count (state: JobState, jobType?: JobType): Promise<number> {
238 const states = state ? [ state ] : jobStates
241 const filteredJobTypes = this.filterJobTypes(jobType)
243 for (const type of filteredJobTypes) {
244 const queue = this.queues[type]
245 if (queue === undefined) {
246 logger.error('Unknown queue %s to count jobs.', type)
250 const counts = await queue.getJobCounts()
252 for (const s of states) {
260 async removeOldJobs () {
261 for (const key of Object.keys(this.queues)) {
262 const queue = this.queues[key]
263 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
267 private addRepeatableJobs () {
268 this.queues['videos-views-stats'].add({}, {
269 repeat: REPEAT_JOBS['videos-views-stats']
270 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
272 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
273 this.queues['activitypub-cleaner'].add({}, {
274 repeat: REPEAT_JOBS['activitypub-cleaner']
275 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
279 private filterJobTypes (jobType?: JobType) {
280 if (!jobType) return jobTypes
282 return jobTypes.filter(t => t === jobType)
285 private getJobConcurrency (jobType: JobType) {
286 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
287 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
289 return JOB_CONCURRENCY[jobType]
292 static get Instance () {
293 return this.instance || (this.instance = new this())
297 // ---------------------------------------------------------------------------