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