job-queue.ts 6.0 KB

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