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