2
1

job-queue.ts 6.3 KB

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