Don't notify on muted instance
[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.getRedisClientOptions(),
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 (options: {
125     state: JobState,
126     start: number,
127     count: number,
128     asc?: boolean,
129     jobType: JobType
130   }): Promise<Bull.Job[]> {
131     const { state, start, count, asc, jobType } = options
132     let results: Bull.Job[] = []
133
134     const filteredJobTypes = this.filterJobTypes(jobType)
135
136     // TODO: optimize
137     for (const jobType of filteredJobTypes) {
138       const queue = this.queues[ jobType ]
139       if (queue === undefined) {
140         logger.error('Unknown queue %s to list jobs.', jobType)
141         continue
142       }
143
144       // FIXME: Bull queue typings does not have getJobs method
145       const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
146       results = results.concat(jobs)
147     }
148
149     results.sort((j1: any, j2: any) => {
150       if (j1.timestamp < j2.timestamp) return -1
151       else if (j1.timestamp === j2.timestamp) return 0
152
153       return 1
154     })
155
156     if (asc === false) results.reverse()
157
158     return results.slice(start, start + count)
159   }
160
161   async count (state: JobState, jobType?: JobType): Promise<number> {
162     let total = 0
163
164     const filteredJobTypes = this.filterJobTypes(jobType)
165
166     for (const type of filteredJobTypes) {
167       const queue = this.queues[ type ]
168       if (queue === undefined) {
169         logger.error('Unknown queue %s to count jobs.', type)
170         continue
171       }
172
173       const counts = await queue.getJobCounts()
174
175       total += counts[ state ]
176     }
177
178     return total
179   }
180
181   async removeOldJobs () {
182     for (const key of Object.keys(this.queues)) {
183       const queue = this.queues[key]
184       await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
185     }
186   }
187
188   private addRepeatableJobs () {
189     this.queues['videos-views'].add({}, {
190       repeat: REPEAT_JOBS['videos-views']
191     })
192   }
193
194   private filterJobTypes (jobType?: JobType) {
195     if (!jobType) return jobTypes
196
197     return jobTypes.filter(t => t === jobType)
198   }
199
200   static get Instance () {
201     return this.instance || (this.instance = new this())
202   }
203 }
204
205 // ---------------------------------------------------------------------------
206
207 export {
208   jobTypes,
209   JobQueue
210 }