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