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