]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/job-queue.ts
Add more info logging
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
CommitLineData
94831479 1import * as Bull from 'bull'
628d28e8 2import { JobState, JobType } from '../../../shared/models'
94a5ff8a 3import { logger } from '../../helpers/logger'
19f7b248 4import { Redis } from '../redis'
71e3dfda 5import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
94a5ff8a
C
6import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
7import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
8import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
ecb4e35f 9import { EmailPayload, processEmail } from './handlers/email'
94831479 10import { processVideoFile, processVideoFileImport, VideoFileImportPayload, VideoFilePayload } from './handlers/video-file'
5350fd8e 11import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
94a5ff8a
C
12
13type CreateJobArgument =
14 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
15 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
16 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
5350fd8e 17 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
28be8916 18 { type: 'video-file-import', payload: VideoFileImportPayload } |
ecb4e35f
C
19 { type: 'video-file', payload: VideoFilePayload } |
20 { type: 'email', payload: EmailPayload }
94a5ff8a 21
94831479 22const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
94a5ff8a
C
23 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
24 'activitypub-http-unicast': processActivityPubHttpUnicast,
25 'activitypub-http-fetcher': processActivityPubHttpFetcher,
5350fd8e 26 'activitypub-follow': processActivityPubFollow,
28be8916 27 'video-file-import': processVideoFileImport,
ecb4e35f
C
28 'video-file': processVideoFile,
29 'email': processEmail
94a5ff8a
C
30}
31
94831479
C
32const jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
33 'activitypub-http-broadcast': true,
34 'activitypub-http-unicast': true,
35 'activitypub-http-fetcher': true,
36 'activitypub-follow': true
37}
38
39const jobTypes: JobType[] = [
40 'activitypub-follow',
71e3dfda 41 'activitypub-http-broadcast',
71e3dfda 42 'activitypub-http-fetcher',
94831479
C
43 'activitypub-http-unicast',
44 'email',
45 'video-file',
46 'video-file-import'
71e3dfda
C
47]
48
94a5ff8a
C
49class JobQueue {
50
51 private static instance: JobQueue
52
94831479 53 private queues: { [ id in JobType ]?: Bull.Queue } = {}
94a5ff8a 54 private initialized = false
2c29ad4f 55 private jobRedisPrefix: string
94a5ff8a
C
56
57 private constructor () {}
58
3df45638 59 async init () {
94a5ff8a
C
60 // Already initialized
61 if (this.initialized === true) return
62 this.initialized = true
63
94831479
C
64 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
65 const queueOptions = {
2c29ad4f 66 prefix: this.jobRedisPrefix,
19f7b248 67 redis: Redis.getRedisClient()
94831479 68 }
ecb4e35f 69
94831479
C
70 for (const handlerName of Object.keys(handlers)) {
71 const queue = new Bull(handlerName, queueOptions)
72 const handler = handlers[handlerName]
94a5ff8a 73
94831479
C
74 queue.process(JOB_CONCURRENCY[handlerName], handler)
75 .catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
3df45638 76
94831479
C
77 queue.on('error', err => {
78 logger.error('Error in job queue %s.', handlerName, { err })
79 process.exit(-1)
94a5ff8a 80 })
94831479
C
81
82 this.queues[handlerName] = queue
94a5ff8a
C
83 }
84 }
85
94831479
C
86 createJob (obj: CreateJobArgument) {
87 const queue = this.queues[obj.type]
88 if (queue === undefined) {
89 logger.error('Unknown queue %s: cannot create job.', obj.type)
c1e791ba 90 throw Error('Unknown queue, cannot create job')
94831479 91 }
94a5ff8a 92
94831479
C
93 const jobArgs: Bull.JobOptions = {
94 backoff: { delay: 60 * 1000, type: 'exponential' },
95 attempts: JOB_ATTEMPTS[obj.type]
96 }
71e3dfda 97
94831479
C
98 if (jobsWithRequestTimeout[obj.type] === true) {
99 jobArgs.timeout = JOB_REQUEST_TTL
100 }
71e3dfda 101
94831479 102 return queue.add(obj.payload, jobArgs)
94a5ff8a
C
103 }
104
94831479
C
105 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
106 let results: Bull.Job[] = []
94a5ff8a 107
94831479
C
108 // TODO: optimize
109 for (const jobType of jobTypes) {
110 const queue = this.queues[ jobType ]
111 if (queue === undefined) {
112 logger.error('Unknown queue %s to list jobs.', jobType)
113 continue
114 }
2c29ad4f 115
94831479
C
116 // FIXME: Bull queue typings does not have getJobs method
117 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
118 results = results.concat(jobs)
119 }
94a5ff8a 120
94831479
C
121 results.sort((j1: any, j2: any) => {
122 if (j1.timestamp < j2.timestamp) return -1
123 else if (j1.timestamp === j2.timestamp) return 0
94a5ff8a 124
94831479 125 return 1
94a5ff8a 126 })
94a5ff8a 127
94831479 128 if (asc === false) results.reverse()
94a5ff8a 129
94831479 130 return results.slice(start, start + count)
94a5ff8a
C
131 }
132
94831479
C
133 async count (state: JobState): Promise<number> {
134 let total = 0
3df45638 135
94831479
C
136 for (const type of jobTypes) {
137 const queue = this.queues[ type ]
138 if (queue === undefined) {
139 logger.error('Unknown queue %s to count jobs.', type)
140 continue
141 }
3df45638 142
94831479 143 const counts = await queue.getJobCounts()
3df45638 144
94831479
C
145 total += counts[ state ]
146 }
3df45638 147
94831479 148 return total
3df45638
C
149 }
150
94831479
C
151 removeOldJobs () {
152 for (const key of Object.keys(this.queues)) {
153 const queue = this.queues[key]
154 queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
155 }
2c29ad4f
C
156 }
157
94a5ff8a
C
158 static get Instance () {
159 return this.instance || (this.instance = new this())
160 }
161}
162
163// ---------------------------------------------------------------------------
164
165export {
166 JobQueue
167}