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