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]
165 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
166 this.createJobWithPromise(obj, options)
167 .catch(err => logger.error('Cannot create job.', { err, obj }))
170 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
171 const queue = this.queues[obj.type]
172 if (queue === undefined) {
173 logger.error('Unknown queue %s: cannot create job.', obj.type)
177 const jobArgs: JobOptions = {
178 backoff: { delay: 60 * 1000, type: 'exponential' },
179 attempts: JOB_ATTEMPTS[obj.type],
180 timeout: JOB_TTL[obj.type],
181 priority: options.priority,
185 return queue.add(obj.payload, jobArgs)
188 async listForApi (options: {
195 const { state, start, count, asc, jobType } = options
197 const states = state ? [ state ] : jobStates
198 let results: Job[] = []
200 const filteredJobTypes = this.filterJobTypes(jobType)
202 for (const jobType of filteredJobTypes) {
203 const queue = this.queues[jobType]
204 if (queue === undefined) {
205 logger.error('Unknown queue %s to list jobs.', jobType)
209 const jobs = await queue.getJobs(states, 0, start + count, asc)
210 results = results.concat(jobs)
213 results.sort((j1: any, j2: any) => {
214 if (j1.timestamp < j2.timestamp) return -1
215 else if (j1.timestamp === j2.timestamp) return 0
220 if (asc === false) results.reverse()
222 return results.slice(start, start + count)
225 async count (state: JobState, jobType?: JobType): Promise<number> {
226 const states = state ? [ state ] : jobStates
229 const filteredJobTypes = this.filterJobTypes(jobType)
231 for (const type of filteredJobTypes) {
232 const queue = this.queues[type]
233 if (queue === undefined) {
234 logger.error('Unknown queue %s to count jobs.', type)
238 const counts = await queue.getJobCounts()
240 for (const s of states) {
248 async removeOldJobs () {
249 for (const key of Object.keys(this.queues)) {
250 const queue = this.queues[key]
251 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
255 private addRepeatableJobs () {
256 this.queues['videos-views-stats'].add({}, {
257 repeat: REPEAT_JOBS['videos-views-stats']
258 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
260 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
261 this.queues['activitypub-cleaner'].add({}, {
262 repeat: REPEAT_JOBS['activitypub-cleaner']
263 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
267 private filterJobTypes (jobType?: JobType) {
268 if (!jobType) return jobTypes
270 return jobTypes.filter(t => t === jobType)
273 private getJobConcurrency (jobType: JobType) {
274 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
275 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
277 return JOB_CONCURRENCY[jobType]
280 static get Instance () {
281 return this.instance || (this.instance = new this())
285 // ---------------------------------------------------------------------------