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-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
47 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
48 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
49 { type: 'activitypub-http-cleaner', payload: {} } |
50 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
51 { type: 'video-file-import', payload: VideoFileImportPayload } |
52 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
53 { type: 'email', payload: EmailPayload } |
54 { type: 'video-import', payload: VideoImportPayload } |
55 { type: 'activitypub-refresher', payload: RefreshPayload } |
56 { type: 'videos-views-stats', payload: {} } |
57 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
58 { type: 'actor-keys', payload: ActorKeysPayload } |
59 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
60 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
61 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
62 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
63 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
65 export type CreateJobOptions = {
70 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
71 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
72 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
73 'activitypub-http-unicast': processActivityPubHttpUnicast,
74 'activitypub-http-fetcher': processActivityPubHttpFetcher,
75 'activitypub-cleaner': processActivityPubCleaner,
76 'activitypub-follow': processActivityPubFollow,
77 'video-file-import': processVideoFileImport,
78 'video-transcoding': processVideoTranscoding,
79 'email': processEmail,
80 'video-import': processVideoImport,
81 'videos-views-stats': processVideosViewsStats,
82 'activitypub-refresher': refreshAPObject,
83 'video-live-ending': processVideoLiveEnding,
84 'actor-keys': processActorKeys,
85 'video-redundancy': processVideoRedundancy,
86 'move-to-object-storage': processMoveToObjectStorage,
87 'manage-video-torrent': processManageVideoTorrent,
88 'video-studio-edition': processVideoStudioEdition
91 const jobTypes: JobType[] = [
93 'activitypub-http-broadcast',
94 'activitypub-http-broadcast-parallel',
95 'activitypub-http-fetcher',
96 'activitypub-http-unicast',
97 'activitypub-cleaner',
102 'videos-views-stats',
103 'activitypub-refresher',
107 'move-to-object-storage',
108 'manage-video-torrent',
109 'video-studio-edition'
112 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
116 private static instance: JobQueue
118 private queues: { [id in JobType]?: Queue } = {}
119 private initialized = false
120 private jobRedisPrefix: string
122 private constructor () {
125 init (produceOnly = false) {
126 // Already initialized
127 if (this.initialized === true) return
128 this.initialized = true
130 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
132 const queueOptions: Bull.QueueOptions = {
133 prefix: this.jobRedisPrefix,
135 password: CONFIG.REDIS.AUTH,
137 host: CONFIG.REDIS.HOSTNAME,
138 port: CONFIG.REDIS.PORT,
139 path: CONFIG.REDIS.SOCKET
142 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
146 for (const handlerName of (Object.keys(handlers) as JobType[])) {
147 const queue = new Bull(handlerName, queueOptions)
151 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
154 const handler = handlers[handlerName]
156 queue.process(this.getJobConcurrency(handlerName), handler)
157 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
159 queue.on('failed', (job, err) => {
160 const logLevel = silentFailure.has(handlerName)
164 logger.log(logLevel, 'Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
167 queue.on('error', err => {
168 logger.error('Error in job queue %s.', handlerName, { err })
171 this.queues[handlerName] = queue
174 this.addRepeatableJobs()
178 for (const queueName of Object.keys(this.queues)) {
179 const queue = this.queues[queueName]
185 for (const handler of Object.keys(this.queues)) {
186 await this.queues[handler].pause(true)
191 for (const handler of Object.keys(this.queues)) {
192 await this.queues[handler].resume(true)
196 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
197 this.createJobWithPromise(obj, options)
198 .catch(err => logger.error('Cannot create job.', { err, obj }))
201 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
202 const queue: Queue = this.queues[obj.type]
203 if (queue === undefined) {
204 logger.error('Unknown queue %s: cannot create job.', obj.type)
208 const jobArgs: JobOptions = {
209 backoff: { delay: 60 * 1000, type: 'exponential' },
210 attempts: JOB_ATTEMPTS[obj.type],
211 timeout: JOB_TTL[obj.type],
212 priority: options.priority,
216 return queue.add(obj.payload, jobArgs)
219 async listForApi (options: {
226 const { state, start, count, asc, jobType } = options
228 const states = state ? [ state ] : jobStates
229 let results: Job[] = []
231 const filteredJobTypes = this.filterJobTypes(jobType)
233 for (const jobType of filteredJobTypes) {
234 const queue = this.queues[jobType]
235 if (queue === undefined) {
236 logger.error('Unknown queue %s to list jobs.', jobType)
240 const jobs = await queue.getJobs(states, 0, start + count, asc)
241 results = results.concat(jobs)
244 results.sort((j1: any, j2: any) => {
245 if (j1.timestamp < j2.timestamp) return -1
246 else if (j1.timestamp === j2.timestamp) return 0
251 if (asc === false) results.reverse()
253 return results.slice(start, start + count)
256 async count (state: JobState, jobType?: JobType): Promise<number> {
257 const states = state ? [ state ] : jobStates
260 const filteredJobTypes = this.filterJobTypes(jobType)
262 for (const type of filteredJobTypes) {
263 const queue = this.queues[type]
264 if (queue === undefined) {
265 logger.error('Unknown queue %s to count jobs.', type)
269 const counts = await queue.getJobCounts()
271 for (const s of states) {
279 async removeOldJobs () {
280 for (const key of Object.keys(this.queues)) {
281 const queue = this.queues[key]
282 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
286 private addRepeatableJobs () {
287 this.queues['videos-views-stats'].add({}, {
288 repeat: REPEAT_JOBS['videos-views-stats']
289 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
291 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
292 this.queues['activitypub-cleaner'].add({}, {
293 repeat: REPEAT_JOBS['activitypub-cleaner']
294 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
298 private filterJobTypes (jobType?: JobType) {
299 if (!jobType) return jobTypes
301 return jobTypes.filter(t => t === jobType)
304 private getJobConcurrency (jobType: JobType) {
305 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
306 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
308 return JOB_CONCURRENCY[jobType]
311 static get Instance () {
312 return this.instance || (this.instance = new this())
316 // ---------------------------------------------------------------------------