]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
Fix job queue tests
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
1 import {
2 FlowJob,
3 FlowProducer,
4 Job,
5 JobsOptions,
6 Queue,
7 QueueEvents,
8 QueueEventsOptions,
9 QueueOptions,
10 QueueScheduler,
11 QueueSchedulerOptions,
12 Worker,
13 WorkerOptions
14 } from 'bullmq'
15 import { jobStates } from '@server/helpers/custom-validators/jobs'
16 import { CONFIG } from '@server/initializers/config'
17 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
18 import { pick, timeoutPromise } from '@shared/core-utils'
19 import {
20 ActivitypubFollowPayload,
21 ActivitypubHttpBroadcastPayload,
22 ActivitypubHttpFetcherPayload,
23 ActivitypubHttpUnicastPayload,
24 ActorKeysPayload,
25 DeleteResumableUploadMetaFilePayload,
26 EmailPayload,
27 FederateVideoPayload,
28 JobState,
29 JobType,
30 ManageVideoTorrentPayload,
31 MoveObjectStoragePayload,
32 NotifyPayload,
33 RefreshPayload,
34 VideoFileImportPayload,
35 VideoImportPayload,
36 VideoLiveEndingPayload,
37 VideoRedundancyPayload,
38 VideoStudioEditionPayload,
39 VideoTranscodingPayload
40 } from '../../../shared/models'
41 import { logger } from '../../helpers/logger'
42 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
43 import { Hooks } from '../plugins/hooks'
44 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
45 import { processActivityPubFollow } from './handlers/activitypub-follow'
46 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
47 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
48 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
49 import { refreshAPObject } from './handlers/activitypub-refresher'
50 import { processActorKeys } from './handlers/actor-keys'
51 import { processEmail } from './handlers/email'
52 import { processFederateVideo } from './handlers/federate-video'
53 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
54 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
55 import { processNotify } from './handlers/notify'
56 import { processVideoFileImport } from './handlers/video-file-import'
57 import { processVideoImport } from './handlers/video-import'
58 import { processVideoLiveEnding } from './handlers/video-live-ending'
59 import { processVideoStudioEdition } from './handlers/video-studio-edition'
60 import { processVideoTranscoding } from './handlers/video-transcoding'
61 import { processVideosViewsStats } from './handlers/video-views-stats'
62
63 export type CreateJobArgument =
64 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
65 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
66 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
67 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
68 { type: 'activitypub-http-cleaner', payload: {} } |
69 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
70 { type: 'video-file-import', payload: VideoFileImportPayload } |
71 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
72 { type: 'email', payload: EmailPayload } |
73 { type: 'video-import', payload: VideoImportPayload } |
74 { type: 'activitypub-refresher', payload: RefreshPayload } |
75 { type: 'videos-views-stats', payload: {} } |
76 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
77 { type: 'actor-keys', payload: ActorKeysPayload } |
78 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
79 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
80 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
81 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
82 { type: 'notify', payload: NotifyPayload } |
83 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
84 { type: 'federate-video', payload: FederateVideoPayload }
85
86 export type CreateJobOptions = {
87 delay?: number
88 priority?: number
89 }
90
91 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
92 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
93 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
94 'activitypub-http-unicast': processActivityPubHttpUnicast,
95 'activitypub-http-fetcher': processActivityPubHttpFetcher,
96 'activitypub-cleaner': processActivityPubCleaner,
97 'activitypub-follow': processActivityPubFollow,
98 'video-file-import': processVideoFileImport,
99 'video-transcoding': processVideoTranscoding,
100 'email': processEmail,
101 'video-import': processVideoImport,
102 'videos-views-stats': processVideosViewsStats,
103 'activitypub-refresher': refreshAPObject,
104 'video-live-ending': processVideoLiveEnding,
105 'actor-keys': processActorKeys,
106 'video-redundancy': processVideoRedundancy,
107 'move-to-object-storage': processMoveToObjectStorage,
108 'manage-video-torrent': processManageVideoTorrent,
109 'notify': processNotify,
110 'video-studio-edition': processVideoStudioEdition,
111 'federate-video': processFederateVideo
112 }
113
114 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
115 'move-to-object-storage': onMoveToObjectStorageFailure
116 }
117
118 const jobTypes: JobType[] = [
119 'activitypub-follow',
120 'activitypub-http-broadcast',
121 'activitypub-http-broadcast-parallel',
122 'activitypub-http-fetcher',
123 'activitypub-http-unicast',
124 'activitypub-cleaner',
125 'email',
126 'video-transcoding',
127 'video-file-import',
128 'video-import',
129 'videos-views-stats',
130 'activitypub-refresher',
131 'video-redundancy',
132 'actor-keys',
133 'video-live-ending',
134 'move-to-object-storage',
135 'manage-video-torrent',
136 'video-studio-edition',
137 'notify',
138 'federate-video'
139 ]
140
141 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
142
143 class JobQueue {
144
145 private static instance: JobQueue
146
147 private workers: { [id in JobType]?: Worker } = {}
148 private queues: { [id in JobType]?: Queue } = {}
149 private queueSchedulers: { [id in JobType]?: QueueScheduler } = {}
150 private queueEvents: { [id in JobType]?: QueueEvents } = {}
151
152 private flowProducer: FlowProducer
153
154 private initialized = false
155 private jobRedisPrefix: string
156
157 private constructor () {
158 }
159
160 init (produceOnly = false) {
161 // Already initialized
162 if (this.initialized === true) return
163 this.initialized = true
164
165 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
166
167 for (const handlerName of (Object.keys(handlers) as JobType[])) {
168 this.buildWorker(handlerName, produceOnly)
169 this.buildQueue(handlerName)
170 this.buildQueueScheduler(handlerName, produceOnly)
171 this.buildQueueEvent(handlerName, produceOnly)
172 }
173
174 this.flowProducer = new FlowProducer({
175 connection: this.getRedisConnection(),
176 prefix: this.jobRedisPrefix
177 })
178
179 this.addRepeatableJobs()
180 }
181
182 private buildWorker (handlerName: JobType, produceOnly: boolean) {
183 const workerOptions: WorkerOptions = {
184 autorun: !produceOnly,
185 concurrency: this.getJobConcurrency(handlerName),
186 prefix: this.jobRedisPrefix,
187 connection: this.getRedisConnection()
188 }
189
190 const handler = function (job: Job) {
191 const timeout = JOB_TTL[handlerName]
192 const p = handlers[handlerName](job)
193
194 if (!timeout) return p
195
196 return timeoutPromise(p, timeout)
197 }
198
199 const processor = async (jobArg: Job<any>) => {
200 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
201
202 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
203 }
204
205 const worker = new Worker(handlerName, processor, workerOptions)
206
207 worker.on('failed', (job, err) => {
208 const logLevel = silentFailure.has(handlerName)
209 ? 'debug'
210 : 'error'
211
212 logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
213
214 if (errorHandlers[job.name]) {
215 errorHandlers[job.name](job, err)
216 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
217 }
218 })
219
220 worker.on('error', err => {
221 logger.error('Error in job queue %s.', handlerName, { err })
222 })
223
224 this.workers[handlerName] = worker
225 }
226
227 private buildQueue (handlerName: JobType) {
228 const queueOptions: QueueOptions = {
229 connection: this.getRedisConnection(),
230 prefix: this.jobRedisPrefix
231 }
232
233 this.queues[handlerName] = new Queue(handlerName, queueOptions)
234 }
235
236 private buildQueueScheduler (handlerName: JobType, produceOnly: boolean) {
237 const queueSchedulerOptions: QueueSchedulerOptions = {
238 autorun: !produceOnly,
239 connection: this.getRedisConnection(),
240 prefix: this.jobRedisPrefix,
241 maxStalledCount: 10
242 }
243 this.queueSchedulers[handlerName] = new QueueScheduler(handlerName, queueSchedulerOptions)
244 }
245
246 private buildQueueEvent (handlerName: JobType, produceOnly: boolean) {
247 const queueEventsOptions: QueueEventsOptions = {
248 autorun: !produceOnly,
249 connection: this.getRedisConnection(),
250 prefix: this.jobRedisPrefix
251 }
252 this.queueEvents[handlerName] = new QueueEvents(handlerName, queueEventsOptions)
253 }
254
255 private getRedisConnection () {
256 return {
257 password: CONFIG.REDIS.AUTH,
258 db: CONFIG.REDIS.DB,
259 host: CONFIG.REDIS.HOSTNAME,
260 port: CONFIG.REDIS.PORT,
261 path: CONFIG.REDIS.SOCKET
262 }
263 }
264
265 // ---------------------------------------------------------------------------
266
267 async terminate () {
268 const promises = Object.keys(this.workers)
269 .map(handlerName => {
270 const worker: Worker = this.workers[handlerName]
271 const queue: Queue = this.queues[handlerName]
272 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
273 const queueEvent: QueueEvents = this.queueEvents[handlerName]
274
275 return Promise.all([
276 worker.close(false),
277 queue.close(),
278 queueScheduler.close(),
279 queueEvent.close()
280 ])
281 })
282
283 return Promise.all(promises)
284 }
285
286 async pause () {
287 for (const handlerName of Object.keys(this.workers)) {
288 const worker: Worker = this.workers[handlerName]
289 const queue: Queue = this.queues[handlerName]
290
291 await worker.pause()
292 await queue.pause()
293 }
294 }
295
296 async resume () {
297 for (const handlerName of Object.keys(this.workers)) {
298 const worker: Worker = this.workers[handlerName]
299 const queue: Queue = this.queues[handlerName]
300
301 worker.resume()
302 await queue.resume()
303 }
304 }
305
306 // ---------------------------------------------------------------------------
307
308 createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
309 this.createJob(options)
310 .catch(err => logger.error('Cannot create job.', { err, options }))
311 }
312
313 async createJob (options: CreateJobArgument & CreateJobOptions) {
314 const queue: Queue = this.queues[options.type]
315 if (queue === undefined) {
316 logger.error('Unknown queue %s: cannot create job.', options.type)
317 return
318 }
319
320 const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
321
322 return queue.add('job', options.payload, jobOptions)
323 }
324
325 async createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
326 let lastJob: FlowJob
327
328 for (const job of jobs) {
329 if (!job) continue
330
331 lastJob = {
332 ...this.buildJobFlowOption(job),
333
334 children: lastJob
335 ? [ lastJob ]
336 : []
337 }
338 }
339
340 return this.flowProducer.add(lastJob)
341 }
342
343 async createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) {
344 return this.flowProducer.add({
345 ...this.buildJobFlowOption(parent),
346
347 children: children.map(c => this.buildJobFlowOption(c))
348 })
349 }
350
351 private buildJobFlowOption (job: CreateJobArgument & CreateJobOptions) {
352 return {
353 name: 'job',
354 data: job.payload,
355 queueName: job.type,
356 opts: this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay' ]))
357 }
358 }
359
360 private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
361 return {
362 backoff: { delay: 60 * 1000, type: 'exponential' },
363 attempts: JOB_ATTEMPTS[type],
364 priority: options.priority,
365 delay: options.delay
366 }
367 }
368
369 // ---------------------------------------------------------------------------
370
371 async listForApi (options: {
372 state?: JobState
373 start: number
374 count: number
375 asc?: boolean
376 jobType: JobType
377 }): Promise<Job[]> {
378 const { state, start, count, asc, jobType } = options
379
380 const states = this.buildStateFilter(state)
381 const filteredJobTypes = this.buildTypeFilter(jobType)
382
383 let results: Job[] = []
384
385 for (const jobType of filteredJobTypes) {
386 const queue: Queue = this.queues[jobType]
387
388 if (queue === undefined) {
389 logger.error('Unknown queue %s to list jobs.', jobType)
390 continue
391 }
392
393 const jobs = await queue.getJobs(states, 0, start + count, asc)
394 results = results.concat(jobs)
395 }
396
397 results.sort((j1: any, j2: any) => {
398 if (j1.timestamp < j2.timestamp) return -1
399 else if (j1.timestamp === j2.timestamp) return 0
400
401 return 1
402 })
403
404 if (asc === false) results.reverse()
405
406 return results.slice(start, start + count)
407 }
408
409 async count (state: JobState, jobType?: JobType): Promise<number> {
410 const states = state ? [ state ] : jobStates
411 const filteredJobTypes = this.buildTypeFilter(jobType)
412
413 let total = 0
414
415 for (const type of filteredJobTypes) {
416 const queue = this.queues[type]
417 if (queue === undefined) {
418 logger.error('Unknown queue %s to count jobs.', type)
419 continue
420 }
421
422 const counts = await queue.getJobCounts()
423
424 for (const s of states) {
425 total += counts[s]
426 }
427 }
428
429 return total
430 }
431
432 private buildStateFilter (state?: JobState) {
433 if (!state) return jobStates
434
435 const states = [ state ]
436
437 // Include parent if filtering on waiting
438 if (state === 'waiting') states.push('waiting-children')
439
440 return states
441 }
442
443 private buildTypeFilter (jobType?: JobType) {
444 if (!jobType) return jobTypes
445
446 return jobTypes.filter(t => t === jobType)
447 }
448
449 async getStats () {
450 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
451
452 return Promise.all(promises)
453 }
454
455 // ---------------------------------------------------------------------------
456
457 async removeOldJobs () {
458 for (const key of Object.keys(this.queues)) {
459 const queue: Queue = this.queues[key]
460 await queue.clean(JOB_COMPLETED_LIFETIME, 100, 'completed')
461 }
462 }
463
464 private addRepeatableJobs () {
465 this.queues['videos-views-stats'].add('job', {}, {
466 repeat: REPEAT_JOBS['videos-views-stats']
467 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
468
469 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
470 this.queues['activitypub-cleaner'].add('job', {}, {
471 repeat: REPEAT_JOBS['activitypub-cleaner']
472 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
473 }
474 }
475
476 private getJobConcurrency (jobType: JobType) {
477 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
478 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
479
480 return JOB_CONCURRENCY[jobType]
481 }
482
483 static get Instance () {
484 return this.instance || (this.instance = new this())
485 }
486 }
487
488 // ---------------------------------------------------------------------------
489
490 export {
491 jobTypes,
492 JobQueue
493 }