]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/job-queue.ts
Implement avatar miniatures (#4639)
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
CommitLineData
41fb13c3 1import Bull, { Job, JobOptions, Queue } from 'bull'
402145b8 2import { jobStates } from '@server/helpers/custom-validators/jobs'
9129b769 3import { CONFIG } from '@server/initializers/config'
402145b8 4import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
8dc8a34e
C
5import {
6 ActivitypubFollowPayload,
7 ActivitypubHttpBroadcastPayload,
e1c55031
C
8 ActivitypubHttpFetcherPayload,
9 ActivitypubHttpUnicastPayload,
8795d6f2 10 ActorKeysPayload,
276250f0 11 DeleteResumableUploadMetaFilePayload,
e1c55031 12 EmailPayload,
8dc8a34e 13 JobState,
e1c55031 14 JobType,
0305db28 15 MoveObjectStoragePayload,
e1c55031
C
16 RefreshPayload,
17 VideoFileImportPayload,
18 VideoImportPayload,
a5cf76af 19 VideoLiveEndingPayload,
e1c55031
C
20 VideoRedundancyPayload,
21 VideoTranscodingPayload
8dc8a34e 22} from '../../../shared/models'
94a5ff8a 23import { logger } from '../../helpers/logger'
74dc3bca 24import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
74d249bc 25import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
402145b8 26import { processActivityPubFollow } from './handlers/activitypub-follow'
8dc8a34e
C
27import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
28import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
29import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
e1c55031 30import { refreshAPObject } from './handlers/activitypub-refresher'
8795d6f2 31import { processActorKeys } from './handlers/actor-keys'
402145b8 32import { processEmail } from './handlers/email'
41fb13c3 33import { processMoveToObjectStorage } from './handlers/move-to-object-storage'
e1c55031 34import { processVideoFileImport } from './handlers/video-file-import'
402145b8 35import { processVideoImport } from './handlers/video-import'
a5cf76af 36import { processVideoLiveEnding } from './handlers/video-live-ending'
402145b8 37import { processVideoTranscoding } from './handlers/video-transcoding'
51353d9a 38import { processVideosViewsStats } from './handlers/video-views-stats'
94a5ff8a
C
39
40type CreateJobArgument =
41 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
42 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
43 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
74d249bc 44 { type: 'activitypub-http-cleaner', payload: {} } |
5350fd8e 45 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
28be8916 46 { type: 'video-file-import', payload: VideoFileImportPayload } |
a0327eed 47 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
fbad87b0 48 { type: 'email', payload: EmailPayload } |
6b616860 49 { type: 'video-import', payload: VideoImportPayload } |
04b8c3fb 50 { type: 'activitypub-refresher', payload: RefreshPayload } |
51353d9a 51 { type: 'videos-views-stats', payload: {} } |
a5cf76af 52 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
8795d6f2 53 { type: 'actor-keys', payload: ActorKeysPayload } |
0305db28 54 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
276250f0 55 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
0305db28 56 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
94a5ff8a 57
0305db28 58export type CreateJobOptions = {
a5cf76af 59 delay?: number
77d7e851 60 priority?: number
a5cf76af
C
61}
62
41fb13c3 63const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
94a5ff8a
C
64 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
65 'activitypub-http-unicast': processActivityPubHttpUnicast,
66 'activitypub-http-fetcher': processActivityPubHttpFetcher,
74d249bc 67 'activitypub-cleaner': processActivityPubCleaner,
5350fd8e 68 'activitypub-follow': processActivityPubFollow,
28be8916 69 'video-file-import': processVideoFileImport,
a0327eed 70 'video-transcoding': processVideoTranscoding,
fbad87b0 71 'email': processEmail,
6b616860 72 'video-import': processVideoImport,
51353d9a 73 'videos-views-stats': processVideosViewsStats,
b764380a 74 'activitypub-refresher': refreshAPObject,
a5cf76af 75 'video-live-ending': processVideoLiveEnding,
8795d6f2 76 'actor-keys': processActorKeys,
0305db28
JB
77 'video-redundancy': processVideoRedundancy,
78 'move-to-object-storage': processMoveToObjectStorage
94a5ff8a
C
79}
80
94831479
C
81const jobTypes: JobType[] = [
82 'activitypub-follow',
71e3dfda 83 'activitypub-http-broadcast',
71e3dfda 84 'activitypub-http-fetcher',
94831479 85 'activitypub-http-unicast',
74d249bc 86 'activitypub-cleaner',
94831479 87 'email',
a0327eed 88 'video-transcoding',
fbad87b0 89 'video-file-import',
6b616860 90 'video-import',
51353d9a 91 'videos-views-stats',
b764380a 92 'activitypub-refresher',
a5cf76af 93 'video-redundancy',
8795d6f2 94 'actor-keys',
0305db28
JB
95 'video-live-ending',
96 'move-to-object-storage'
71e3dfda
C
97]
98
94a5ff8a
C
99class JobQueue {
100
101 private static instance: JobQueue
102
41fb13c3 103 private queues: { [id in JobType]?: Queue } = {}
94a5ff8a 104 private initialized = false
2c29ad4f 105 private jobRedisPrefix: string
94a5ff8a 106
a1587156
C
107 private constructor () {
108 }
94a5ff8a 109
e1ab52d7 110 init (produceOnly = false) {
94a5ff8a
C
111 // Already initialized
112 if (this.initialized === true) return
113 this.initialized = true
114
6dd9de95 115 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
ff4d2c73
C
116
117 const queueOptions: Bull.QueueOptions = {
2c29ad4f 118 prefix: this.jobRedisPrefix,
ff4d2c73
C
119 redis: {
120 password: CONFIG.REDIS.AUTH,
121 db: CONFIG.REDIS.DB,
122 host: CONFIG.REDIS.HOSTNAME,
123 port: CONFIG.REDIS.PORT,
124 path: CONFIG.REDIS.SOCKET
125 },
4a9e71c2
C
126 settings: {
127 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
128 }
94831479 129 }
ecb4e35f 130
9129b769 131 for (const handlerName of (Object.keys(handlers) as JobType[])) {
94831479 132 const queue = new Bull(handlerName, queueOptions)
e1ab52d7 133
134 if (produceOnly) {
135 queue.pause(true)
136 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
137 }
138
94831479 139 const handler = handlers[handlerName]
94a5ff8a 140
9129b769 141 queue.process(this.getJobConcurrency(handlerName), handler)
2b86fe72 142 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
d7f83948
C
143
144 queue.on('failed', (job, err) => {
145 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
146 })
3df45638 147
94831479
C
148 queue.on('error', err => {
149 logger.error('Error in job queue %s.', handlerName, { err })
94a5ff8a 150 })
94831479
C
151
152 this.queues[handlerName] = queue
94a5ff8a 153 }
6b616860
C
154
155 this.addRepeatableJobs()
94a5ff8a
C
156 }
157
14f2b3ad
C
158 terminate () {
159 for (const queueName of Object.keys(this.queues)) {
160 const queue = this.queues[queueName]
161 queue.close()
162 }
163 }
164
419b520c
C
165 async pause () {
166 for (const handler of Object.keys(this.queues)) {
167 await this.queues[handler].pause(true)
168 }
169 }
170
171 async resume () {
172 for (const handler of Object.keys(this.queues)) {
173 await this.queues[handler].resume(true)
174 }
175 }
176
a5cf76af
C
177 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
178 this.createJobWithPromise(obj, options)
e1c55031 179 .catch(err => logger.error('Cannot create job.', { err, obj }))
a1587156
C
180 }
181
a5cf76af 182 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
94831479
C
183 const queue = this.queues[obj.type]
184 if (queue === undefined) {
185 logger.error('Unknown queue %s: cannot create job.', obj.type)
a1587156 186 return
94831479 187 }
94a5ff8a 188
41fb13c3 189 const jobArgs: JobOptions = {
94831479 190 backoff: { delay: 60 * 1000, type: 'exponential' },
2b86fe72 191 attempts: JOB_ATTEMPTS[obj.type],
a5cf76af 192 timeout: JOB_TTL[obj.type],
77d7e851 193 priority: options.priority,
a5cf76af 194 delay: options.delay
94831479 195 }
71e3dfda 196
94831479 197 return queue.add(obj.payload, jobArgs)
94a5ff8a
C
198 }
199
1061c73f 200 async listForApi (options: {
402145b8 201 state?: JobState
a1587156
C
202 start: number
203 count: number
204 asc?: boolean
1061c73f 205 jobType: JobType
41fb13c3 206 }): Promise<Job[]> {
402145b8
C
207 const { state, start, count, asc, jobType } = options
208
209 const states = state ? [ state ] : jobStates
41fb13c3 210 let results: Job[] = []
94a5ff8a 211
1061c73f
C
212 const filteredJobTypes = this.filterJobTypes(jobType)
213
1061c73f 214 for (const jobType of filteredJobTypes) {
a1587156 215 const queue = this.queues[jobType]
94831479
C
216 if (queue === undefined) {
217 logger.error('Unknown queue %s to list jobs.', jobType)
218 continue
219 }
2c29ad4f 220
402145b8 221 const jobs = await queue.getJobs(states, 0, start + count, asc)
94831479
C
222 results = results.concat(jobs)
223 }
94a5ff8a 224
94831479
C
225 results.sort((j1: any, j2: any) => {
226 if (j1.timestamp < j2.timestamp) return -1
227 else if (j1.timestamp === j2.timestamp) return 0
94a5ff8a 228
94831479 229 return 1
94a5ff8a 230 })
94a5ff8a 231
94831479 232 if (asc === false) results.reverse()
94a5ff8a 233
94831479 234 return results.slice(start, start + count)
94a5ff8a
C
235 }
236
402145b8
C
237 async count (state: JobState, jobType?: JobType): Promise<number> {
238 const states = state ? [ state ] : jobStates
94831479 239 let total = 0
3df45638 240
1061c73f
C
241 const filteredJobTypes = this.filterJobTypes(jobType)
242
243 for (const type of filteredJobTypes) {
a1587156 244 const queue = this.queues[type]
94831479
C
245 if (queue === undefined) {
246 logger.error('Unknown queue %s to count jobs.', type)
247 continue
248 }
3df45638 249
94831479 250 const counts = await queue.getJobCounts()
3df45638 251
040d6896
RK
252 for (const s of states) {
253 total += counts[s]
254 }
94831479 255 }
3df45638 256
94831479 257 return total
3df45638
C
258 }
259
2f5c6b2f 260 async removeOldJobs () {
94831479
C
261 for (const key of Object.keys(this.queues)) {
262 const queue = this.queues[key]
2f5c6b2f 263 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
94831479 264 }
2c29ad4f
C
265 }
266
6b616860 267 private addRepeatableJobs () {
51353d9a
C
268 this.queues['videos-views-stats'].add({}, {
269 repeat: REPEAT_JOBS['videos-views-stats']
a1587156 270 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
74d249bc
C
271
272 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
273 this.queues['activitypub-cleaner'].add({}, {
274 repeat: REPEAT_JOBS['activitypub-cleaner']
275 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
276 }
6b616860
C
277 }
278
1061c73f
C
279 private filterJobTypes (jobType?: JobType) {
280 if (!jobType) return jobTypes
281
282 return jobTypes.filter(t => t === jobType)
283 }
284
9129b769
C
285 private getJobConcurrency (jobType: JobType) {
286 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
287 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
288
289 return JOB_CONCURRENCY[jobType]
290 }
291
94a5ff8a
C
292 static get Instance () {
293 return this.instance || (this.instance = new this())
294 }
295}
296
297// ---------------------------------------------------------------------------
298
299export {
1061c73f 300 jobTypes,
94a5ff8a
C
301 JobQueue
302}