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