]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
5862e178f81d8b18b4c10e373b2a4b54c290b256
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
1 import * as Bull from 'bull'
2 import { JobState, JobType } from '../../../shared/models'
3 import { logger } from '../../helpers/logger'
4 import { Redis } from '../redis'
5 import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS } from '../../initializers'
6 import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
7 import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
8 import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
9 import { EmailPayload, processEmail } from './handlers/email'
10 import { processVideoFile, processVideoFileImport, VideoFileImportPayload, VideoFilePayload } from './handlers/video-file'
11 import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
12 import { processVideoImport, VideoImportPayload } from './handlers/video-import'
13 import { processVideosViews } from './handlers/video-views'
14 import { refreshAPObject, RefreshPayload } from './handlers/activitypub-refresher'
15
16 type CreateJobArgument =
17 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
18 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
19 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
20 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
21 { type: 'video-file-import', payload: VideoFileImportPayload } |
22 { type: 'video-file', payload: VideoFilePayload } |
23 { type: 'email', payload: EmailPayload } |
24 { type: 'video-import', payload: VideoImportPayload } |
25 { type: 'activitypub-refresher', payload: RefreshPayload } |
26 { type: 'videos-views', payload: {} }
27
28 const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
29 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
30 'activitypub-http-unicast': processActivityPubHttpUnicast,
31 'activitypub-http-fetcher': processActivityPubHttpFetcher,
32 'activitypub-follow': processActivityPubFollow,
33 'video-file-import': processVideoFileImport,
34 'video-file': processVideoFile,
35 'email': processEmail,
36 'video-import': processVideoImport,
37 'videos-views': processVideosViews,
38 'activitypub-refresher': refreshAPObject
39 }
40
41 const jobTypes: JobType[] = [
42 'activitypub-follow',
43 'activitypub-http-broadcast',
44 'activitypub-http-fetcher',
45 'activitypub-http-unicast',
46 'email',
47 'video-file',
48 'video-file-import',
49 'video-import',
50 'videos-views',
51 'activitypub-refresher'
52 ]
53
54 class JobQueue {
55
56 private static instance: JobQueue
57
58 private queues: { [ id in JobType ]?: Bull.Queue } = {}
59 private initialized = false
60 private jobRedisPrefix: string
61
62 private constructor () {}
63
64 async init () {
65 // Already initialized
66 if (this.initialized === true) return
67 this.initialized = true
68
69 this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
70 const queueOptions = {
71 prefix: this.jobRedisPrefix,
72 redis: Redis.getRedisClient(),
73 settings: {
74 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
75 }
76 }
77
78 for (const handlerName of Object.keys(handlers)) {
79 const queue = new Bull(handlerName, queueOptions)
80 const handler = handlers[handlerName]
81
82 queue.process(JOB_CONCURRENCY[handlerName], handler)
83 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
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 })
88
89 queue.on('error', err => {
90 logger.error('Error in job queue %s.', handlerName, { err })
91 process.exit(-1)
92 })
93
94 this.queues[handlerName] = queue
95 }
96
97 this.addRepeatableJobs()
98 }
99
100 terminate () {
101 for (const queueName of Object.keys(this.queues)) {
102 const queue = this.queues[queueName]
103 queue.close()
104 }
105 }
106
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)
111 throw Error('Unknown queue, cannot create job')
112 }
113
114 const jobArgs: Bull.JobOptions = {
115 backoff: { delay: 60 * 1000, type: 'exponential' },
116 attempts: JOB_ATTEMPTS[obj.type],
117 timeout: JOB_TTL[obj.type]
118 }
119
120 return queue.add(obj.payload, jobArgs)
121 }
122
123 async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
124 let results: Bull.Job[] = []
125
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 }
133
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 }
138
139 results.sort((j1: any, j2: any) => {
140 if (j1.timestamp < j2.timestamp) return -1
141 else if (j1.timestamp === j2.timestamp) return 0
142
143 return 1
144 })
145
146 if (asc === false) results.reverse()
147
148 return results.slice(start, start + count)
149 }
150
151 async count (state: JobState): Promise<number> {
152 let total = 0
153
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 }
160
161 const counts = await queue.getJobCounts()
162
163 total += counts[ state ]
164 }
165
166 return total
167 }
168
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 }
174 }
175
176 private addRepeatableJobs () {
177 this.queues['videos-views'].add({}, {
178 repeat: REPEAT_JOBS['videos-views']
179 })
180 }
181
182 static get Instance () {
183 return this.instance || (this.instance = new this())
184 }
185 }
186
187 // ---------------------------------------------------------------------------
188
189 export {
190 JobQueue
191 }