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