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