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