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