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