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