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