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