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