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