| 3 | import { Queue, QueueOptions } from "./queue" |
| 4 | |
| 5 | export class RedisQueue<T> extends Queue<T> { |
| 6 | private redisBlocking: IORedis |
| 7 | private redisNonBlocking: IORedis |
| 8 | private redisSubscriber: IORedis |
| 9 | |
| 10 | constructor(redisUrl: string, queueName: string, options?: QueueOptions) { |
| 11 | super(queueName, options) |
| 12 | |
| 13 | this.redisBlocking = new IORedis(redisUrl) |
| 14 | this.redisNonBlocking = new IORedis(redisUrl) |
| 15 | this.redisSubscriber = new IORedis(redisUrl) |
| 16 | |
| 17 | this.listenForExpiredJobs() |
| 18 | this.checkForExpiredJobs() |
| 19 | } |
| 20 | |
| 21 | get length() { |
| 22 | return this.redisNonBlocking.zcard(this.activeJobsQueue) |
| 23 | } |
| 24 | |
| 25 | async getOrWaitForJob() { |
| 26 | const data = await this.redisBlocking.bzpopmin(this.activeJobsQueue, 0) |
| 27 | return data?.[1] ? JSON.parse(data[1]) : null |
| 28 | } |
| 29 | |
| 30 | protected async push(job: Job<T>) { |
| 31 | if (job.options.delay > 0) { |
| 32 | return await this.redisNonBlocking |
| 33 | .multi() |
| 34 | .set(this.expiringJobIdList(job.id), job.id) |
| 35 | .pexpire(this.expiringJobIdList(job.id), job.options.delay) |
| 36 | .zadd(this.delayedJobIdsQueue, Date.now() + job.options.delay, job.id) |
| 37 | .hset(this.delayedJobsList, job.id, JSON.stringify(job)) |
| 38 | .exec() |
| 39 | } else { |
| 40 | return await this.addActiveJob(job) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // Ready to execute jobs sorted by priority |
| 45 | private get activeJobsQueue() { |
| 46 | return `${this.queueName}:active` |
| 47 | } |
| 48 | |
| 49 | // Full job data for delayed jobs |
| 50 | private get delayedJobsList() { |
| 51 | return `${this.queueName}:jobs` |
| 52 | } |
| 53 | |
| 54 | // Delayed job ids sorted by execution date |
| 55 | private get delayedJobIdsQueue() { |
| 56 | return `${this.queueName}:delayed` |
| 57 | } |
| 58 | |
| 59 | // Delayed job ids that will expire after the delay |
| 60 | private expiringJobIdList(jobId: string) { |
| 61 | return `${this.queueName}:expiringJobs:${jobId}` |
| 62 | } |
nothing calls this directly
no outgoing calls
no test coverage detected