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