]>
Commit | Line | Data |
---|---|---|
1 | import * as Bull from 'bull' | |
2 | import { jobStates } from '@server/helpers/custom-validators/jobs' | |
3 | import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy' | |
4 | import { | |
5 | ActivitypubFollowPayload, | |
6 | ActivitypubHttpBroadcastPayload, | |
7 | ActivitypubHttpFetcherPayload, | |
8 | ActivitypubHttpUnicastPayload, | |
9 | EmailPayload, | |
10 | JobState, | |
11 | JobType, | |
12 | RefreshPayload, | |
13 | VideoFileImportPayload, | |
14 | VideoImportPayload, | |
15 | VideoLiveEndingPayload, | |
16 | VideoRedundancyPayload, | |
17 | VideoTranscodingPayload | |
18 | } from '../../../shared/models' | |
19 | import { logger } from '../../helpers/logger' | |
20 | import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants' | |
21 | import { Redis } from '../redis' | |
22 | import { processActivityPubFollow } from './handlers/activitypub-follow' | |
23 | import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast' | |
24 | import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher' | |
25 | import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast' | |
26 | import { refreshAPObject } from './handlers/activitypub-refresher' | |
27 | import { processEmail } from './handlers/email' | |
28 | import { processVideoFileImport } from './handlers/video-file-import' | |
29 | import { processVideoImport } from './handlers/video-import' | |
30 | import { processVideoLiveEnding } from './handlers/video-live-ending' | |
31 | import { processVideoTranscoding } from './handlers/video-transcoding' | |
32 | import { processVideosViews } from './handlers/video-views' | |
33 | ||
34 | type CreateJobArgument = | |
35 | { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } | | |
36 | { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } | | |
37 | { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } | | |
38 | { type: 'activitypub-follow', payload: ActivitypubFollowPayload } | | |
39 | { type: 'video-file-import', payload: VideoFileImportPayload } | | |
40 | { type: 'video-transcoding', payload: VideoTranscodingPayload } | | |
41 | { type: 'email', payload: EmailPayload } | | |
42 | { type: 'video-import', payload: VideoImportPayload } | | |
43 | { type: 'activitypub-refresher', payload: RefreshPayload } | | |
44 | { type: 'videos-views', payload: {} } | | |
45 | { type: 'video-live-ending', payload: VideoLiveEndingPayload } | | |
46 | { type: 'video-redundancy', payload: VideoRedundancyPayload } | |
47 | ||
48 | type CreateJobOptions = { | |
49 | delay?: number | |
50 | } | |
51 | ||
52 | const handlers: { [id in JobType]: (job: Bull.Job) => Promise<any> } = { | |
53 | 'activitypub-http-broadcast': processActivityPubHttpBroadcast, | |
54 | 'activitypub-http-unicast': processActivityPubHttpUnicast, | |
55 | 'activitypub-http-fetcher': processActivityPubHttpFetcher, | |
56 | 'activitypub-follow': processActivityPubFollow, | |
57 | 'video-file-import': processVideoFileImport, | |
58 | 'video-transcoding': processVideoTranscoding, | |
59 | 'email': processEmail, | |
60 | 'video-import': processVideoImport, | |
61 | 'videos-views': processVideosViews, | |
62 | 'activitypub-refresher': refreshAPObject, | |
63 | 'video-live-ending': processVideoLiveEnding, | |
64 | 'video-redundancy': processVideoRedundancy | |
65 | } | |
66 | ||
67 | const jobTypes: JobType[] = [ | |
68 | 'activitypub-follow', | |
69 | 'activitypub-http-broadcast', | |
70 | 'activitypub-http-fetcher', | |
71 | 'activitypub-http-unicast', | |
72 | 'email', | |
73 | 'video-transcoding', | |
74 | 'video-file-import', | |
75 | 'video-import', | |
76 | 'videos-views', | |
77 | 'activitypub-refresher', | |
78 | 'video-redundancy', | |
79 | 'video-live-ending' | |
80 | ] | |
81 | ||
82 | class JobQueue { | |
83 | ||
84 | private static instance: JobQueue | |
85 | ||
86 | private queues: { [id in JobType]?: Bull.Queue } = {} | |
87 | private initialized = false | |
88 | private jobRedisPrefix: string | |
89 | ||
90 | private constructor () { | |
91 | } | |
92 | ||
93 | init () { | |
94 | // Already initialized | |
95 | if (this.initialized === true) return | |
96 | this.initialized = true | |
97 | ||
98 | this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST | |
99 | const queueOptions = { | |
100 | prefix: this.jobRedisPrefix, | |
101 | redis: Redis.getRedisClientOptions(), | |
102 | settings: { | |
103 | maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts | |
104 | } | |
105 | } | |
106 | ||
107 | for (const handlerName of Object.keys(handlers)) { | |
108 | const queue = new Bull(handlerName, queueOptions) | |
109 | const handler = handlers[handlerName] | |
110 | ||
111 | queue.process(JOB_CONCURRENCY[handlerName], handler) | |
112 | .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err })) | |
113 | ||
114 | queue.on('failed', (job, err) => { | |
115 | logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err }) | |
116 | }) | |
117 | ||
118 | queue.on('error', err => { | |
119 | logger.error('Error in job queue %s.', handlerName, { err }) | |
120 | }) | |
121 | ||
122 | this.queues[handlerName] = queue | |
123 | } | |
124 | ||
125 | this.addRepeatableJobs() | |
126 | } | |
127 | ||
128 | terminate () { | |
129 | for (const queueName of Object.keys(this.queues)) { | |
130 | const queue = this.queues[queueName] | |
131 | queue.close() | |
132 | } | |
133 | } | |
134 | ||
135 | createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void { | |
136 | this.createJobWithPromise(obj, options) | |
137 | .catch(err => logger.error('Cannot create job.', { err, obj })) | |
138 | } | |
139 | ||
140 | createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) { | |
141 | const queue = this.queues[obj.type] | |
142 | if (queue === undefined) { | |
143 | logger.error('Unknown queue %s: cannot create job.', obj.type) | |
144 | return | |
145 | } | |
146 | ||
147 | const jobArgs: Bull.JobOptions = { | |
148 | backoff: { delay: 60 * 1000, type: 'exponential' }, | |
149 | attempts: JOB_ATTEMPTS[obj.type], | |
150 | timeout: JOB_TTL[obj.type], | |
151 | delay: options.delay | |
152 | } | |
153 | ||
154 | return queue.add(obj.payload, jobArgs) | |
155 | } | |
156 | ||
157 | async listForApi (options: { | |
158 | state?: JobState | |
159 | start: number | |
160 | count: number | |
161 | asc?: boolean | |
162 | jobType: JobType | |
163 | }): Promise<Bull.Job[]> { | |
164 | const { state, start, count, asc, jobType } = options | |
165 | ||
166 | const states = state ? [ state ] : jobStates | |
167 | let results: Bull.Job[] = [] | |
168 | ||
169 | const filteredJobTypes = this.filterJobTypes(jobType) | |
170 | ||
171 | for (const jobType of filteredJobTypes) { | |
172 | const queue = this.queues[jobType] | |
173 | if (queue === undefined) { | |
174 | logger.error('Unknown queue %s to list jobs.', jobType) | |
175 | continue | |
176 | } | |
177 | ||
178 | const jobs = await queue.getJobs(states, 0, start + count, asc) | |
179 | results = results.concat(jobs) | |
180 | } | |
181 | ||
182 | results.sort((j1: any, j2: any) => { | |
183 | if (j1.timestamp < j2.timestamp) return -1 | |
184 | else if (j1.timestamp === j2.timestamp) return 0 | |
185 | ||
186 | return 1 | |
187 | }) | |
188 | ||
189 | if (asc === false) results.reverse() | |
190 | ||
191 | return results.slice(start, start + count) | |
192 | } | |
193 | ||
194 | async count (state: JobState, jobType?: JobType): Promise<number> { | |
195 | const states = state ? [ state ] : jobStates | |
196 | let total = 0 | |
197 | ||
198 | const filteredJobTypes = this.filterJobTypes(jobType) | |
199 | ||
200 | for (const type of filteredJobTypes) { | |
201 | const queue = this.queues[type] | |
202 | if (queue === undefined) { | |
203 | logger.error('Unknown queue %s to count jobs.', type) | |
204 | continue | |
205 | } | |
206 | ||
207 | const counts = await queue.getJobCounts() | |
208 | ||
209 | for (const s of states) { | |
210 | total += counts[s] | |
211 | } | |
212 | } | |
213 | ||
214 | return total | |
215 | } | |
216 | ||
217 | async removeOldJobs () { | |
218 | for (const key of Object.keys(this.queues)) { | |
219 | const queue = this.queues[key] | |
220 | await queue.clean(JOB_COMPLETED_LIFETIME, 'completed') | |
221 | } | |
222 | } | |
223 | ||
224 | private addRepeatableJobs () { | |
225 | this.queues['videos-views'].add({}, { | |
226 | repeat: REPEAT_JOBS['videos-views'] | |
227 | }).catch(err => logger.error('Cannot add repeatable job.', { err })) | |
228 | } | |
229 | ||
230 | private filterJobTypes (jobType?: JobType) { | |
231 | if (!jobType) return jobTypes | |
232 | ||
233 | return jobTypes.filter(t => t === jobType) | |
234 | } | |
235 | ||
236 | static get Instance () { | |
237 | return this.instance || (this.instance = new this()) | |
238 | } | |
239 | } | |
240 | ||
241 | // --------------------------------------------------------------------------- | |
242 | ||
243 | export { | |
244 | jobTypes, | |
245 | JobQueue | |
246 | } |