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