8ff0c169e092276543b2eaa5dfbaf6aa12906787
[oweals/peertube.git] / server / lib / job-queue / job-queue.ts
1 import * as Bull from 'bull'
2 import { JobState, JobType } from '../../../shared/models'
3 import { logger } from '../../helpers/logger'
4 import { Redis } from '../redis'
5 import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
6 import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
7 import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
8 import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
9 import { EmailPayload, processEmail } from './handlers/email'
10 import { processVideoFile, processVideoFileImport, VideoFileImportPayload, VideoFilePayload } from './handlers/video-file'
11 import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
12
13 type CreateJobArgument =
14   { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
15   { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
16   { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
17   { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
18   { type: 'video-file-import', payload: VideoFileImportPayload } |
19   { type: 'video-file', payload: VideoFilePayload } |
20   { type: 'email', payload: EmailPayload }
21
22 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
23   'activitypub-http-broadcast': processActivityPubHttpBroadcast,
24   'activitypub-http-unicast': processActivityPubHttpUnicast,
25   'activitypub-http-fetcher': processActivityPubHttpFetcher,
26   'activitypub-follow': processActivityPubFollow,
27   'video-file-import': processVideoFileImport,
28   'video-file': processVideoFile,
29   'email': processEmail
30 }
31
32 const jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
33   'activitypub-http-broadcast': true,
34   'activitypub-http-unicast': true,
35   'activitypub-http-fetcher': true,
36   'activitypub-follow': true
37 }
38
39 const jobTypes: JobType[] = [
40   'activitypub-follow',
41   'activitypub-http-broadcast',
42   'activitypub-http-fetcher',
43   'activitypub-http-unicast',
44   'email',
45   'video-file',
46   'video-file-import'
47 ]
48
49 class JobQueue {
50
51   private static instance: JobQueue
52
53   private queues: { [ id in JobType ]?: Bull.Queue } = {}
54   private initialized = false
55   private jobRedisPrefix: string
56
57   private constructor () {}
58
59   async init () {
60     // Already initialized
61     if (this.initialized === true) return
62     this.initialized = true
63
64     this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
65     const queueOptions = {
66       prefix: this.jobRedisPrefix,
67       redis: Redis.getRedisClient(),
68       settings: {
69         maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
70       }
71     }
72
73     for (const handlerName of Object.keys(handlers)) {
74       const queue = new Bull(handlerName, queueOptions)
75       const handler = handlers[handlerName]
76
77       queue.process(JOB_CONCURRENCY[handlerName], handler)
78         .catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
79
80       queue.on('error', err => {
81         logger.error('Error in job queue %s.', handlerName, { err })
82         process.exit(-1)
83       })
84
85       this.queues[handlerName] = queue
86     }
87   }
88
89   terminate () {
90     for (const queueName of Object.keys(this.queues)) {
91       const queue = this.queues[queueName]
92       queue.close()
93     }
94   }
95
96   createJob (obj: CreateJobArgument) {
97     const queue = this.queues[obj.type]
98     if (queue === undefined) {
99       logger.error('Unknown queue %s: cannot create job.', obj.type)
100       throw Error('Unknown queue, cannot create job')
101     }
102
103     const jobArgs: Bull.JobOptions = {
104       backoff: { delay: 60 * 1000, type: 'exponential' },
105       attempts: JOB_ATTEMPTS[obj.type]
106     }
107
108     if (jobsWithRequestTimeout[obj.type] === true) {
109       jobArgs.timeout = JOB_REQUEST_TTL
110     }
111
112     return queue.add(obj.payload, jobArgs)
113   }
114
115   async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
116     let results: Bull.Job[] = []
117
118     // TODO: optimize
119     for (const jobType of jobTypes) {
120       const queue = this.queues[ jobType ]
121       if (queue === undefined) {
122         logger.error('Unknown queue %s to list jobs.', jobType)
123         continue
124       }
125
126       // FIXME: Bull queue typings does not have getJobs method
127       const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
128       results = results.concat(jobs)
129     }
130
131     results.sort((j1: any, j2: any) => {
132       if (j1.timestamp < j2.timestamp) return -1
133       else if (j1.timestamp === j2.timestamp) return 0
134
135       return 1
136     })
137
138     if (asc === false) results.reverse()
139
140     return results.slice(start, start + count)
141   }
142
143   async count (state: JobState): Promise<number> {
144     let total = 0
145
146     for (const type of jobTypes) {
147       const queue = this.queues[ type ]
148       if (queue === undefined) {
149         logger.error('Unknown queue %s to count jobs.', type)
150         continue
151       }
152
153       const counts = await queue.getJobCounts()
154
155       total += counts[ state ]
156     }
157
158     return total
159   }
160
161   removeOldJobs () {
162     for (const key of Object.keys(this.queues)) {
163       const queue = this.queues[key]
164       queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
165     }
166   }
167
168   static get Instance () {
169     return this.instance || (this.instance = new this())
170   }
171 }
172
173 // ---------------------------------------------------------------------------
174
175 export {
176   JobQueue
177 }