Graceful job queue shutdown
[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     }
69
70     for (const handlerName of Object.keys(handlers)) {
71       const queue = new Bull(handlerName, queueOptions)
72       const handler = handlers[handlerName]
73
74       queue.process(JOB_CONCURRENCY[handlerName], handler)
75         .catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
76
77       queue.on('error', err => {
78         logger.error('Error in job queue %s.', handlerName, { err })
79         process.exit(-1)
80       })
81
82       this.queues[handlerName] = queue
83     }
84   }
85
86   terminate () {
87     for (const queueName of Object.keys(this.queues)) {
88       const queue = this.queues[queueName]
89       queue.close()
90     }
91   }
92
93   createJob (obj: CreateJobArgument) {
94     const queue = this.queues[obj.type]
95     if (queue === undefined) {
96       logger.error('Unknown queue %s: cannot create job.', obj.type)
97       throw Error('Unknown queue, cannot create job')
98     }
99
100     const jobArgs: Bull.JobOptions = {
101       backoff: { delay: 60 * 1000, type: 'exponential' },
102       attempts: JOB_ATTEMPTS[obj.type]
103     }
104
105     if (jobsWithRequestTimeout[obj.type] === true) {
106       jobArgs.timeout = JOB_REQUEST_TTL
107     }
108
109     return queue.add(obj.payload, jobArgs)
110   }
111
112   async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
113     let results: Bull.Job[] = []
114
115     // TODO: optimize
116     for (const jobType of jobTypes) {
117       const queue = this.queues[ jobType ]
118       if (queue === undefined) {
119         logger.error('Unknown queue %s to list jobs.', jobType)
120         continue
121       }
122
123       // FIXME: Bull queue typings does not have getJobs method
124       const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
125       results = results.concat(jobs)
126     }
127
128     results.sort((j1: any, j2: any) => {
129       if (j1.timestamp < j2.timestamp) return -1
130       else if (j1.timestamp === j2.timestamp) return 0
131
132       return 1
133     })
134
135     if (asc === false) results.reverse()
136
137     return results.slice(start, start + count)
138   }
139
140   async count (state: JobState): Promise<number> {
141     let total = 0
142
143     for (const type of jobTypes) {
144       const queue = this.queues[ type ]
145       if (queue === undefined) {
146         logger.error('Unknown queue %s to count jobs.', type)
147         continue
148       }
149
150       const counts = await queue.getJobCounts()
151
152       total += counts[ state ]
153     }
154
155     return total
156   }
157
158   removeOldJobs () {
159     for (const key of Object.keys(this.queues)) {
160       const queue = this.queues[key]
161       queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
162     }
163   }
164
165   static get Instance () {
166     return this.instance || (this.instance = new this())
167   }
168 }
169
170 // ---------------------------------------------------------------------------
171
172 export {
173   JobQueue
174 }