]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - 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
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 } 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 class JobQueue {
31
32 private static instance: JobQueue
33
34 private jobQueue: kue.Queue
35 private initialized = false
36 private jobRedisPrefix: string
37
38 private constructor () {}
39
40 async init () {
41 // Already initialized
42 if (this.initialized === true) return
43 this.initialized = true
44
45 this.jobRedisPrefix = 'q-' + CONFIG.WEBSERVER.HOST
46
47 this.jobQueue = kue.createQueue({
48 prefix: this.jobRedisPrefix,
49 redis: {
50 host: CONFIG.REDIS.HOSTNAME,
51 port: CONFIG.REDIS.PORT,
52 auth: CONFIG.REDIS.AUTH
53 }
54 })
55
56 this.jobQueue.setMaxListeners(20)
57
58 this.jobQueue.on('error', err => {
59 logger.error('Error in job queue.', { err })
60 process.exit(-1)
61 })
62 this.jobQueue.watchStuckJobs(5000)
63
64 await this.reactiveStuckJobs()
65
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])
84 .backoff({ delay: 60 * 1000, type: 'exponential' })
85 .save(err => {
86 if (err) return rej(err)
87
88 return res()
89 })
90 })
91 }
92
93 async listForApi (state: JobState, start: number, count: number, sort: 'ASC' | 'DESC'): Promise<kue.Job[]> {
94 const jobStrings = await Redis.Instance.listJobs(this.jobRedisPrefix, state, 'alpha', sort, start, count)
95
96 const jobPromises = jobStrings
97 .map(s => s.split('|'))
98 .map(([ , jobId ]) => this.getJob(parseInt(jobId, 10)))
99
100 return Promise.all(jobPromises)
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) {
117 logger.error('Cannot get jobs when removing old jobs.', { err })
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
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
154 private getJob (id: number) {
155 return new Promise<kue.Job>((res, rej) => {
156 kue.Job.get(id, (err, job) => {
157 if (err) return rej(err)
158
159 return res(job)
160 })
161 })
162 }
163
164 static get Instance () {
165 return this.instance || (this.instance = new this())
166 }
167 }
168
169 // ---------------------------------------------------------------------------
170
171 export {
172 JobQueue
173 }