PeerTube/server/lib/job-queue/job-queue.ts

175 lines
5.3 KiB
TypeScript
Raw Normal View History

2018-07-10 10:02:20 -05:00
import * as Bull from 'bull'
2018-02-27 10:42:32 -06:00
import { JobState, JobType } from '../../../shared/models'
import { logger } from '../../helpers/logger'
2018-05-14 10:51:15 -05:00
import { Redis } from '../redis'
2018-05-09 02:08:22 -05:00
import { CONFIG, JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_REQUEST_TTL } from '../../initializers'
import { ActivitypubHttpBroadcastPayload, processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
import { ActivitypubHttpFetcherPayload, processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
import { ActivitypubHttpUnicastPayload, processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
2018-01-30 06:27:07 -06:00
import { EmailPayload, processEmail } from './handlers/email'
2018-07-10 10:02:20 -05:00
import { processVideoFile, processVideoFileImport, VideoFileImportPayload, VideoFilePayload } from './handlers/video-file'
import { ActivitypubFollowPayload, processActivityPubFollow } from './handlers/activitypub-follow'
type CreateJobArgument =
{ type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
{ type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
{ type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
{ type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
{ type: 'video-file-import', payload: VideoFileImportPayload } |
2018-01-30 06:27:07 -06:00
{ type: 'video-file', payload: VideoFilePayload } |
{ type: 'email', payload: EmailPayload }
2018-07-10 10:02:20 -05:00
const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise<any>} = {
'activitypub-http-broadcast': processActivityPubHttpBroadcast,
'activitypub-http-unicast': processActivityPubHttpUnicast,
'activitypub-http-fetcher': processActivityPubHttpFetcher,
'activitypub-follow': processActivityPubFollow,
'video-file-import': processVideoFileImport,
2018-01-30 06:27:07 -06:00
'video-file': processVideoFile,
'email': processEmail
}
2018-07-10 10:02:20 -05:00
const jobsWithRequestTimeout: { [ id in JobType ]?: boolean } = {
'activitypub-http-broadcast': true,
'activitypub-http-unicast': true,
'activitypub-http-fetcher': true,
'activitypub-follow': true
}
const jobTypes: JobType[] = [
'activitypub-follow',
2018-05-09 02:08:22 -05:00
'activitypub-http-broadcast',
'activitypub-http-fetcher',
2018-07-10 10:02:20 -05:00
'activitypub-http-unicast',
'email',
'video-file',
'video-file-import'
2018-05-09 02:08:22 -05:00
]
class JobQueue {
private static instance: JobQueue
2018-07-10 10:02:20 -05:00
private queues: { [ id in JobType ]?: Bull.Queue } = {}
private initialized = false
private jobRedisPrefix: string
private constructor () {}
2018-02-12 04:25:09 -06:00
async init () {
// Already initialized
if (this.initialized === true) return
this.initialized = true
2018-07-10 10:02:20 -05:00
this.jobRedisPrefix = 'bull-' + CONFIG.WEBSERVER.HOST
const queueOptions = {
prefix: this.jobRedisPrefix,
2018-05-14 10:51:15 -05:00
redis: Redis.getRedisClient()
2018-07-10 10:02:20 -05:00
}
2018-01-30 06:27:07 -06:00
2018-07-10 10:02:20 -05:00
for (const handlerName of Object.keys(handlers)) {
const queue = new Bull(handlerName, queueOptions)
const handler = handlers[handlerName]
2018-07-10 10:02:20 -05:00
queue.process(JOB_CONCURRENCY[handlerName], handler)
.catch(err => logger.error('Cannot execute job queue %s.', handlerName, { err }))
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
queue.on('error', err => {
logger.error('Error in job queue %s.', handlerName, { err })
process.exit(-1)
})
2018-07-10 10:02:20 -05:00
this.queues[handlerName] = queue
}
}
2018-07-30 11:49:54 -05:00
terminate () {
for (const queueName of Object.keys(this.queues)) {
const queue = this.queues[queueName]
queue.close()
}
}
2018-07-10 10:02:20 -05:00
createJob (obj: CreateJobArgument) {
const queue = this.queues[obj.type]
if (queue === undefined) {
logger.error('Unknown queue %s: cannot create job.', obj.type)
throw Error('Unknown queue, cannot create job')
2018-07-10 10:02:20 -05:00
}
2018-07-10 10:02:20 -05:00
const jobArgs: Bull.JobOptions = {
backoff: { delay: 60 * 1000, type: 'exponential' },
attempts: JOB_ATTEMPTS[obj.type]
}
2018-05-09 02:08:22 -05:00
2018-07-10 10:02:20 -05:00
if (jobsWithRequestTimeout[obj.type] === true) {
jobArgs.timeout = JOB_REQUEST_TTL
}
2018-05-09 02:08:22 -05:00
2018-07-10 10:02:20 -05:00
return queue.add(obj.payload, jobArgs)
}
2018-07-10 10:02:20 -05:00
async listForApi (state: JobState, start: number, count: number, asc?: boolean): Promise<Bull.Job[]> {
let results: Bull.Job[] = []
2018-07-10 10:02:20 -05:00
// TODO: optimize
for (const jobType of jobTypes) {
const queue = this.queues[ jobType ]
if (queue === undefined) {
logger.error('Unknown queue %s to list jobs.', jobType)
continue
}
2018-07-10 10:02:20 -05:00
// FIXME: Bull queue typings does not have getJobs method
const jobs = await (queue as any).getJobs(state, 0, start + count, asc)
results = results.concat(jobs)
}
2018-07-10 10:02:20 -05:00
results.sort((j1: any, j2: any) => {
if (j1.timestamp < j2.timestamp) return -1
else if (j1.timestamp === j2.timestamp) return 0
2018-07-10 10:02:20 -05:00
return 1
})
2018-07-10 10:02:20 -05:00
if (asc === false) results.reverse()
2018-07-10 10:02:20 -05:00
return results.slice(start, start + count)
}
2018-07-10 10:02:20 -05:00
async count (state: JobState): Promise<number> {
let total = 0
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
for (const type of jobTypes) {
const queue = this.queues[ type ]
if (queue === undefined) {
logger.error('Unknown queue %s to count jobs.', type)
continue
}
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
const counts = await queue.getJobCounts()
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
total += counts[ state ]
}
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
return total
2018-02-12 04:25:09 -06:00
}
2018-07-10 10:02:20 -05:00
removeOldJobs () {
for (const key of Object.keys(this.queues)) {
const queue = this.queues[key]
queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
}
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}
// ---------------------------------------------------------------------------
export {
JobQueue
}