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