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