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 { processActivityPubCleaner } from './handlers/activitypub-cleaner'
28 import { processActivityPubFollow } from './handlers/activitypub-follow'
29 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
30 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
31 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
32 import { refreshAPObject } from './handlers/activitypub-refresher'
33 import { processActorKeys } from './handlers/actor-keys'
34 import { processEmail } from './handlers/email'
35 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
36 import { processMoveToObjectStorage } from './handlers/move-to-object-storage'
37 import { processVideoFileImport } from './handlers/video-file-import'
38 import { processVideoImport } from './handlers/video-import'
39 import { processVideoLiveEnding } from './handlers/video-live-ending'
40 import { processVideoStudioEdition } from './handlers/video-studio-edition'
41 import { processVideoTranscoding } from './handlers/video-transcoding'
42 import { processVideosViewsStats } from './handlers/video-views-stats'
44 type CreateJobArgument =
45 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
46 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
47 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
48 { type: 'activitypub-http-cleaner', payload: {} } |
49 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
50 { type: 'video-file-import', payload: VideoFileImportPayload } |
51 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
52 { type: 'email', payload: EmailPayload } |
53 { type: 'video-import', payload: VideoImportPayload } |
54 { type: 'activitypub-refresher', payload: RefreshPayload } |
55 { type: 'videos-views-stats', payload: {} } |
56 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
57 { type: 'actor-keys', payload: ActorKeysPayload } |
58 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
59 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
60 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
61 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
62 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
64 export type CreateJobOptions = {
69 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
70 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
71 'activitypub-http-unicast': processActivityPubHttpUnicast,
72 'activitypub-http-fetcher': processActivityPubHttpFetcher,
73 'activitypub-cleaner': processActivityPubCleaner,
74 'activitypub-follow': processActivityPubFollow,
75 'video-file-import': processVideoFileImport,
76 'video-transcoding': processVideoTranscoding,
77 'email': processEmail,
78 'video-import': processVideoImport,
79 'videos-views-stats': processVideosViewsStats,
80 'activitypub-refresher': refreshAPObject,
81 'video-live-ending': processVideoLiveEnding,
82 'actor-keys': processActorKeys,
83 'video-redundancy': processVideoRedundancy,
84 'move-to-object-storage': processMoveToObjectStorage,
85 'manage-video-torrent': processManageVideoTorrent,
86 'video-studio-edition': processVideoStudioEdition
89 const jobTypes: JobType[] = [
91 'activitypub-http-broadcast',
92 'activitypub-http-fetcher',
93 'activitypub-http-unicast',
94 'activitypub-cleaner',
100 'activitypub-refresher',
104 'move-to-object-storage',
105 'manage-video-torrent',
106 'video-studio-edition'
111 private static instance: JobQueue
113 private queues: { [id in JobType]?: Queue } = {}
114 private initialized = false
115 private jobRedisPrefix: string
117 private constructor () {
120 init (produceOnly = false) {
121 // Already initialized
122 if (this.initialized === true) return
123 this.initialized = true
125 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
127 const queueOptions: Bull.QueueOptions = {
128 prefix: this.jobRedisPrefix,
130 password: CONFIG.REDIS.AUTH,
132 host: CONFIG.REDIS.HOSTNAME,
133 port: CONFIG.REDIS.PORT,
134 path: CONFIG.REDIS.SOCKET
137 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
141 for (const handlerName of (Object.keys(handlers) as JobType[])) {
142 const queue = new Bull(handlerName, queueOptions)
146 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
149 const handler = handlers[handlerName]
151 queue.process(this.getJobConcurrency(handlerName), handler)
152 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
154 queue.on('failed', (job, err) => {
155 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
158 queue.on('error', err => {
159 logger.error('Error in job queue %s.', handlerName, { err })
162 this.queues[handlerName] = queue
165 this.addRepeatableJobs()
169 for (const queueName of Object.keys(this.queues)) {
170 const queue = this.queues[queueName]
176 for (const handler of Object.keys(this.queues)) {
177 await this.queues[handler].pause(true)
182 for (const handler of Object.keys(this.queues)) {
183 await this.queues[handler].resume(true)
187 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
188 this.createJobWithPromise(obj, options)
189 .catch(err => logger.error('Cannot create job.', { err, obj }))
192 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
193 const queue: Queue = this.queues[obj.type]
194 if (queue === undefined) {
195 logger.error('Unknown queue %s: cannot create job.', obj.type)
199 const jobArgs: JobOptions = {
200 backoff: { delay: 60 * 1000, type: 'exponential' },
201 attempts: JOB_ATTEMPTS[obj.type],
202 timeout: JOB_TTL[obj.type],
203 priority: options.priority,
207 return queue.add(obj.payload, jobArgs)
210 async listForApi (options: {
217 const { state, start, count, asc, jobType } = options
219 const states = state ? [ state ] : jobStates
220 let results: Job[] = []
222 const filteredJobTypes = this.filterJobTypes(jobType)
224 for (const jobType of filteredJobTypes) {
225 const queue = this.queues[jobType]
226 if (queue === undefined) {
227 logger.error('Unknown queue %s to list jobs.', jobType)
231 const jobs = await queue.getJobs(states, 0, start + count, asc)
232 results = results.concat(jobs)
235 results.sort((j1: any, j2: any) => {
236 if (j1.timestamp < j2.timestamp) return -1
237 else if (j1.timestamp === j2.timestamp) return 0
242 if (asc === false) results.reverse()
244 return results.slice(start, start + count)
247 async count (state: JobState, jobType?: JobType): Promise<number> {
248 const states = state ? [ state ] : jobStates
251 const filteredJobTypes = this.filterJobTypes(jobType)
253 for (const type of filteredJobTypes) {
254 const queue = this.queues[type]
255 if (queue === undefined) {
256 logger.error('Unknown queue %s to count jobs.', type)
260 const counts = await queue.getJobCounts()
262 for (const s of states) {
270 async removeOldJobs () {
271 for (const key of Object.keys(this.queues)) {
272 const queue = this.queues[key]
273 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
277 private addRepeatableJobs () {
278 this.queues['videos-views-stats'].add({}, {
279 repeat: REPEAT_JOBS['videos-views-stats']
280 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
282 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
283 this.queues['activitypub-cleaner'].add({}, {
284 repeat: REPEAT_JOBS['activitypub-cleaner']
285 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
289 private filterJobTypes (jobType?: JobType) {
290 if (!jobType) return jobTypes
292 return jobTypes.filter(t => t === jobType)
295 private getJobConcurrency (jobType: JobType) {
296 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
297 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
299 return JOB_CONCURRENCY[jobType]
302 static get Instance () {
303 return this.instance || (this.instance = new this())
307 // ---------------------------------------------------------------------------