]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/job-queue.ts
Move video file import in its own file
[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'
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
94831479
C
71 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
72 const queueOptions = {
2c29ad4f 73 prefix: this.jobRedisPrefix,
4a9e71c2
C
74 redis: Redis.getRedisClient(),
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
94831479
C
124 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
125 let results: Bull.Job[] = []
94a5ff8a 126
94831479
C
127 // TODO: optimize
128 for (const jobType of jobTypes) {
129 const queue = this.queues[ jobType ]
130 if (queue === undefined) {
131 logger.error('Unknown queue %s to list jobs.', jobType)
132 continue
133 }
2c29ad4f 134
94831479
C
135 // FIXME: Bull queue typings does not have getJobs method
136 const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
137 results = results.concat(jobs)
138 }
94a5ff8a 139
94831479
C
140 results.sort((j1: any, j2: any) => {
141 if (j1.timestamp < j2.timestamp) return -1
142 else if (j1.timestamp === j2.timestamp) return 0
94a5ff8a 143
94831479 144 return 1
94a5ff8a 145 })
94a5ff8a 146
94831479 147 if (asc === false) results.reverse()
94a5ff8a 148
94831479 149 return results.slice(start, start + count)
94a5ff8a
C
150 }
151
94831479
C
152 async count (state: JobState): Promise<number> {
153 let total = 0
3df45638 154
94831479
C
155 for (const type of jobTypes) {
156 const queue = this.queues[ type ]
157 if (queue === undefined) {
158 logger.error('Unknown queue %s to count jobs.', type)
159 continue
160 }
3df45638 161
94831479 162 const counts = await queue.getJobCounts()
3df45638 163
94831479
C
164 total += counts[ state ]
165 }
3df45638 166
94831479 167 return total
3df45638
C
168 }
169
2f5c6b2f 170 async removeOldJobs () {
94831479
C
171 for (const key of Object.keys(this.queues)) {
172 const queue = this.queues[key]
2f5c6b2f 173 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
94831479 174 }
2c29ad4f
C
175 }
176
6b616860
C
177 private addRepeatableJobs () {
178 this.queues['videos-views'].add({}, {
179 repeat: REPEAT_JOBS['videos-views']
180 })
181 }
182
94a5ff8a
C
183 static get Instance () {
184 return this.instance || (this.instance = new this())
185 }
186}
187
188// ---------------------------------------------------------------------------
189
190export {
191 JobQueue
192}