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