]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/job-queue.ts
Update validator dependency
[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'
74dc3bca 5import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
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'
30842128 10import { processVideoTranscoding, VideoTranscodingPayload } from './handlers/video-transcoding'
5350fd8e 11import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
fbad87b0 12import { processVideoImport, VideoImportPayload } from './handlers/video-import'
030177d2 13import { processVideosViews } from './handlers/video-views'
04b8c3fb 14import { refreshAPObject, RefreshPayload } from './handlers/activitypub-refresher'
30842128 15import { processVideoFileImport, VideoFileImportPayload } from './handlers/video-file-import'
94a5ff8a
C
16
17type CreateJobArgument =
18 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
19 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
20 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
5350fd8e 21 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
28be8916 22 { type: 'video-file-import', payload: VideoFileImportPayload } |
a0327eed 23 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
fbad87b0 24 { type: 'email', payload: EmailPayload } |
6b616860 25 { type: 'video-import', payload: VideoImportPayload } |
04b8c3fb 26 { type: 'activitypub-refresher', payload: RefreshPayload } |
6b616860 27 { type: 'videos-views', payload: {} }
94a5ff8a 28
a0327eed 29const handlers: { [ id in (JobType | 'video-file') ]: (job: Bull.Job) => Promise<any>} = {
94a5ff8a
C
30 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
31 'activitypub-http-unicast': processActivityPubHttpUnicast,
32 'activitypub-http-fetcher': processActivityPubHttpFetcher,
5350fd8e 33 'activitypub-follow': processActivityPubFollow,
28be8916 34 'video-file-import': processVideoFileImport,
a0327eed
C
35 'video-transcoding': processVideoTranscoding,
36 'video-file': processVideoTranscoding, // TODO: remove it (changed in 1.3)
fbad87b0 37 'email': processEmail,
6b616860 38 'video-import': processVideoImport,
04b8c3fb
C
39 'videos-views': processVideosViews,
40 'activitypub-refresher': refreshAPObject
94a5ff8a
C
41}
42
94831479
C
43const jobTypes: JobType[] = [
44 'activitypub-follow',
71e3dfda 45 'activitypub-http-broadcast',
71e3dfda 46 'activitypub-http-fetcher',
94831479
C
47 'activitypub-http-unicast',
48 'email',
a0327eed 49 'video-transcoding',
fbad87b0 50 'video-file-import',
6b616860 51 'video-import',
04b8c3fb
C
52 'videos-views',
53 'activitypub-refresher'
71e3dfda
C
54]
55
94a5ff8a
C
56class JobQueue {
57
58 private static instance: JobQueue
59
94831479 60 private queues: { [ id in JobType ]?: Bull.Queue } = {}
94a5ff8a 61 private initialized = false
2c29ad4f 62 private jobRedisPrefix: string
94a5ff8a
C
63
64 private constructor () {}
65
3df45638 66 async init () {
94a5ff8a
C
67 // Already initialized
68 if (this.initialized === true) return
69 this.initialized = true
70
6dd9de95 71 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
94831479 72 const queueOptions = {
2c29ad4f 73 prefix: this.jobRedisPrefix,
47f6409b 74 redis: Redis.getRedisClientOptions(),
4a9e71c2
C
75 settings: {
76 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
77 }
94831479 78 }
ecb4e35f 79
94831479
C
80 for (const handlerName of Object.keys(handlers)) {
81 const queue = new Bull(handlerName, queueOptions)
82 const handler = handlers[handlerName]
94a5ff8a 83
94831479 84 queue.process(JOB_CONCURRENCY[handlerName], handler)
2b86fe72 85 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
d7f83948
C
86
87 queue.on('failed', (job, err) => {
88 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
89 })
3df45638 90
94831479
C
91 queue.on('error', err => {
92 logger.error('Error in job queue %s.', handlerName, { err })
94a5ff8a 93 })
94831479
C
94
95 this.queues[handlerName] = queue
94a5ff8a 96 }
6b616860
C
97
98 this.addRepeatableJobs()
94a5ff8a
C
99 }
100
14f2b3ad
C
101 terminate () {
102 for (const queueName of Object.keys(this.queues)) {
103 const queue = this.queues[queueName]
104 queue.close()
105 }
106 }
107
94831479
C
108 createJob (obj: CreateJobArgument) {
109 const queue = this.queues[obj.type]
110 if (queue === undefined) {
111 logger.error('Unknown queue %s: cannot create job.', obj.type)
c1e791ba 112 throw Error('Unknown queue, cannot create job')
94831479 113 }
94a5ff8a 114
94831479
C
115 const jobArgs: Bull.JobOptions = {
116 backoff: { delay: 60 * 1000, type: 'exponential' },
2b86fe72
C
117 attempts: JOB_ATTEMPTS[obj.type],
118 timeout: JOB_TTL[obj.type]
94831479 119 }
71e3dfda 120
94831479 121 return queue.add(obj.payload, jobArgs)
94a5ff8a
C
122 }
123
1061c73f
C
124 async listForApi (options: {
125 state: JobState,
126 start: number,
127 count: number,
128 asc?: boolean,
129 jobType: JobType
130 }): Promise<Bull.Job[]> {
131 const { state, start, count, asc, jobType } = options
94831479 132 let results: Bull.Job[] = []
94a5ff8a 133
1061c73f
C
134 const filteredJobTypes = this.filterJobTypes(jobType)
135
94831479 136 // TODO: optimize
1061c73f 137 for (const jobType of filteredJobTypes) {
94831479
C
138 const queue = this.queues[ jobType ]
139 if (queue === undefined) {
140 logger.error('Unknown queue %s to list jobs.', jobType)
141 continue
142 }
2c29ad4f 143
94831479
C
144 // FIXME: Bull queue typings does not have getJobs method
145 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
146 results = results.concat(jobs)
147 }
94a5ff8a 148
94831479
C
149 results.sort((j1: any, j2: any) => {
150 if (j1.timestamp < j2.timestamp) return -1
151 else if (j1.timestamp === j2.timestamp) return 0
94a5ff8a 152
94831479 153 return 1
94a5ff8a 154 })
94a5ff8a 155
94831479 156 if (asc === false) results.reverse()
94a5ff8a 157
94831479 158 return results.slice(start, start + count)
94a5ff8a
C
159 }
160
1061c73f 161 async count (state: JobState, jobType?: JobType): Promise<number> {
94831479 162 let total = 0
3df45638 163
1061c73f
C
164 const filteredJobTypes = this.filterJobTypes(jobType)
165
166 for (const type of filteredJobTypes) {
94831479
C
167 const queue = this.queues[ type ]
168 if (queue === undefined) {
169 logger.error('Unknown queue %s to count jobs.', type)
170 continue
171 }
3df45638 172
94831479 173 const counts = await queue.getJobCounts()
3df45638 174
94831479
C
175 total += counts[ state ]
176 }
3df45638 177
94831479 178 return total
3df45638
C
179 }
180
2f5c6b2f 181 async removeOldJobs () {
94831479
C
182 for (const key of Object.keys(this.queues)) {
183 const queue = this.queues[key]
2f5c6b2f 184 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
94831479 185 }
2c29ad4f
C
186 }
187
6b616860
C
188 private addRepeatableJobs () {
189 this.queues['videos-views'].add({}, {
190 repeat: REPEAT_JOBS['videos-views']
191 })
192 }
193
1061c73f
C
194 private filterJobTypes (jobType?: JobType) {
195 if (!jobType) return jobTypes
196
197 return jobTypes.filter(t => t === jobType)
198 }
199
94a5ff8a
C
200 static get Instance () {
201 return this.instance || (this.instance = new this())
202 }
203}
204
205// ---------------------------------------------------------------------------
206
207export {
1061c73f 208 jobTypes,
94a5ff8a
C
209 JobQueue
210}