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