]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/job-queue.ts
Add create-import-video-file-job command
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
CommitLineData
94a5ff8a 1import * as kue from 'kue'
628d28e8 2import { JobState, JobType } from '../../../shared/models'
94a5ff8a 3import { logger } from '../../helpers/logger'
71e3dfda 4import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
2c29ad4f 5import { Redis } from '../redis'
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'
0138af92 10import { processVideoFile, processVideoImport, VideoFilePayload, VideoImportPayload } from './handlers/video-file'
5350fd8e 11import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
94a5ff8a
C
12
13type CreateJobArgument =
14 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
15 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
16 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
5350fd8e 17 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
0138af92 18 { type: 'video-file-import', payload: VideoImportPayload } |
ecb4e35f
C
19 { type: 'video-file', payload: VideoFilePayload } |
20 { type: 'email', payload: EmailPayload }
94a5ff8a
C
21
22const handlers: { [ id in JobType ]: (job: kue.Job) => Promise<any>} = {
23 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
24 'activitypub-http-unicast': processActivityPubHttpUnicast,
25 'activitypub-http-fetcher': processActivityPubHttpFetcher,
5350fd8e 26 'activitypub-follow': processActivityPubFollow,
0138af92 27 'video-file-import': processVideoImport,
ecb4e35f
C
28 'video-file': processVideoFile,
29 'email': processEmail
94a5ff8a
C
30}
31
71e3dfda
C
32const jobsWithTLL: JobType[] = [
33 'activitypub-http-broadcast',
34 'activitypub-http-unicast',
35 'activitypub-http-fetcher',
36 'activitypub-follow'
37]
38
94a5ff8a
C
39class JobQueue {
40
41 private static instance: JobQueue
42
43 private jobQueue: kue.Queue
44 private initialized = false
2c29ad4f 45 private jobRedisPrefix: string
94a5ff8a
C
46
47 private constructor () {}
48
3df45638 49 async init () {
94a5ff8a
C
50 // Already initialized
51 if (this.initialized === true) return
52 this.initialized = true
53
2c29ad4f
C
54 this.jobRedisPrefix = 'q-' + CONFIG.WEBSERVER.HOST
55
94a5ff8a 56 this.jobQueue = kue.createQueue({
2c29ad4f 57 prefix: this.jobRedisPrefix,
94a5ff8a
C
58 redis: {
59 host: CONFIG.REDIS.HOSTNAME,
60 port: CONFIG.REDIS.PORT,
30c82f0d
RK
61 auth: CONFIG.REDIS.AUTH,
62 db: CONFIG.REDIS.DB
94a5ff8a
C
63 }
64 })
65
5350fd8e 66 this.jobQueue.setMaxListeners(20)
ecb4e35f 67
94a5ff8a 68 this.jobQueue.on('error', err => {
d5b7d911 69 logger.error('Error in job queue.', { err })
94a5ff8a
C
70 process.exit(-1)
71 })
72 this.jobQueue.watchStuckJobs(5000)
73
3df45638
C
74 await this.reactiveStuckJobs()
75
94a5ff8a
C
76 for (const handlerName of Object.keys(handlers)) {
77 this.jobQueue.process(handlerName, JOB_CONCURRENCY[handlerName], async (job, done) => {
78 try {
79 const res = await handlers[ handlerName ](job)
80 return done(null, res)
81 } catch (err) {
82 return done(err)
83 }
84 })
85 }
86 }
87
88 createJob (obj: CreateJobArgument, priority = 'normal') {
89 return new Promise((res, rej) => {
71e3dfda 90 let job = this.jobQueue
94a5ff8a
C
91 .create(obj.type, obj.payload)
92 .priority(priority)
93 .attempts(JOB_ATTEMPTS[obj.type])
802dbc32 94 .backoff({ delay: 60 * 1000, type: 'exponential' })
94a5ff8a 95
71e3dfda
C
96 if (jobsWithTLL.indexOf(obj.type) !== -1) {
97 job = job.ttl(JOB_REQUEST_TTL)
98 }
99
100 return job.save(err => {
101 if (err) return rej(err)
102
103 return res()
104 })
94a5ff8a
C
105 })
106 }
107
628d28e8 108 async listForApi (state: JobState, start: number, count: number, sort: 'ASC' | 'DESC'): Promise<kue.Job[]> {
2c29ad4f 109 const jobStrings = await Redis.Instance.listJobs(this.jobRedisPrefix, state, 'alpha', sort, start, count)
94a5ff8a 110
2c29ad4f
C
111 const jobPromises = jobStrings
112 .map(s => s.split('|'))
113 .map(([ , jobId ]) => this.getJob(parseInt(jobId, 10)))
114
115 return Promise.all(jobPromises)
94a5ff8a
C
116 }
117
118 count (state: JobState) {
119 return new Promise<number>((res, rej) => {
120 this.jobQueue[state + 'Count']((err, total) => {
121 if (err) return rej(err)
122
123 return res(total)
124 })
125 })
126 }
127
128 removeOldJobs () {
129 const now = new Date().getTime()
130 kue.Job.rangeByState('complete', 0, -1, 'asc', (err, jobs) => {
131 if (err) {
d5b7d911 132 logger.error('Cannot get jobs when removing old jobs.', { err })
94a5ff8a
C
133 return
134 }
135
136 for (const job of jobs) {
137 if (now - job.created_at > JOB_COMPLETED_LIFETIME) {
138 job.remove()
139 }
140 }
141 })
142 }
143
3df45638
C
144 private reactiveStuckJobs () {
145 const promises: Promise<any>[] = []
146
147 this.jobQueue.active((err, ids) => {
148 if (err) throw err
149
150 for (const id of ids) {
151 kue.Job.get(id, (err, job) => {
152 if (err) throw err
153
154 const p = new Promise((res, rej) => {
155 job.inactive(err => {
156 if (err) return rej(err)
157 return res()
158 })
159 })
160
161 promises.push(p)
162 })
163 }
164 })
165
166 return Promise.all(promises)
167 }
168
2c29ad4f 169 private getJob (id: number) {
628d28e8 170 return new Promise<kue.Job>((res, rej) => {
2c29ad4f
C
171 kue.Job.get(id, (err, job) => {
172 if (err) return rej(err)
173
174 return res(job)
175 })
176 })
177 }
178
94a5ff8a
C
179 static get Instance () {
180 return this.instance || (this.instance = new this())
181 }
182}
183
184// ---------------------------------------------------------------------------
185
186export {
187 JobQueue
188}