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,
18 VideoFileImportPayload,
20 VideoLiveEndingPayload,
21 VideoRedundancyPayload,
22 VideoTranscodingPayload
23 } from '../../../shared/models'
24 import { logger } from '../../helpers/logger'
25 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
26 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
27 import { processActivityPubFollow } from './handlers/activitypub-follow'
28 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
29 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
30 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
31 import { refreshAPObject } from './handlers/activitypub-refresher'
32 import { processActorKeys } from './handlers/actor-keys'
33 import { processEmail } from './handlers/email'
34 import { processMoveToObjectStorage } from './handlers/move-to-object-storage'
35 import { processVideoEdition } from './handlers/video-edition'
36 import { processVideoFileImport } from './handlers/video-file-import'
37 import { processVideoImport } from './handlers/video-import'
38 import { processVideoLiveEnding } from './handlers/video-live-ending'
39 import { processVideoTranscoding } from './handlers/video-transcoding'
40 import { processVideosViewsStats } from './handlers/video-views-stats'
42 type CreateJobArgument =
43 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
44 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
45 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
46 { type: 'activitypub-http-cleaner', payload: {} } |
47 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
48 { type: 'video-file-import', payload: VideoFileImportPayload } |
49 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
50 { type: 'email', payload: EmailPayload } |
51 { type: 'video-import', payload: VideoImportPayload } |
52 { type: 'activitypub-refresher', payload: RefreshPayload } |
53 { type: 'videos-views-stats', payload: {} } |
54 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
55 { type: 'actor-keys', payload: ActorKeysPayload } |
56 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
57 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
58 { type: 'video-edition', payload: VideoEditionPayload } |
59 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
61 export type CreateJobOptions = {
66 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
67 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
68 'activitypub-http-unicast': processActivityPubHttpUnicast,
69 'activitypub-http-fetcher': processActivityPubHttpFetcher,
70 'activitypub-cleaner': processActivityPubCleaner,
71 'activitypub-follow': processActivityPubFollow,
72 'video-file-import': processVideoFileImport,
73 'video-transcoding': processVideoTranscoding,
74 'email': processEmail,
75 'video-import': processVideoImport,
76 'videos-views-stats': processVideosViewsStats,
77 'activitypub-refresher': refreshAPObject,
78 'video-live-ending': processVideoLiveEnding,
79 'actor-keys': processActorKeys,
80 'video-redundancy': processVideoRedundancy,
81 'move-to-object-storage': processMoveToObjectStorage,
82 'video-edition': processVideoEdition
85 const jobTypes: JobType[] = [
87 'activitypub-http-broadcast',
88 'activitypub-http-fetcher',
89 'activitypub-http-unicast',
90 'activitypub-cleaner',
96 'activitypub-refresher',
100 'move-to-object-storage',
106 private static instance: JobQueue
108 private queues: { [id in JobType]?: Queue } = {}
109 private initialized = false
110 private jobRedisPrefix: string
112 private constructor () {
115 init (produceOnly = false) {
116 // Already initialized
117 if (this.initialized === true) return
118 this.initialized = true
120 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
122 const queueOptions: Bull.QueueOptions = {
123 prefix: this.jobRedisPrefix,
125 password: CONFIG.REDIS.AUTH,
127 host: CONFIG.REDIS.HOSTNAME,
128 port: CONFIG.REDIS.PORT,
129 path: CONFIG.REDIS.SOCKET
132 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
136 for (const handlerName of (Object.keys(handlers) as JobType[])) {
137 const queue = new Bull(handlerName, queueOptions)
141 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
144 const handler = handlers[handlerName]
146 queue.process(this.getJobConcurrency(handlerName), handler)
147 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
149 queue.on('failed', (job, err) => {
150 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
153 queue.on('error', err => {
154 logger.error('Error in job queue %s.', handlerName, { err })
157 this.queues[handlerName] = queue
160 this.addRepeatableJobs()
164 for (const queueName of Object.keys(this.queues)) {
165 const queue = this.queues[queueName]
171 for (const handler of Object.keys(this.queues)) {
172 await this.queues[handler].pause(true)
177 for (const handler of Object.keys(this.queues)) {
178 await this.queues[handler].resume(true)
182 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
183 this.createJobWithPromise(obj, options)
184 .catch(err => logger.error('Cannot create job.', { err, obj }))
187 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
188 const queue = this.queues[obj.type]
189 if (queue === undefined) {
190 logger.error('Unknown queue %s: cannot create job.', obj.type)
194 const jobArgs: JobOptions = {
195 backoff: { delay: 60 * 1000, type: 'exponential' },
196 attempts: JOB_ATTEMPTS[obj.type],
197 timeout: JOB_TTL[obj.type],
198 priority: options.priority,
202 return queue.add(obj.payload, jobArgs)
205 async listForApi (options: {
212 const { state, start, count, asc, jobType } = options
214 const states = state ? [ state ] : jobStates
215 let results: Job[] = []
217 const filteredJobTypes = this.filterJobTypes(jobType)
219 for (const jobType of filteredJobTypes) {
220 const queue = this.queues[jobType]
221 if (queue === undefined) {
222 logger.error('Unknown queue %s to list jobs.', jobType)
226 const jobs = await queue.getJobs(states, 0, start + count, asc)
227 results = results.concat(jobs)
230 results.sort((j1: any, j2: any) => {
231 if (j1.timestamp < j2.timestamp) return -1
232 else if (j1.timestamp === j2.timestamp) return 0
237 if (asc === false) results.reverse()
239 return results.slice(start, start + count)
242 async count (state: JobState, jobType?: JobType): Promise<number> {
243 const states = state ? [ state ] : jobStates
246 const filteredJobTypes = this.filterJobTypes(jobType)
248 for (const type of filteredJobTypes) {
249 const queue = this.queues[type]
250 if (queue === undefined) {
251 logger.error('Unknown queue %s to count jobs.', type)
255 const counts = await queue.getJobCounts()
257 for (const s of states) {
265 async removeOldJobs () {
266 for (const key of Object.keys(this.queues)) {
267 const queue = this.queues[key]
268 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
272 private addRepeatableJobs () {
273 this.queues['videos-views-stats'].add({}, {
274 repeat: REPEAT_JOBS['videos-views-stats']
275 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
277 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
278 this.queues['activitypub-cleaner'].add({}, {
279 repeat: REPEAT_JOBS['activitypub-cleaner']
280 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
284 private filterJobTypes (jobType?: JobType) {
285 if (!jobType) return jobTypes
287 return jobTypes.filter(t => t === jobType)
290 private getJobConcurrency (jobType: JobType) {
291 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
292 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
294 return JOB_CONCURRENCY[jobType]
297 static get Instance () {
298 return this.instance || (this.instance = new this())
302 // ---------------------------------------------------------------------------