]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
Add basic video editor support
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
1 import Bull, { Job, JobOptions, Queue } from 'bull'
2 import { jobStates } from '@server/helpers/custom-validators/jobs'
3 import { CONFIG } from '@server/initializers/config'
4 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
5 import {
6 ActivitypubFollowPayload,
7 ActivitypubHttpBroadcastPayload,
8 ActivitypubHttpFetcherPayload,
9 ActivitypubHttpUnicastPayload,
10 ActorKeysPayload,
11 DeleteResumableUploadMetaFilePayload,
12 EmailPayload,
13 JobState,
14 JobType,
15 MoveObjectStoragePayload,
16 RefreshPayload,
17 VideoEditionPayload,
18 VideoFileImportPayload,
19 VideoImportPayload,
20 VideoLiveEndingPayload,
21 VideoRedundancyPayload,
22 VideoTranscodingPayload
23 } from '../../../shared/models'
24 import { logger } from '../../helpers/logger'
25 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
26 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
27 import { processActivityPubFollow } from './handlers/activitypub-follow'
28 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
29 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
30 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
31 import { refreshAPObject } from './handlers/activitypub-refresher'
32 import { processActorKeys } from './handlers/actor-keys'
33 import { processEmail } from './handlers/email'
34 import { processMoveToObjectStorage } from './handlers/move-to-object-storage'
35 import { processVideoEdition } from './handlers/video-edition'
36 import { processVideoFileImport } from './handlers/video-file-import'
37 import { processVideoImport } from './handlers/video-import'
38 import { processVideoLiveEnding } from './handlers/video-live-ending'
39 import { processVideoTranscoding } from './handlers/video-transcoding'
40 import { processVideosViewsStats } from './handlers/video-views-stats'
41
42 type CreateJobArgument =
43 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
44 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
45 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
46 { type: 'activitypub-http-cleaner', payload: {} } |
47 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
48 { type: 'video-file-import', payload: VideoFileImportPayload } |
49 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
50 { type: 'email', payload: EmailPayload } |
51 { type: 'video-import', payload: VideoImportPayload } |
52 { type: 'activitypub-refresher', payload: RefreshPayload } |
53 { type: 'videos-views-stats', payload: {} } |
54 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
55 { type: 'actor-keys', payload: ActorKeysPayload } |
56 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
57 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
58 { type: 'video-edition', payload: VideoEditionPayload } |
59 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
60
61 export type CreateJobOptions = {
62 delay?: number
63 priority?: number
64 }
65
66 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
67 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
68 'activitypub-http-unicast': processActivityPubHttpUnicast,
69 'activitypub-http-fetcher': processActivityPubHttpFetcher,
70 'activitypub-cleaner': processActivityPubCleaner,
71 'activitypub-follow': processActivityPubFollow,
72 'video-file-import': processVideoFileImport,
73 'video-transcoding': processVideoTranscoding,
74 'email': processEmail,
75 'video-import': processVideoImport,
76 'videos-views-stats': processVideosViewsStats,
77 'activitypub-refresher': refreshAPObject,
78 'video-live-ending': processVideoLiveEnding,
79 'actor-keys': processActorKeys,
80 'video-redundancy': processVideoRedundancy,
81 'move-to-object-storage': processMoveToObjectStorage,
82 'video-edition': processVideoEdition
83 }
84
85 const jobTypes: JobType[] = [
86 'activitypub-follow',
87 'activitypub-http-broadcast',
88 'activitypub-http-fetcher',
89 'activitypub-http-unicast',
90 'activitypub-cleaner',
91 'email',
92 'video-transcoding',
93 'video-file-import',
94 'video-import',
95 'videos-views-stats',
96 'activitypub-refresher',
97 'video-redundancy',
98 'actor-keys',
99 'video-live-ending',
100 'move-to-object-storage',
101 'video-edition'
102 ]
103
104 class JobQueue {
105
106 private static instance: JobQueue
107
108 private queues: { [id in JobType]?: Queue } = {}
109 private initialized = false
110 private jobRedisPrefix: string
111
112 private constructor () {
113 }
114
115 init (produceOnly = false) {
116 // Already initialized
117 if (this.initialized === true) return
118 this.initialized = true
119
120 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
121
122 const queueOptions: Bull.QueueOptions = {
123 prefix: this.jobRedisPrefix,
124 redis: {
125 password: CONFIG.REDIS.AUTH,
126 db: CONFIG.REDIS.DB,
127 host: CONFIG.REDIS.HOSTNAME,
128 port: CONFIG.REDIS.PORT,
129 path: CONFIG.REDIS.SOCKET
130 },
131 settings: {
132 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
133 }
134 }
135
136 for (const handlerName of (Object.keys(handlers) as JobType[])) {
137 const queue = new Bull(handlerName, queueOptions)
138
139 if (produceOnly) {
140 queue.pause(true)
141 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
142 }
143
144 const handler = handlers[handlerName]
145
146 queue.process(this.getJobConcurrency(handlerName), handler)
147 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
148
149 queue.on('failed', (job, err) => {
150 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
151 })
152
153 queue.on('error', err => {
154 logger.error('Error in job queue %s.', handlerName, { err })
155 })
156
157 this.queues[handlerName] = queue
158 }
159
160 this.addRepeatableJobs()
161 }
162
163 terminate () {
164 for (const queueName of Object.keys(this.queues)) {
165 const queue = this.queues[queueName]
166 queue.close()
167 }
168 }
169
170 async pause () {
171 for (const handler of Object.keys(this.queues)) {
172 await this.queues[handler].pause(true)
173 }
174 }
175
176 async resume () {
177 for (const handler of Object.keys(this.queues)) {
178 await this.queues[handler].resume(true)
179 }
180 }
181
182 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
183 this.createJobWithPromise(obj, options)
184 .catch(err => logger.error('Cannot create job.', { err, obj }))
185 }
186
187 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
188 const queue = this.queues[obj.type]
189 if (queue === undefined) {
190 logger.error('Unknown queue %s: cannot create job.', obj.type)
191 return
192 }
193
194 const jobArgs: JobOptions = {
195 backoff: { delay: 60 * 1000, type: 'exponential' },
196 attempts: JOB_ATTEMPTS[obj.type],
197 timeout: JOB_TTL[obj.type],
198 priority: options.priority,
199 delay: options.delay
200 }
201
202 return queue.add(obj.payload, jobArgs)
203 }
204
205 async listForApi (options: {
206 state?: JobState
207 start: number
208 count: number
209 asc?: boolean
210 jobType: JobType
211 }): Promise<Job[]> {
212 const { state, start, count, asc, jobType } = options
213
214 const states = state ? [ state ] : jobStates
215 let results: Job[] = []
216
217 const filteredJobTypes = this.filterJobTypes(jobType)
218
219 for (const jobType of filteredJobTypes) {
220 const queue = this.queues[jobType]
221 if (queue === undefined) {
222 logger.error('Unknown queue %s to list jobs.', jobType)
223 continue
224 }
225
226 const jobs = await queue.getJobs(states, 0, start + count, asc)
227 results = results.concat(jobs)
228 }
229
230 results.sort((j1: any, j2: any) => {
231 if (j1.timestamp < j2.timestamp) return -1
232 else if (j1.timestamp === j2.timestamp) return 0
233
234 return 1
235 })
236
237 if (asc === false) results.reverse()
238
239 return results.slice(start, start + count)
240 }
241
242 async count (state: JobState, jobType?: JobType): Promise<number> {
243 const states = state ? [ state ] : jobStates
244 let total = 0
245
246 const filteredJobTypes = this.filterJobTypes(jobType)
247
248 for (const type of filteredJobTypes) {
249 const queue = this.queues[type]
250 if (queue === undefined) {
251 logger.error('Unknown queue %s to count jobs.', type)
252 continue
253 }
254
255 const counts = await queue.getJobCounts()
256
257 for (const s of states) {
258 total += counts[s]
259 }
260 }
261
262 return total
263 }
264
265 async removeOldJobs () {
266 for (const key of Object.keys(this.queues)) {
267 const queue = this.queues[key]
268 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
269 }
270 }
271
272 private addRepeatableJobs () {
273 this.queues['videos-views-stats'].add({}, {
274 repeat: REPEAT_JOBS['videos-views-stats']
275 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
276
277 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
278 this.queues['activitypub-cleaner'].add({}, {
279 repeat: REPEAT_JOBS['activitypub-cleaner']
280 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
281 }
282 }
283
284 private filterJobTypes (jobType?: JobType) {
285 if (!jobType) return jobTypes
286
287 return jobTypes.filter(t => t === jobType)
288 }
289
290 private getJobConcurrency (jobType: JobType) {
291 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
292 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
293
294 return JOB_CONCURRENCY[jobType]
295 }
296
297 static get Instance () {
298 return this.instance || (this.instance = new this())
299 }
300 }
301
302 // ---------------------------------------------------------------------------
303
304 export {
305 jobTypes,
306 JobQueue
307 }