├── .nvmrc ├── .prettierrc ├── CNAME ├── resque-web ├── .ruby-version ├── Gemfile ├── config.ru ├── Gemfile.lock └── readme.md ├── .github ├── FUNDING.yml ├── workflows │ ├── publish_docs.yml │ └── test.yml └── dependabot.yml ├── images ├── favicon.ico └── error_payload.png ├── src ├── types │ ├── jobs.ts │ ├── job.ts │ ├── errorPayload.ts │ └── options.ts ├── plugins │ ├── index.ts │ ├── Noop.ts │ ├── DelayQueueLock.ts │ ├── QueueLock.ts │ ├── JobLock.ts │ └── Retry.ts ├── index.ts ├── utils │ └── eventLoopDelay.ts └── core │ ├── plugin.ts │ ├── pluginRunner.ts │ ├── connection.ts │ ├── multiWorker.ts │ ├── scheduler.ts │ └── worker.ts ├── .devcontainer ├── devcontainer.json └── setup.sh ├── .gitignore ├── jest.config.js ├── examples ├── docker │ ├── producer │ │ ├── tsconfig.json │ │ ├── Dockerfile │ │ ├── package.json │ │ └── src │ │ │ └── producer.ts │ ├── worker │ │ ├── tsconfig.json │ │ ├── Dockerfile │ │ ├── package.json │ │ └── src │ │ │ └── worker.ts │ ├── docker-compose.yml │ └── README.md ├── performInline.ts ├── errorExample.ts ├── customPluginExample.ts ├── retry.ts ├── stuckWorker.ts ├── multiWorker.ts ├── scheduledJobs.ts ├── cluster.ts ├── example-mock.ts └── example.ts ├── SECURITY.md ├── tsconfig.json ├── __tests__ ├── utils │ ├── custom-plugin.ts │ └── specHelper.ts ├── plugins │ ├── custom_plugins.ts │ ├── delayedQueueLock.ts │ ├── noop.ts │ ├── queueLock.ts │ ├── jobLock.ts │ └── retry.ts ├── core │ ├── connectionError.ts │ ├── multiWorker.ts │ ├── scheduler.ts │ ├── connection.ts │ └── worker.ts └── integration │ ├── ioredis.ts │ └── ioredis-mock.ts ├── lua └── popAndStoreJob.lua ├── bin └── deploy-docs ├── package.json └── LICENSE.txt /.nvmrc: -------------------------------------------------------------------------------- 1 | v20 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | node-resque.actionherojs.com 2 | -------------------------------------------------------------------------------- /resque-web/.ruby-version: -------------------------------------------------------------------------------- 1 | 2.5.0 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [evantahler] 2 | -------------------------------------------------------------------------------- /images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/actionhero/node-resque/HEAD/images/favicon.ico -------------------------------------------------------------------------------- /images/error_payload.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/actionhero/node-resque/HEAD/images/error_payload.png -------------------------------------------------------------------------------- /src/types/jobs.ts: -------------------------------------------------------------------------------- 1 | import { Job } from "./job"; 2 | 3 | export interface Jobs { 4 | [jobName: string]: Job; 5 | } 6 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "appPort": 8080, 3 | "postCreateCommand": "/bin/bash ./.devcontainer/setup.sh", 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | npm-debug.log 4 | dump.rdb 5 | .idea/ 6 | dist 7 | docs 8 | examples/docker/*/package-lock.json 9 | -------------------------------------------------------------------------------- /resque-web/Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | 3 | gem 'rake' 4 | gem 'sinatra' 5 | gem 'resque' 6 | gem 'resque-scheduler' 7 | gem 'resque-retry' 8 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | maxWorkers: "50%", 3 | testPathIgnorePatterns: ["/__tests__/utils"], 4 | transform: { 5 | "^.+\\.ts?$": "ts-jest", 6 | }, 7 | }; 8 | -------------------------------------------------------------------------------- /examples/docker/producer/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "allowJs": true, 5 | "module": "commonjs", 6 | "target": "es2018" 7 | }, 8 | "include": ["./src/**/*"] 9 | } 10 | -------------------------------------------------------------------------------- /examples/docker/worker/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "allowJs": true, 5 | "module": "commonjs", 6 | "target": "es2018" 7 | }, 8 | "include": ["./src/**/*"] 9 | } 10 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | If you have found a security issue, please email evan [at] actionherojs.com. Do not post a Github Issue so we can properly patch the issue before disclosing publicly. 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "allowJs": true, 5 | "module": "commonjs", 6 | "target": "es2018", 7 | "noImplicitAny": true 8 | }, 9 | "include": ["./src/**/*"] 10 | } 11 | -------------------------------------------------------------------------------- /src/types/job.ts: -------------------------------------------------------------------------------- 1 | export interface Job { 2 | plugins?: Array; 3 | pluginOptions?: { 4 | [pluginName: string]: { 5 | [key: string]: any; 6 | }; 7 | }; 8 | perform: (...args: any[]) => Promise; 9 | } 10 | -------------------------------------------------------------------------------- /.devcontainer/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "--- CONFIURING CODESPACE ---" 4 | 5 | # configure node 6 | nvm install v16 7 | npm install 8 | 9 | # configure redis 10 | sudo apt-get install redis-tools -y 11 | docker run -p 6379:6379 --name redis -d redis 12 | -------------------------------------------------------------------------------- /src/types/errorPayload.ts: -------------------------------------------------------------------------------- 1 | export interface ErrorPayload { 2 | worker: string; 3 | queue: string; 4 | payload: { 5 | class: string; 6 | args: Array; 7 | }; 8 | exception: string; 9 | error: string; 10 | backtrace: Array; 11 | failed_at: string | number; 12 | } 13 | -------------------------------------------------------------------------------- /src/plugins/index.ts: -------------------------------------------------------------------------------- 1 | import { DelayQueueLock } from "./DelayQueueLock"; 2 | import { JobLock } from "./JobLock"; 3 | import { Noop } from "./Noop"; 4 | import { QueueLock } from "./QueueLock"; 5 | import { Retry } from "./Retry"; 6 | 7 | export default { 8 | DelayQueueLock, 9 | JobLock, 10 | Noop, 11 | QueueLock, 12 | Retry, 13 | }; 14 | -------------------------------------------------------------------------------- /examples/docker/producer/Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM alpine:latest 3 | 4 | WORKDIR /node-resque-demo 5 | 6 | RUN apk add --update nodejs nodejs-npm 7 | 8 | COPY package.json . 9 | COPY tsconfig.json . 10 | COPY src src 11 | 12 | # npm install will also run npm prepare, compiling the typescript 13 | RUN npm install --unsafe-perm 14 | RUN npm prune 15 | 16 | CMD ["node", "dist/producer.js"] 17 | -------------------------------------------------------------------------------- /examples/docker/worker/Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM alpine:latest 3 | 4 | WORKDIR /node-resque-demo 5 | 6 | RUN apk add --update nodejs nodejs-npm 7 | 8 | COPY package.json . 9 | COPY tsconfig.json . 10 | COPY src src 11 | 12 | # npm install will also run npm prepare, compiling the typescript 13 | RUN npm install --unsafe-perm 14 | RUN npm prune 15 | 16 | CMD ["node", "dist/worker.js"] 17 | -------------------------------------------------------------------------------- /__tests__/utils/custom-plugin.ts: -------------------------------------------------------------------------------- 1 | // Simple plugin to prevent all jobs 2 | import { Plugin } from "../../src"; 3 | 4 | export class CustomPlugin extends Plugin { 5 | async beforeEnqueue() { 6 | return false; 7 | } 8 | 9 | async afterEnqueue() { 10 | return false; 11 | } 12 | 13 | async beforePerform() { 14 | return false; 15 | } 16 | 17 | async afterPerform() { 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /resque-web/config.ru: -------------------------------------------------------------------------------- 1 | require "bundler/setup" 2 | Bundler.require(:default) 3 | require 'sinatra' 4 | require 'resque/server' 5 | require 'resque/scheduler' 6 | require 'resque/scheduler/server' 7 | require 'resque-retry' 8 | require 'resque-retry/server' 9 | require 'yaml' 10 | 11 | Resque.redis = Redis.new({ 12 | :host => !ENV['RAILS_RESQUE_REDIS'].nil? ? ENV['RAILS_RESQUE_REDIS'] : '127.0.0.1', 13 | :port => 6379, 14 | # :db => 1, 15 | }) 16 | # Resque.redis.namespace = 'resque_test' 17 | 18 | run Rack::URLMap.new \ 19 | "/" => Resque::Server.new 20 | -------------------------------------------------------------------------------- /examples/docker/producer/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-resque-docker-example-producer", 3 | "version": "1.0.0", 4 | "description": "An example node-resque docker project", 5 | "author": "", 6 | "license": "ISC", 7 | "repository": { 8 | "type": "git", 9 | "url": "git://github.com/actionhero/node-resque.git" 10 | }, 11 | "scripts": { 12 | "prepare": "tsc" 13 | }, 14 | "dependencies": { 15 | "node-resque": "latest" 16 | }, 17 | "devDependencies": { 18 | "@types/node": "latest", 19 | "typescript": "latest" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/docker/worker/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-resque-docker-example-worker", 3 | "version": "1.0.0", 4 | "description": "An example node-resque docker project", 5 | "author": "", 6 | "license": "ISC", 7 | "repository": { 8 | "type": "git", 9 | "url": "git://github.com/actionhero/node-resque.git" 10 | }, 11 | "scripts": { 12 | "prepare": "tsc" 13 | }, 14 | "dependencies": { 15 | "node-resque": "latest" 16 | }, 17 | "devDependencies": { 18 | "@types/node": "latest", 19 | "typescript": "latest" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.1" 2 | 3 | services: 4 | redis: 5 | image: redis 6 | networks: 7 | - resque_network 8 | 9 | node-resque-worker: 10 | build: ./worker 11 | environment: 12 | REDIS_HOST: redis 13 | depends_on: 14 | - redis 15 | networks: 16 | - resque_network 17 | 18 | node-resque-producer: 19 | build: ./producer 20 | environment: 21 | REDIS_HOST: redis 22 | depends_on: 23 | - redis 24 | networks: 25 | - resque_network 26 | 27 | networks: 28 | resque_network: 29 | -------------------------------------------------------------------------------- /lua/popAndStoreJob.lua: -------------------------------------------------------------------------------- 1 | -- { "numberOfKeys": 2 } 2 | 3 | -- Keys: 4 | -- 1 - Queue Key 5 | -- 2 - Worker Key 6 | 7 | -- Args 8 | -- 1 - Date 9 | -- 2 - Queue Name 10 | -- 3 - Worker Name 11 | 12 | local payload = redis.call('lpop', KEYS[1]) 13 | 14 | if payload then 15 | local workerPayload = {} 16 | workerPayload['run_at'] = ARGV[1] 17 | workerPayload['queue'] = ARGV[2] 18 | workerPayload['payload'] = cjson.decode(payload) 19 | workerPayload['worker'] = ARGV[3] 20 | 21 | redis.call('set', KEYS[2], cjson.encode(workerPayload)) 22 | end 23 | 24 | return payload 25 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { Connection } from "./core/connection"; 2 | export { 3 | Queue, 4 | ParsedJob, 5 | ParsedWorkerPayload, 6 | ParsedFailedJobPayload, 7 | } from "./core/queue"; 8 | export { Scheduler } from "./core/scheduler"; 9 | export { Worker } from "./core/worker"; 10 | export { MultiWorker } from "./core/multiWorker"; 11 | export { Plugin } from "./core/plugin"; 12 | export { default as Plugins } from "./plugins"; 13 | 14 | export { ConnectionOptions } from "./types/options"; 15 | export { Job } from "./types/job"; 16 | export { Jobs } from "./types/jobs"; 17 | export { ErrorPayload } from "./types/errorPayload"; 18 | -------------------------------------------------------------------------------- /src/plugins/Noop.ts: -------------------------------------------------------------------------------- 1 | import { Plugin } from ".."; 2 | 3 | export class Noop extends Plugin { 4 | async afterPerform() { 5 | if (this.worker.error) { 6 | if (typeof this.options.logger === "function") { 7 | this.options.logger(this.worker.error); 8 | } else { 9 | console.log(this.worker.error); 10 | } 11 | delete this.worker.error; 12 | } 13 | 14 | return true; 15 | } 16 | 17 | async beforeEnqueue() { 18 | return true; 19 | } 20 | 21 | async afterEnqueue() { 22 | return true; 23 | } 24 | 25 | async beforePerform() { 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.github/workflows/publish_docs.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docs 2 | on: 3 | push: 4 | branches: [main] 5 | 6 | jobs: 7 | publish_docs: 8 | runs-on: ubuntu-latest 9 | container: 10 | image: node 11 | steps: 12 | - uses: actions/checkout@v6 13 | - name: Use Node.js 20.x 14 | uses: actions/setup-node@v6.0.0 15 | with: 16 | node-version: 20.x 17 | - run: npm ci 18 | - run: ./bin/deploy-docs 19 | - name: Push changes 20 | uses: ad-m/github-push-action@master 21 | with: 22 | github_token: ${{ secrets.GITHUB_TOKEN }} 23 | branch: gh-pages 24 | directory: gh-pages 25 | force: true 26 | -------------------------------------------------------------------------------- /src/utils/eventLoopDelay.ts: -------------------------------------------------------------------------------- 1 | // inspired by https://github.com/tj/node-blocked 2 | 3 | export function EventLoopDelay( 4 | limit: number, 5 | interval: number, 6 | fn: (blocked: boolean, delay: number) => any, 7 | ) { 8 | let start = process.hrtime(); 9 | 10 | const timeout = setInterval(() => { 11 | const delta = process.hrtime(start); 12 | const nanosec = delta[0] * 1e9 + delta[1]; 13 | const ms = nanosec / 1e6; 14 | const n = ms - interval; 15 | if (n > limit) { 16 | fn(true, Math.round(n)); 17 | } else { 18 | fn(false, Math.round(n)); 19 | } 20 | start = process.hrtime(); 21 | }, interval); 22 | 23 | if (timeout.unref) { 24 | timeout.unref(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | open-pull-requests-limit: 999 11 | schedule: 12 | interval: "weekly" 13 | - package-ecosystem: "github-actions" 14 | directory: "/" 15 | open-pull-requests-limit: 999 16 | schedule: 17 | interval: "weekly" 18 | -------------------------------------------------------------------------------- /src/plugins/DelayQueueLock.ts: -------------------------------------------------------------------------------- 1 | // If a job with the same name, queue, and args is already in the delayed queue(s), do not enqueue it again 2 | 3 | import { Plugin } from ".."; 4 | 5 | export class DelayQueueLock extends Plugin { 6 | async beforeEnqueue() { 7 | const timestamps = await this.queueObject.scheduledAt( 8 | this.queue, 9 | this.func, 10 | this.args, 11 | ); 12 | if (timestamps.length > 0) { 13 | return false; 14 | } else { 15 | return true; 16 | } 17 | } 18 | 19 | async afterEnqueue() { 20 | return true; 21 | } 22 | 23 | async beforePerform() { 24 | return true; 25 | } 26 | 27 | async afterPerform() { 28 | return true; 29 | } 30 | } 31 | 32 | exports.DelayQueueLock = DelayQueueLock; 33 | -------------------------------------------------------------------------------- /bin/deploy-docs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | cd "$(dirname "$0")" 6 | cd .. 7 | 8 | ## git config 9 | GIT_USER_NAME='Github Actions for Actionhero' 10 | GIT_USER_EMAIL='admin@actionherojs.com' 11 | 12 | ## Configure a new direcotry to hold the site 13 | rm -rf gh-pages 14 | mkdir gh-pages 15 | cd gh-pages 16 | git init 17 | if git rev-parse --verify origin/gh-pages > /dev/null 2>&1 18 | then 19 | git checkout gh-pages 20 | git rm -rf . 21 | else 22 | git checkout --orphan gh-pages 23 | fi 24 | cd .. 25 | 26 | ## build main's docs 27 | rm -rf docs 28 | mkdir -p docs 29 | npm run docs 30 | cp -a docs/. gh-pages/ 31 | touch gh-pages/.nojekyll 32 | cp images/favicon.ico gh-pages/favicon.ico 33 | cp CNAME gh-pages/CNAME 34 | 35 | ## make the commmit 36 | cd gh-pages 37 | git add -A 38 | git -c user.name="$GIT_USER_NAME" -c user.email="$GIT_USER_EMAIL" commit --allow-empty -m "deploy static site @ $(date)" 39 | -------------------------------------------------------------------------------- /__tests__/plugins/custom_plugins.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { Queue, Job } from "../../src"; 3 | import { CustomPlugin } from "../utils/custom-plugin"; 4 | 5 | describe("plugins", () => { 6 | describe("custom plugins", () => { 7 | test("runs a custom plugin outside of the plugins directory", async () => { 8 | const jobs = { 9 | //@ts-ignore 10 | myJob: { 11 | plugins: [CustomPlugin], 12 | perform: async () => { 13 | throw new Error("should not get here"); 14 | }, 15 | } as Job, 16 | }; 17 | 18 | const queue = new Queue( 19 | { 20 | connection: specHelper.cleanConnectionDetails(), 21 | queue: specHelper.queue, 22 | }, 23 | jobs, 24 | ); 25 | 26 | await queue.connect(); 27 | const enqueueResponse = await queue.enqueue( 28 | specHelper.queue, 29 | "myJob", 30 | [1, 2], 31 | ); 32 | expect(enqueueResponse).toBe(false); 33 | const length = await queue.length(specHelper.queue); 34 | expect(length).toBe(0); 35 | await queue.end(); 36 | }); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /__tests__/core/connectionError.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from "../../src"; 2 | import specHelper from "../utils/specHelper"; 3 | 4 | describe("connection error", () => { 5 | test( 6 | "can provide an error if connection failed", 7 | async () => { 8 | await new Promise(async (resolve) => { 9 | const connectionDetails = { 10 | pkg: specHelper.connectionDetails.pkg, 11 | host: "wronghostname", 12 | password: specHelper.connectionDetails.password, 13 | port: specHelper.connectionDetails.port, 14 | database: specHelper.connectionDetails.database, 15 | namespace: specHelper.connectionDetails.namespace, 16 | options: { maxRetriesPerRequest: 1 }, 17 | }; 18 | 19 | const brokenConnection = new Connection(connectionDetails); 20 | 21 | brokenConnection.on("error", async (error) => { 22 | expect(error.message).toMatch( 23 | /ENOTFOUND|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN/, 24 | ); 25 | }); 26 | 27 | try { 28 | await brokenConnection.connect(); 29 | } catch (error) { 30 | setTimeout(resolve, 3 * 1000); 31 | } 32 | }); 33 | }, 34 | 60 * 1000, 35 | ); 36 | }); 37 | -------------------------------------------------------------------------------- /src/core/plugin.ts: -------------------------------------------------------------------------------- 1 | import { Worker } from "./worker"; 2 | import { Connection } from "./connection"; 3 | import { ParsedJob, Queue } from "./queue"; 4 | 5 | export abstract class Plugin { 6 | name: string; 7 | worker: Connection | Worker | any; 8 | queueObject: Queue; 9 | queue: string; 10 | func: string; 11 | job: ParsedJob; 12 | args: Array; 13 | options: { 14 | [key: string]: any; 15 | }; 16 | 17 | constructor( 18 | worker: Queue | Worker, 19 | func: string, 20 | queue: string, 21 | job: ParsedJob, 22 | args: Array, 23 | options: { 24 | [key: string]: any; 25 | }, 26 | ) { 27 | this.name = this?.constructor?.name || "Node Resque Plugin"; 28 | this.worker = worker; 29 | this.queue = queue; 30 | this.func = func; 31 | this.job = job; 32 | this.args = args; 33 | this.options = options; 34 | 35 | if (this.worker && this.worker.queueObject) { 36 | this.queueObject = this.worker.queueObject; 37 | } else { 38 | this.queueObject = this.worker; 39 | } 40 | } 41 | 42 | abstract beforeEnqueue?(): Promise; 43 | abstract afterEnqueue?(): Promise; 44 | abstract beforePerform?(): Promise; 45 | abstract afterPerform?(): Promise; 46 | } 47 | -------------------------------------------------------------------------------- /src/types/options.ts: -------------------------------------------------------------------------------- 1 | import * as IORedis from "ioredis"; 2 | 3 | export interface ConnectionOptions { 4 | pkg?: string; 5 | host?: string; 6 | port?: number; 7 | database?: number; 8 | namespace?: string | string[]; 9 | looping?: boolean; 10 | options?: any; 11 | redis?: IORedis.Redis | IORedis.Cluster; 12 | scanCount?: number; 13 | } 14 | 15 | export interface QueueOptions extends ConnectionOptions { 16 | connection?: ConnectionOptions; 17 | queue?: string | string[]; 18 | } 19 | 20 | export interface WorkerOptions extends ConnectionOptions { 21 | name?: string; 22 | queues?: Array | string; 23 | timeout?: number; 24 | looping?: boolean; 25 | id?: number; 26 | connection?: ConnectionOptions; 27 | } 28 | 29 | export interface SchedulerOptions extends ConnectionOptions { 30 | name?: string; 31 | timeout?: number; 32 | leaderLockTimeout?: number; 33 | stuckWorkerTimeout?: number; 34 | retryStuckJobs?: boolean; 35 | connection?: ConnectionOptions; 36 | } 37 | 38 | export interface MultiWorkerOptions extends ConnectionOptions { 39 | name?: string; 40 | queues?: Array; 41 | timeout?: number; 42 | maxEventLoopDelay?: number; 43 | checkTimeout?: number; 44 | connection?: ConnectionOptions; 45 | minTaskProcessors?: number; 46 | maxTaskProcessors?: number; 47 | } 48 | 49 | // Re-export for backward compatibility 50 | export { Job } from "./job"; 51 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Evan Tahler ", 3 | "name": "node-resque", 4 | "description": "an opinionated implementation of resque in node", 5 | "license": "Apache-2.0", 6 | "version": "9.3.8", 7 | "homepage": "http://github.com/actionhero/node-resque", 8 | "repository": { 9 | "type": "git", 10 | "url": "git://github.com/actionhero/node-resque.git" 11 | }, 12 | "main": "dist/index", 13 | "types": "dist/index", 14 | "keywords": [ 15 | "delayed", 16 | "queue", 17 | "resque", 18 | "redis", 19 | "work", 20 | "worker", 21 | "background", 22 | "job", 23 | "task" 24 | ], 25 | "engines": { 26 | "node": ">=12.0.0" 27 | }, 28 | "dependencies": { 29 | "ioredis": "^5.6.0" 30 | }, 31 | "devDependencies": { 32 | "@types/jest": "^29.5.14", 33 | "@types/node": "^24.10.1", 34 | "ioredis-mock": "^8.9.0", 35 | "jest": "^29.7.0", 36 | "node-schedule": "^2.1.1", 37 | "prettier": "^3.5.3", 38 | "ts-jest": "^29.3.1", 39 | "ts-node": "^10.9.2", 40 | "typedoc": "^0.28.1", 41 | "typescript": "^5.8.2" 42 | }, 43 | "scripts": { 44 | "prepare": "npm run build && npm run docs", 45 | "pretest": "npm run lint && npm run build", 46 | "lint": "prettier --check src __tests__ examples \"*.md\"", 47 | "pretty": "prettier --write src __tests__ examples \"**/*.md\"", 48 | "test": "jest", 49 | "build": "tsc --declaration", 50 | "docs": "typedoc --out docs --theme default src/index.ts" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /resque-web/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: http://rubygems.org/ 3 | specs: 4 | concurrent-ruby (1.2.2) 5 | connection_pool (2.4.1) 6 | et-orbi (1.2.7) 7 | tzinfo 8 | fugit (1.9.0) 9 | et-orbi (~> 1, >= 1.2.7) 10 | raabro (~> 1.4) 11 | mono_logger (1.1.2) 12 | multi_json (1.15.0) 13 | mustermann (2.0.2) 14 | ruby2_keywords (~> 0.0.1) 15 | raabro (1.4.0) 16 | rack (2.2.8) 17 | rack-protection (2.2.3) 18 | rack 19 | rake (12.3.3) 20 | redis (5.0.8) 21 | redis-client (>= 0.17.0) 22 | redis-client (0.19.0) 23 | connection_pool 24 | redis-namespace (1.11.0) 25 | redis (>= 4) 26 | resque (2.6.0) 27 | mono_logger (~> 1.0) 28 | multi_json (~> 1.0) 29 | redis-namespace (~> 1.6) 30 | sinatra (>= 0.9.2) 31 | resque-retry (1.8.1) 32 | resque (>= 1.25, < 3.0) 33 | resque-scheduler (>= 4.0, < 6.0) 34 | resque-scheduler (4.10.2) 35 | mono_logger (~> 1.0) 36 | redis (>= 3.3) 37 | resque (>= 1.27) 38 | rufus-scheduler (~> 3.2, != 3.3) 39 | ruby2_keywords (0.0.5) 40 | rufus-scheduler (3.9.1) 41 | fugit (~> 1.1, >= 1.1.6) 42 | sinatra (2.2.3) 43 | mustermann (~> 2.0) 44 | rack (~> 2.2) 45 | rack-protection (= 2.2.3) 46 | tilt (~> 2.0) 47 | tilt (2.3.0) 48 | tzinfo (2.0.6) 49 | concurrent-ruby (~> 1.0) 50 | 51 | PLATFORMS 52 | ruby 53 | 54 | DEPENDENCIES 55 | rake 56 | resque 57 | resque-retry 58 | resque-scheduler 59 | sinatra 60 | 61 | BUNDLED WITH 62 | 1.17.2 63 | -------------------------------------------------------------------------------- /examples/performInline.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Worker } from "../src"; 4 | /* In your projects: 5 | import { Worker } from "node-resque"; 6 | */ 7 | 8 | // //////////////////////// 9 | // SET UP THE CONNECTION // 10 | // //////////////////////// 11 | 12 | const connectionDetails = { 13 | pkg: "ioredis", 14 | host: "127.0.0.1", 15 | password: null, 16 | port: 6379, 17 | database: 0, 18 | // namespace: 'resque', 19 | // looping: true, 20 | // options: {password: 'abc'}, 21 | }; 22 | 23 | async function boot() { 24 | // /////////////////////////// 25 | // DEFINE YOUR WORKER TASKS // 26 | // /////////////////////////// 27 | 28 | const jobs = { 29 | add: { 30 | plugins: [], 31 | pluginOptions: { 32 | JobLock: {}, 33 | }, 34 | perform: async (a, b) => { 35 | await new Promise((resolve) => { 36 | setTimeout(resolve, 1000); 37 | }); 38 | const answer = a + b; 39 | return answer; 40 | }, 41 | }, 42 | }; 43 | 44 | // ////////////////////////////// 45 | // BUILD A WORKER & WORK A JOB // 46 | // ////////////////////////////// 47 | 48 | const worker = new Worker( 49 | { connection: connectionDetails, queues: ["math", "otherQueue"] }, 50 | jobs, 51 | ); 52 | await worker.connect(); 53 | 54 | let result = await worker.performInline("add", [1, 2]); 55 | console.log("Result: " + result); 56 | 57 | result = await worker.performInline("add", [5, 8]); 58 | console.log("Result: " + result); 59 | 60 | process.exit(); 61 | } 62 | 63 | boot(); 64 | -------------------------------------------------------------------------------- /resque-web/readme.md: -------------------------------------------------------------------------------- 1 | # Ruby Resque UI 2 | 3 | This directory contains a small ruby project which will run the resque web server. This is contained within the node-resque project so that we can test and confirm that node-resque is interoperable with ruby-resque. 4 | 5 | 1. **install ruby** 6 | 7 | Ensure that you have ruby installed on your system. You can confirm this with `ruby --version`. You can get ruby from [ruby-lang.org](https://www.ruby-lang.org) if you don't have it. OSX comes with ruby, and most linux distributions have a top-level package (i.e.: `apt-get install ruby`) 8 | 9 | 2. **install bundler** 10 | 11 | Bundler is the ruby package manager (think NPM). Ruby uses "gems" (packages), and bundler is a tool that can manage dependencies of a project. A `Gemfile` contains a list of dependancies and a `Gemfile.lock` is like a `npm shinkwrap` output, formally defining gem versions. 12 | 13 | Install bundler with `gem install bundler` (the `gem` application is included with ruby) 14 | 15 | 3. **install the packages** 16 | 17 | From within this directory, run `bundle install`. This equivalent to `npm install` 18 | 19 | 4. **run the application** 20 | 21 | The ruby-resque package includes a web interface which can be "mounted" within a number of common ruby web frameworks, like sintatra, ruby-on-rails, etc. I have included the smallest possible application which is a [`rack`](http://rack.github.io/) application. To run this application, type `bundle exec rackup`. Running this command will boot the server on port `9292` (and the CLI will inform you if this changed). 22 | 23 | This should only be used in development, as there is no security around this web interface, and you can delete everything. 24 | 25 | ### TLDR; 26 | 27 | ```bash 28 | # install ruby 29 | cd ./resque-web 30 | gem install bundler 31 | bundle install 32 | bundle exec rackup 33 | ``` 34 | -------------------------------------------------------------------------------- /src/plugins/QueueLock.ts: -------------------------------------------------------------------------------- 1 | // If a job with the same name, queue, and args is already in the queue, do not enqueue it again 2 | 3 | import { Plugin } from ".."; 4 | 5 | export class QueueLock extends Plugin { 6 | async beforeEnqueue() { 7 | const key = this.key(); 8 | const now = Math.round(new Date().getTime() / 1000); 9 | const timeout = now + this.lockTimeout() + 1; 10 | const set = await this.queueObject.connection.redis.setnx(key, timeout); 11 | 12 | //@ts-ignore 13 | if (set === true || set === 1) { 14 | await this.queueObject.connection.redis.expire(key, this.lockTimeout()); 15 | return true; 16 | } 17 | 18 | const redisTimeout = await this.queueObject.connection.redis.get(key); 19 | const redisTimeoutInt = parseInt(redisTimeout); 20 | if (now <= redisTimeoutInt) { 21 | return false; 22 | } 23 | 24 | await this.queueObject.connection.redis.set(key, timeout); 25 | await this.queueObject.connection.redis.expire(key, this.lockTimeout()); 26 | return true; 27 | } 28 | 29 | async afterEnqueue() { 30 | return true; 31 | } 32 | 33 | async beforePerform() { 34 | const key = this.key(); 35 | await this.queueObject.connection.redis.del(key); 36 | return true; 37 | } 38 | 39 | async afterPerform() { 40 | return true; 41 | } 42 | 43 | lockTimeout() { 44 | if (this.options.lockTimeout) { 45 | return this.options.lockTimeout; 46 | } else { 47 | return 3600; // in seconds 48 | } 49 | } 50 | 51 | key() { 52 | if (this.options.key) { 53 | return typeof this.options.key === "function" 54 | ? this.options.key.apply(this) 55 | : this.options.key; 56 | } else { 57 | const flattenedArgs = JSON.stringify(this.args); 58 | return this.queueObject.connection.key( 59 | "lock", 60 | this.func, 61 | this.queue, 62 | flattenedArgs, 63 | ); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /examples/docker/producer/src/producer.ts: -------------------------------------------------------------------------------- 1 | import { Queue } from "node-resque"; 2 | 3 | /* In your projects: 4 | import { Queue } from require("node-resque"); 5 | */ 6 | 7 | let queue; 8 | 9 | async function boot() { 10 | const connectionDetails = { 11 | pkg: "ioredis", 12 | host: process.env.REDIS_HOST, 13 | }; 14 | 15 | queue = new Queue({ connection: connectionDetails }); 16 | queue.on("error", function (error) { 17 | console.log(error); 18 | }); 19 | 20 | await queue.connect(); 21 | 22 | // keep adding jobs forever... 23 | setInterval(async () => { 24 | console.log(`adding jobs @ ${new Date()}`); 25 | await queue.enqueue("math", "add", [1, 2]); 26 | await queue.enqueue("math", "add", [2, 3]); 27 | await queue.enqueueIn(3000, "math", "subtract", [2, 1]); 28 | }, 1000); 29 | } 30 | 31 | async function shutdown() { 32 | await queue.end(); 33 | console.log(`processes gracefully stopped`); 34 | } 35 | 36 | function awaitHardStop() { 37 | const timeout = process.env.SHUTDOWN_TIMEOUT 38 | ? parseInt(process.env.SHUTDOWN_TIMEOUT) 39 | : 1000 * 30; 40 | return setTimeout(() => { 41 | console.error( 42 | `Process did not terminate within ${timeout}ms. Stopping now!`, 43 | ); 44 | process.nextTick(() => process.exit(1)); 45 | }, timeout); 46 | } 47 | 48 | // handle errors & rejections 49 | process.on("uncaughtException", (error) => { 50 | console.error(error.stack); 51 | process.nextTick(() => process.exit(1)); 52 | }); 53 | 54 | process.on("unhandledRejection", (rejection) => { 55 | console.error(rejection["stack"]); 56 | process.nextTick(() => process.exit(1)); 57 | }); 58 | 59 | // handle signals 60 | process.on("SIGINT", async () => { 61 | console.log(`[ SIGNAL ] - SIGINT`); 62 | let timer = awaitHardStop(); 63 | await shutdown(); 64 | clearTimeout(timer); 65 | }); 66 | 67 | process.on("SIGTERM", async () => { 68 | console.log(`[ SIGNAL ] - SIGTERM`); 69 | let timer = awaitHardStop(); 70 | await shutdown(); 71 | clearTimeout(timer); 72 | }); 73 | 74 | process.on("SIGUSR2", async () => { 75 | console.log(`[ SIGNAL ] - SIGUSR2`); 76 | let timer = awaitHardStop(); 77 | await shutdown(); 78 | clearTimeout(timer); 79 | }); 80 | 81 | boot(); 82 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v6 9 | - name: Use Node.js 20.x 10 | uses: actions/setup-node@v6.0.0 11 | with: 12 | node-version: 20.x 13 | - run: npm ci 14 | - name: save cache 15 | uses: actions/cache@v4.3.0 16 | with: 17 | path: | 18 | node_modules 19 | dist 20 | key: ${{ runner.os }}-cache-${{ hashFiles('**/package-lock.json') }} 21 | 22 | lint: 23 | runs-on: ubuntu-latest 24 | needs: build 25 | steps: 26 | - uses: actions/checkout@v6 27 | - name: Use Node.js 20.x 28 | uses: actions/setup-node@v6.0.0 29 | with: 30 | node-version: 20.x 31 | - name: download cache 32 | uses: actions/cache@v4.3.0 33 | with: 34 | path: | 35 | node_modules 36 | dist 37 | key: ${{ runner.os }}-cache-${{ hashFiles('**/package-lock.json') }} 38 | - run: npm run lint 39 | 40 | test: 41 | runs-on: ubuntu-latest 42 | needs: build 43 | 44 | services: 45 | redis: 46 | image: redis 47 | options: >- 48 | --health-cmd "redis-cli ping" 49 | --health-interval 10s 50 | --health-timeout 5s 51 | --health-retries 5 52 | ports: 53 | - 6379:6379 54 | 55 | strategy: 56 | fail-fast: false 57 | matrix: 58 | node-version: [14.x, 16.x, 18.x, 20.x] 59 | 60 | steps: 61 | - uses: actions/checkout@v6 62 | - name: Use Node.js ${{ matrix.node-version }} 63 | uses: actions/setup-node@v6.0.0 64 | with: 65 | node-version: ${{ matrix.node-version }} 66 | - name: download cache 67 | uses: actions/cache@v4.3.0 68 | with: 69 | path: | 70 | node_modules 71 | dist 72 | key: ${{ runner.os }}-cache-${{ hashFiles('**/package-lock.json') }} 73 | - run: npm rebuild 74 | - run: ./node_modules/.bin/jest --ci --forceExit 75 | env: 76 | REDIS_HOST: localhost 77 | REDIS_PORT: 6379 78 | 79 | complete: 80 | runs-on: ubuntu-latest 81 | needs: [test, lint] 82 | steps: 83 | - run: echo "Done!" 84 | -------------------------------------------------------------------------------- /src/plugins/JobLock.ts: -------------------------------------------------------------------------------- 1 | // If a job with the same name, queue, and args is already running, put this job back in the queue and try later 2 | import { Plugin } from ".."; 3 | 4 | export class JobLock extends Plugin { 5 | async beforeEnqueue() { 6 | return true; 7 | } 8 | 9 | async afterEnqueue() { 10 | return true; 11 | } 12 | 13 | async beforePerform() { 14 | const key = this.key(); 15 | const now = Math.round(new Date().getTime() / 1000); 16 | const timeout = now + this.lockTimeout() + 1; 17 | 18 | const lockedByMe = await this.queueObject.connection.redis.set( 19 | key, 20 | timeout, 21 | "EX", 22 | this.lockTimeout(), 23 | "NX", 24 | ); 25 | if (lockedByMe && lockedByMe.toString().toUpperCase() === "OK") { 26 | return true; 27 | } else { 28 | const options = this.job.pluginOptions; 29 | const toReEnqueue = options.JobLock 30 | ? options.JobLock.reEnqueue !== null && 31 | options.JobLock.reEnqueue !== undefined 32 | ? options.JobLock.reEnqueue 33 | : true 34 | : true; 35 | 36 | if (toReEnqueue) await this.reEnqueue(); 37 | return false; 38 | } 39 | } 40 | 41 | async afterPerform() { 42 | const key = this.key(); 43 | await this.queueObject.connection.redis.del(key); 44 | return true; 45 | } 46 | 47 | async reEnqueue() { 48 | await this.queueObject.enqueueIn( 49 | this.enqueueTimeout(), 50 | this.queue, 51 | this.func, 52 | this.args, 53 | ); 54 | } 55 | 56 | lockTimeout() { 57 | if (this.options.lockTimeout) { 58 | return this.options.lockTimeout; 59 | } else { 60 | return 3600; // in seconds 61 | } 62 | } 63 | 64 | enqueueTimeout() { 65 | if (this.options.enqueueTimeout) { 66 | return this.options.enqueueTimeout; 67 | } else { 68 | return 1001; // in ms 69 | } 70 | } 71 | 72 | key() { 73 | if (this.options.key) { 74 | return typeof this.options.key === "function" 75 | ? this.options.key.apply(this) 76 | : this.options.key; 77 | } else { 78 | const flattenedArgs = JSON.stringify(this.args); 79 | return this.worker.connection.key( 80 | "workerslock", 81 | this.func, 82 | this.queue, 83 | flattenedArgs, 84 | ); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /__tests__/integration/ioredis.ts: -------------------------------------------------------------------------------- 1 | import { Queue, Worker, Scheduler, Job } from "../../src"; 2 | import specHelper from "../utils/specHelper"; 3 | 4 | const connectionDetails = { 5 | pkg: "ioredis", 6 | host: "127.0.0.1", 7 | port: 6379, 8 | database: parseInt(process.env.JEST_WORKER_ID || "0"), 9 | }; 10 | 11 | const jobs = { 12 | add: { 13 | perform: async (a, b) => { 14 | const response = a + b; 15 | return response; 16 | }, 17 | } as Job, 18 | }; 19 | 20 | describe("testing with ioredis package", () => { 21 | let queue: Queue; 22 | let scheduler: Scheduler; 23 | let worker: Worker; 24 | 25 | afterAll(async () => { 26 | await queue.end(); 27 | await scheduler.end(); 28 | await worker.end(); 29 | }); 30 | 31 | test("a queue can be created", async () => { 32 | queue = new Queue({ connection: connectionDetails }, jobs); 33 | await queue.connect(); 34 | }); 35 | 36 | test("a scheduler can be created", async () => { 37 | scheduler = new Scheduler({ connection: connectionDetails }, jobs); 38 | await scheduler.connect(); 39 | // await scheduler.start(); 40 | }); 41 | 42 | test("a worker can be created", async () => { 43 | worker = new Worker( 44 | { 45 | connection: connectionDetails, 46 | queues: ["math"], 47 | timeout: specHelper.timeout, 48 | }, 49 | jobs, 50 | ); 51 | await worker.connect(); 52 | // worker.start(); 53 | }); 54 | 55 | test("a job can be enqueued", async () => { 56 | await queue.enqueueIn(1, "math", "add", [1, 2]); 57 | const times = await queue.scheduledAt("math", "add", [1, 2]); 58 | expect(times.length).toBe(1); 59 | }); 60 | 61 | test("the scheduler can promote the job", async () => { 62 | await scheduler.poll(); 63 | const times = await queue.scheduledAt("math", "add", [1, 2]); 64 | expect(times.length).toBe(0); 65 | const jobsLength = await queue.length("math"); 66 | expect(jobsLength).toBe(1); 67 | }); 68 | 69 | test("the worker can work the job", async () => { 70 | await new Promise(async (resolve) => { 71 | await worker.start(); 72 | worker.on("success", async (q, job, result, duration) => { 73 | expect(q).toBe("math"); 74 | expect(job.class).toBe("add"); 75 | expect(result).toBe(3); 76 | expect(worker.result).toBe(result); 77 | expect(duration).toBeGreaterThanOrEqual(0); 78 | 79 | worker.removeAllListeners("success"); 80 | resolve(null); 81 | }); 82 | }); 83 | }); 84 | }); 85 | -------------------------------------------------------------------------------- /__tests__/plugins/delayedQueueLock.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { Queue, Plugins } from "../../src"; 3 | 4 | let queue: Queue; 5 | const jobDelay = 100; 6 | 7 | const jobs = { 8 | slowAdd: { 9 | plugins: [Plugins.JobLock], 10 | pluginOptions: { jobLock: {} }, 11 | perform: async (a: number, b: number) => { 12 | const answer = a + b; 13 | await new Promise((resolve) => { 14 | setTimeout(resolve, jobDelay); 15 | }); 16 | return answer; 17 | }, 18 | }, 19 | uniqueJob: { 20 | plugins: [Plugins.DelayQueueLock], 21 | pluginOptions: { queueLock: {}, delayQueueLock: {} }, 22 | perform: async (a: number, b: number) => { 23 | const answer = a + b; 24 | return answer; 25 | }, 26 | }, 27 | }; 28 | 29 | describe("plugins", () => { 30 | beforeAll(async () => { 31 | await specHelper.connect(); 32 | await specHelper.cleanup(); 33 | queue = new Queue( 34 | { 35 | connection: specHelper.cleanConnectionDetails(), 36 | queue: [specHelper.queue], 37 | }, 38 | jobs, 39 | ); 40 | queue.connect(); 41 | }); 42 | 43 | afterAll(async () => { 44 | await queue.end(); 45 | await specHelper.cleanup(); 46 | await specHelper.disconnect(); 47 | }); 48 | 49 | beforeEach(async () => { 50 | await specHelper.cleanup(); 51 | }); 52 | 53 | describe("delayQueueLock", () => { 54 | test("will not enque a job with the same args if it is already in the delayed queue", async () => { 55 | await queue.enqueueIn(10 * 1000, specHelper.queue, "uniqueJob", [1, 2]); 56 | await queue.enqueue(specHelper.queue, "uniqueJob", [1, 2]); 57 | const delayedLen = await specHelper.redis.zcount( 58 | specHelper.namespace + ":delayed_queue_schedule", 59 | "-inf", 60 | "+inf", 61 | ); 62 | const queueLen = await queue.length(specHelper.queue); 63 | expect(delayedLen).toBe(1); 64 | expect(queueLen).toBe(0); 65 | }); 66 | 67 | test("will enque a job with the different args", async () => { 68 | await queue.enqueueIn(10 * 1000, specHelper.queue, "uniqueJob", [1, 2]); 69 | await queue.enqueue(specHelper.queue, "uniqueJob", [3, 4]); 70 | const delayedLen = await specHelper.redis.zcount( 71 | specHelper.namespace + ":delayed_queue_schedule", 72 | "-inf", 73 | "+inf", 74 | ); 75 | const queueLen = await queue.length(specHelper.queue); 76 | expect(delayedLen).toBe(1); 77 | expect(queueLen).toBe(1); 78 | }); 79 | }); 80 | }); 81 | -------------------------------------------------------------------------------- /__tests__/integration/ioredis-mock.ts: -------------------------------------------------------------------------------- 1 | import { Queue, Worker, Scheduler, Job } from "../../src"; 2 | import specHelper from "../utils/specHelper"; 3 | 4 | // import * as RedisMock from "ioredis-mock"; // TYPE HACK! 5 | import Redis from "ioredis"; 6 | const RedisMock: typeof Redis = require("ioredis-mock"); 7 | 8 | // for ioredis-mock, we need to re-use a shared connection 9 | // setting "pkg" is important! 10 | const REDIS = new RedisMock(); 11 | const connectionDetails = { redis: REDIS, pkg: "ioredis-mock" }; 12 | 13 | const jobs = { 14 | add: { 15 | perform: async (a, b) => { 16 | const response = a + b; 17 | return response; 18 | }, 19 | } as Job, 20 | }; 21 | 22 | describe("testing with ioredis-mock package", () => { 23 | let queue: Queue; 24 | let scheduler: Scheduler; 25 | let worker: Worker; 26 | 27 | afterAll(async () => { 28 | await queue.end(); 29 | await scheduler.end(); 30 | await worker.end(); 31 | }); 32 | 33 | test("a queue can be created", async () => { 34 | queue = new Queue({ connection: connectionDetails }, jobs); 35 | await queue.connect(); 36 | }); 37 | 38 | test("a scheduler can be created", async () => { 39 | scheduler = new Scheduler({ connection: connectionDetails }, jobs); 40 | await scheduler.connect(); 41 | // await scheduler.start(); 42 | }); 43 | 44 | test("a worker can be created", async () => { 45 | worker = new Worker( 46 | { 47 | connection: connectionDetails, 48 | queues: ["math"], 49 | timeout: specHelper.timeout, 50 | }, 51 | jobs, 52 | ); 53 | await worker.connect(); 54 | // worker.start(); 55 | }); 56 | 57 | test("a job can be enqueued", async () => { 58 | await queue.enqueueIn(1, "math", "add", [1, 2]); 59 | const times = await queue.scheduledAt("math", "add", [1, 2]); 60 | expect(times.length).toBe(1); 61 | }); 62 | 63 | test("the scheduler can promote the job", async () => { 64 | await scheduler.poll(); 65 | const times = await queue.scheduledAt("math", "add", [1, 2]); 66 | expect(times.length).toBe(0); 67 | const jobsLength = await queue.length("math"); 68 | expect(jobsLength).toBe(1); 69 | }); 70 | 71 | test("the worker can work the job", async () => { 72 | await new Promise(async (resolve) => { 73 | await worker.start(); 74 | worker.on("success", async (q, job, result, duration) => { 75 | expect(q).toBe("math"); 76 | expect(job.class).toBe("add"); 77 | expect(result).toBe(3); 78 | expect(worker.result).toBe(result); 79 | expect(duration).toBeGreaterThanOrEqual(0); 80 | 81 | worker.removeAllListeners("success"); 82 | resolve(null); 83 | }); 84 | }); 85 | }); 86 | }); 87 | -------------------------------------------------------------------------------- /examples/docker/README.md: -------------------------------------------------------------------------------- 1 | # node-resque docker example 2 | 3 | This project contains well-crafted docker files that demonstrate how to use node-resque dockerized environment. This project also contains a docker-compose example which will run the `worker` and `producer` against a shared redis image. 4 | 5 | ## Things to note 6 | 7 | - The node-resque applications not only start the workers and scheduler, but also handle signals to gracefully shut them down. If you don't do this, you are likely to loose job data and have "stuck" workers in your environment 8 | - See https://github.com/actionhero/node-resque/issues/319 and https://github.com/actionhero/node-resque/issues/312 for examples 9 | - You should run many instances of the scheduler. In this example every worker node will also be a scuduler. We handle leader election for you 10 | - The docker files themselves should be constructed in a way that will ensure signals will be passed from the OS to your node application. Do not use PM2, npm, yarn, etc to run your app... call it directly. 11 | - You can learn more here https://hynek.me/articles/docker-signals/ 12 | 13 | ## To Run 14 | 15 | ``` 16 | docker-compose up 17 | ``` 18 | 19 | You will see output like: 20 | 21 | ``` 22 | node-resque-producer_1 | adding jobs @ Mon Feb 17 2020 04:12:42 GMT+0000 (Coordinated Universal Time) 23 | node-resque-producer_1 | adding jobs @ Mon Feb 17 2020 04:12:43 GMT+0000 (Coordinated Universal Time) 24 | node-resque-producer_1 | adding jobs @ Mon Feb 17 2020 04:12:44 GMT+0000 (Coordinated Universal Time) 25 | node-resque-producer_1 | adding jobs @ Mon Feb 17 2020 04:12:45 GMT+0000 (Coordinated Universal Time) 26 | node-resque-producer_1 | adding jobs @ Mon Feb 17 2020 04:12:46 GMT+0000 (Coordinated Universal Time) 27 | node-resque-worker_1 | worker check in @ 1581912766 28 | node-resque-worker_1 | scheduler became leader 29 | node-resque-worker_1 | scheduler polling 30 | node-resque-worker_1 | scheduler working timestamp 1581912700 31 | node-resque-worker_1 | scheduler enqueuing job 1581912700 >> {"class":"subtract","queue":"math","args":[2,1]} 32 | node-resque-worker_1 | worker polling math 33 | node-resque-worker_1 | working job math {"class":"add","queue":"math","args":[1,2]} 34 | node-resque-worker_1 | job success math {"class":"add","queue":"math","args":[1,2]} >> 3 (1ms) 35 | node-resque-worker_1 | worker polling math 36 | ``` 37 | 38 | When you stop the cluster, you can then inspect the logs from your image to confirm that the shutdown behavior is what you expected: 39 | 40 | ``` 41 | docker logs -f {your image ID} 42 | 43 | ... (snip) 44 | 45 | scheduler polling 46 | scheduler working timestamp 1581912881 47 | scheduler enqueuing job 1581912881 >> {"class":"subtract","queue":"math","args":[2,1]} 48 | scheduler polling 49 | [ SIGNAL ] - SIGTERM 50 | scheduler ended 51 | worker ended 52 | processes gracefully stopped 53 | ``` 54 | -------------------------------------------------------------------------------- /src/core/pluginRunner.ts: -------------------------------------------------------------------------------- 1 | import { Job } from "../types/job"; 2 | import { Worker } from "./worker"; 3 | import { Queue } from "./queue"; 4 | import { Plugin } from "./plugin"; 5 | 6 | type PluginConstructor = new (...args: any[]) => T & { 7 | [key: string]: Plugin; 8 | }; 9 | 10 | export async function RunPlugins( 11 | self: Queue | Worker, 12 | type: string, 13 | func: string, 14 | queue: string, 15 | job: Job, 16 | args: Array, 17 | pluginCounter?: number, 18 | ): Promise { 19 | if (!job) return true; 20 | if (!pluginCounter) pluginCounter = 0; 21 | if ( 22 | job.plugins === null || 23 | job.plugins === undefined || 24 | job.plugins.length === 0 25 | ) { 26 | return true; 27 | } 28 | if (pluginCounter >= job.plugins.length) return true; 29 | 30 | const pluginRefrence = job.plugins[pluginCounter]; 31 | const toRun = await RunPlugin( 32 | self, 33 | pluginRefrence, 34 | type, 35 | func, 36 | queue, 37 | job, 38 | args, 39 | ); 40 | pluginCounter++; 41 | if (toRun === false) return false; 42 | 43 | return RunPlugins(self, type, func, queue, job, args, pluginCounter); 44 | } 45 | 46 | export async function RunPlugin( 47 | self: Queue | Worker, 48 | PluginReference: string | PluginConstructor, 49 | type: string, 50 | func: string, 51 | queue: string, 52 | job: Job, 53 | args: Array, 54 | ): Promise { 55 | if (!job) return true; 56 | 57 | let pluginName: string; 58 | if (typeof PluginReference === "function") { 59 | // @ts-ignore 60 | pluginName = new PluginReference(self, func, queue, job, args, {}).name; 61 | } else if (typeof pluginName === "function") { 62 | pluginName = pluginName["name"]; 63 | } 64 | 65 | let pluginOptions = null; 66 | 67 | if ( 68 | self.jobs[func].pluginOptions && 69 | self.jobs[func].pluginOptions[pluginName] 70 | ) { 71 | pluginOptions = self.jobs[func].pluginOptions[pluginName]; 72 | } else { 73 | pluginOptions = {}; 74 | } 75 | 76 | let plugin: { [key: string]: Plugin }; 77 | if (typeof PluginReference === "string") { 78 | const PluginConstructor = require(`./../plugins/${PluginReference}`)[ 79 | PluginReference 80 | ]; 81 | plugin = new PluginConstructor(self, func, queue, job, args, pluginOptions); 82 | } else if (typeof PluginReference === "function") { 83 | // @ts-ignore 84 | plugin = new PluginReference(self, func, queue, job, args, pluginOptions); 85 | } else { 86 | throw new Error("Plugin must be the constructor name or an object"); 87 | } 88 | 89 | if ( 90 | plugin[type] === null || 91 | plugin[type] === undefined || 92 | typeof plugin[type] !== "function" 93 | ) { 94 | return true; 95 | } 96 | 97 | // @ts-ignore 98 | return plugin[type](); 99 | } 100 | -------------------------------------------------------------------------------- /examples/errorExample.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Worker } from "../src"; 4 | /* In your projects: 5 | import { Queue, Worker } from "node-resque"; 6 | */ 7 | 8 | // //////////////////////// 9 | // SET UP THE CONNECTION // 10 | // //////////////////////// 11 | 12 | const connectionDetails = { 13 | pkg: "ioredis", 14 | host: "127.0.0.1", 15 | password: null, 16 | port: 6379, 17 | database: 0, 18 | // namespace: 'resque', 19 | // looping: true, 20 | // // options: {password: 'abc'}, 21 | }; 22 | 23 | async function boot() { 24 | // /////////////////////////// 25 | // DEFINE YOUR WORKER TASKS // 26 | // /////////////////////////// 27 | 28 | let jobsToComplete = 0; 29 | 30 | const jobs = { 31 | brokenJob: { 32 | plugins: [], 33 | pluginOptions: {}, 34 | perform: function (a, b) { 35 | jobsToComplete--; 36 | tryShutdown(); 37 | 38 | throw new Error("broken message from job"); 39 | }, 40 | }, 41 | }; 42 | 43 | // just a helper for this demo 44 | async function tryShutdown() { 45 | if (jobsToComplete === 0) { 46 | await new Promise((resolve) => { 47 | setTimeout(resolve, 500); 48 | }); 49 | await worker.end(); 50 | process.exit(); 51 | } 52 | } 53 | 54 | // ///////////////// 55 | // START A WORKER // 56 | // ///////////////// 57 | 58 | const worker = new Worker( 59 | { connection: connectionDetails, queues: ["default"] }, 60 | jobs, 61 | ); 62 | await worker.connect(); 63 | worker.start(); 64 | 65 | // ////////////////////// 66 | // REGESTER FOR EVENTS // 67 | // ////////////////////// 68 | 69 | worker.on("start", () => { 70 | console.log("worker started"); 71 | }); 72 | worker.on("end", () => { 73 | console.log("worker ended"); 74 | }); 75 | worker.on("cleaning_worker", (worker, pid) => { 76 | console.log(`cleaning old worker ${worker}`); 77 | }); 78 | worker.on("poll", (queue) => { 79 | console.log(`worker polling ${queue}`); 80 | }); 81 | worker.on("job", (queue, job) => { 82 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 83 | }); 84 | worker.on("reEnqueue", (queue, job, plugin) => { 85 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 86 | }); 87 | worker.on("success", (queue, job, result) => { 88 | console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); 89 | }); 90 | worker.on("failure", (queue, job, failure) => { 91 | console.log(`job failure ${queue} ${JSON.stringify(job)} >> ${failure}`); 92 | }); 93 | worker.on("error", (error, queue, job) => { 94 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 95 | }); 96 | worker.on("pause", () => { 97 | console.log("worker paused"); 98 | }); 99 | 100 | // ///////////////////// 101 | // CONNECT TO A QUEUE // 102 | // ///////////////////// 103 | 104 | const queue = new Queue({ connection: connectionDetails }, jobs); 105 | await queue.connect(); 106 | await queue.enqueue("default", "brokenJob", [1, 2]); 107 | jobsToComplete = 1; 108 | } 109 | 110 | boot(); 111 | -------------------------------------------------------------------------------- /__tests__/utils/specHelper.ts: -------------------------------------------------------------------------------- 1 | import Redis from "ioredis"; 2 | import * as NodeResque from "../../src/index"; 3 | 4 | const namespace = `resque-test-${process.env.JEST_WORKER_ID || 0}`; 5 | const queue = "test_queue"; 6 | const pkg = "ioredis"; 7 | 8 | const SpecHelper = { 9 | pkg: pkg, 10 | namespace: namespace, 11 | queue: queue, 12 | timeout: 500, 13 | smallTimeout: 3, 14 | redis: null as Redis, 15 | connectionDetails: { 16 | pkg: pkg, 17 | host: process.env.REDIS_HOST || "127.0.0.1", 18 | password: "", 19 | port: 6379, 20 | database: parseInt(process.env.JEST_WORKER_ID || "0"), 21 | namespace: namespace, 22 | // looping: true 23 | }, 24 | 25 | connect: async function () { 26 | if (!this.connectionDetails.options) this.connectionDetails.options = {}; 27 | this.connectionDetails.options.db = 28 | this.connectionDetails?.options?.database; 29 | this.redis = new Redis( 30 | this.connectionDetails.port, 31 | this.connectionDetails.host, 32 | this.connectionDetails.options, 33 | ); 34 | 35 | this.redis.setMaxListeners(0); 36 | if ( 37 | this.connectionDetails.password !== null && 38 | this.connectionDetails.password !== "" 39 | ) { 40 | await this.redis.auth(this.connectionDetails.password); 41 | } 42 | await this.redis.select(this.connectionDetails.database); 43 | this.connectionDetails.redis = this.redis; 44 | }, 45 | 46 | cleanup: async function () { 47 | const keys = await this.redis.keys(this.namespace + "*"); 48 | if (keys.length > 0) await this.redis.del(keys); 49 | }, 50 | 51 | disconnect: async function () { 52 | if (typeof this.redis.disconnect === "function") { 53 | await this.redis.disconnect(); 54 | } else if (typeof this.redis.quit === "function") { 55 | await this.redis.quit(); 56 | } 57 | 58 | delete this.redis; 59 | delete this.connectionDetails.redis; 60 | }, 61 | 62 | startAll: async function (jobs: NodeResque.Jobs) { 63 | const Worker = NodeResque.Worker; 64 | const Scheduler = NodeResque.Scheduler; 65 | const Queue = NodeResque.Queue; 66 | 67 | this.worker = new Worker( 68 | { 69 | //@ts-ignore 70 | connection: { redis: this.redis }, 71 | queues: this.queue, 72 | timeout: this.timeout, 73 | }, 74 | jobs, 75 | ); 76 | await this.worker.connect(); 77 | 78 | this.scheduler = new Scheduler({ 79 | connection: { redis: this.redis }, 80 | timeout: this.timeout, 81 | }); 82 | 83 | await this.scheduler.connect(); 84 | 85 | this.queue = new Queue({ connection: { redis: this.redis } }); 86 | await this.queue.connect(); 87 | }, 88 | 89 | endAll: async function () { 90 | await this.worker.end(); 91 | await this.scheduler.end(); 92 | }, 93 | 94 | popFromQueue: async function () { 95 | return this.redis.lpop(this.namespace + ":queue:" + this.queue); 96 | }, 97 | 98 | cleanConnectionDetails: function () { 99 | interface connectionDetails { 100 | database: number; 101 | namespace: string; 102 | } 103 | 104 | const out: connectionDetails = { 105 | database: parseInt(process.env.JEST_WORKER_ID || "0"), 106 | namespace: namespace, 107 | }; 108 | 109 | for (const i in this.connectionDetails) { 110 | if (i !== "redis") { 111 | //@ts-ignore 112 | out[i] = this.connectionDetails[i]; 113 | } 114 | } 115 | 116 | return out; 117 | }, 118 | }; 119 | 120 | export default SpecHelper; 121 | -------------------------------------------------------------------------------- /examples/customPluginExample.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Plugin, Worker, Queue } from "../src"; 4 | /* In your projects: 5 | import { Worker, Scheduler, Queue } from "node-resque"; 6 | */ 7 | 8 | // //////////////////////// 9 | // SET UP THE CONNECTION // 10 | // //////////////////////// 11 | 12 | const connectionDetails = { 13 | pkg: "ioredis", 14 | host: "127.0.0.1", 15 | password: null, 16 | port: 6379, 17 | database: 0, 18 | // namespace: 'resque', 19 | // looping: true, 20 | // options: {password: 'abc'}, 21 | }; 22 | 23 | // //////////////////// 24 | // BUILD THE PLUGIN // 25 | // //////////////////// 26 | 27 | class MyPlugin extends Plugin { 28 | constructor(...args) { 29 | // @ts-ignore 30 | super(...args); 31 | this.name = "MyPlugin"; 32 | } 33 | 34 | beforePerform() { 35 | console.log(this.options.messagePrefix + " | " + JSON.stringify(this.args)); 36 | return true; 37 | } 38 | 39 | beforeEnqueue() { 40 | return true; 41 | } 42 | afterEnqueue() { 43 | return true; 44 | } 45 | afterPerform() { 46 | return true; 47 | } 48 | } 49 | 50 | async function boot() { 51 | // /////////////////////////// 52 | // DEFINE YOUR WORKER TASKS // 53 | // /////////////////////////// 54 | 55 | let jobsToComplete = 0; 56 | 57 | const jobs = { 58 | jobby: { 59 | plugins: [MyPlugin], 60 | pluginOptions: { 61 | MyPlugin: { messagePrefix: "[🤡🤡🤡]" }, 62 | }, 63 | perform: (a, b) => { 64 | jobsToComplete--; 65 | tryShutdown(); 66 | }, 67 | }, 68 | }; 69 | 70 | // just a helper for this demo 71 | async function tryShutdown() { 72 | if (jobsToComplete === 0) { 73 | await new Promise((resolve) => { 74 | setTimeout(resolve, 500); 75 | }); 76 | await worker.end(); 77 | process.exit(); 78 | } 79 | } 80 | 81 | // ///////////////// 82 | // START A WORKER // 83 | // ///////////////// 84 | 85 | const worker = new Worker( 86 | { connection: connectionDetails, queues: ["default"] }, 87 | jobs, 88 | ); 89 | await worker.connect(); 90 | worker.start(); 91 | 92 | // ////////////////////// 93 | // REGESTER FOR EVENTS // 94 | // ////////////////////// 95 | 96 | worker.on("start", () => { 97 | console.log("worker started"); 98 | }); 99 | worker.on("end", () => { 100 | console.log("worker ended"); 101 | }); 102 | worker.on("cleaning_worker", (worker, pid) => { 103 | console.log(`cleaning old worker ${worker}`); 104 | }); 105 | worker.on("poll", (queue) => { 106 | console.log(`worker polling ${queue}`); 107 | }); 108 | worker.on("job", (queue, job) => { 109 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 110 | }); 111 | worker.on("reEnqueue", (queue, job, plugin) => { 112 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 113 | }); 114 | worker.on("success", (queue, job, result) => { 115 | console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); 116 | }); 117 | worker.on("failure", (queue, job, failure) => { 118 | console.log(`job failure ${queue} ${JSON.stringify(job)} >> ${failure}`); 119 | }); 120 | worker.on("error", (error, queue, job) => { 121 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 122 | }); 123 | worker.on("pause", () => { 124 | console.log("worker paused"); 125 | }); 126 | 127 | // ///////////////////// 128 | // CONNECT TO A QUEUE // 129 | // ///////////////////// 130 | 131 | const queue = new Queue({ connection: connectionDetails }, jobs); 132 | queue.on("error", function (error) { 133 | console.log(error); 134 | }); 135 | await queue.connect(); 136 | await queue.enqueue("default", "jobby", [1, 2]); 137 | jobsToComplete = 1; 138 | } 139 | 140 | boot(); 141 | -------------------------------------------------------------------------------- /__tests__/plugins/noop.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { Scheduler, Plugins, Queue, Worker, Job } from "../../src"; 3 | 4 | let queue: Queue; 5 | let scheduler: Scheduler; 6 | let loggedErrors = []; 7 | 8 | const jobs = { 9 | brokenJob: { 10 | plugins: [Plugins.Noop], 11 | pluginOptions: { 12 | Noop: { 13 | logger: (error: Error) => { 14 | loggedErrors.push(error); 15 | }, 16 | }, 17 | }, 18 | perform: () => { 19 | throw new Error("BUSTED"); 20 | }, 21 | } as Job, 22 | happyJob: { 23 | plugins: [Plugins.Noop], 24 | pluginOptions: { 25 | Noop: { 26 | logger: (error: Error) => { 27 | loggedErrors.push(error); 28 | }, 29 | }, 30 | }, 31 | perform: async () => { 32 | // nothing 33 | }, 34 | } as Job, 35 | }; 36 | 37 | describe("plugins", () => { 38 | describe("noop", () => { 39 | beforeAll(async () => { 40 | await specHelper.connect(); 41 | await specHelper.cleanup(); 42 | queue = new Queue( 43 | { 44 | connection: specHelper.cleanConnectionDetails(), 45 | queue: specHelper.queue, 46 | }, 47 | jobs, 48 | ); 49 | scheduler = new Scheduler({ 50 | connection: specHelper.cleanConnectionDetails(), 51 | timeout: specHelper.timeout, 52 | }); 53 | await scheduler.connect(); 54 | scheduler.start(); 55 | await queue.connect(); 56 | }); 57 | 58 | beforeEach(() => { 59 | loggedErrors = []; 60 | }); 61 | 62 | afterAll(async () => { 63 | await scheduler.end(); 64 | await queue.end(); 65 | await specHelper.disconnect(); 66 | }); 67 | 68 | afterEach(async () => { 69 | await specHelper.cleanup(); 70 | }); 71 | 72 | test("will work fine with non-crashing jobs", async () => { 73 | await new Promise(async (resolve) => { 74 | await queue.enqueue(specHelper.queue, "happyJob", [1, 2]); 75 | const length = await queue.length(specHelper.queue); 76 | expect(length).toBe(1); 77 | 78 | const worker = new Worker( 79 | { 80 | connection: specHelper.cleanConnectionDetails(), 81 | timeout: specHelper.timeout, 82 | queues: [specHelper.queue], 83 | }, 84 | jobs, 85 | ); 86 | 87 | worker.on("success", async () => { 88 | expect(loggedErrors.length).toBe(0); 89 | const length = await specHelper.redis.llen("resque_test:failed"); 90 | expect(length).toBe(0); 91 | await worker.end(); 92 | resolve(null); 93 | }); 94 | 95 | worker.on("failure", () => { 96 | throw new Error("should never get here"); 97 | }); 98 | 99 | await worker.connect(); 100 | await worker.start(); 101 | }); 102 | }); 103 | 104 | test("will prevent any failed jobs from ending in the failed queue", async () => { 105 | await new Promise(async (resolve) => { 106 | await queue.enqueue(specHelper.queue, "brokenJob", [1, 2]); 107 | const length = await queue.length(specHelper.queue); 108 | expect(length).toBe(1); 109 | 110 | const worker = new Worker( 111 | { 112 | connection: specHelper.cleanConnectionDetails(), 113 | timeout: specHelper.timeout, 114 | queues: [specHelper.queue], 115 | }, 116 | jobs, 117 | ); 118 | 119 | worker.on("success", async () => { 120 | expect(loggedErrors.length).toBe(1); 121 | const length = await specHelper.redis.llen("resque_test:failed"); 122 | expect(length).toBe(0); 123 | await worker.end(); 124 | resolve(null); 125 | }); 126 | 127 | await worker.connect(); 128 | worker.on("failure", () => { 129 | throw new Error("should never get here"); 130 | }); 131 | worker.start(); 132 | }); 133 | }); 134 | }); 135 | }); 136 | -------------------------------------------------------------------------------- /examples/retry.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Plugins, Scheduler, Worker } from "../src"; 4 | /* In your projects: 5 | import { Queue, Plugins, Scheduler, Worker } from "node-resque"; 6 | */ 7 | 8 | // //////////////////////// 9 | // SET UP THE CONNECTION // 10 | // //////////////////////// 11 | 12 | const connectionDetails = { 13 | pkg: "ioredis", 14 | host: "127.0.0.1", 15 | password: null, 16 | port: 6379, 17 | database: 0, 18 | // namespace: 'resque', 19 | // looping: true, 20 | // options: {password: 'abc'}, 21 | }; 22 | 23 | // /////////////////////////// 24 | // DEFINE YOUR WORKER TASKS // 25 | // /////////////////////////// 26 | 27 | const jobs = { 28 | add: { 29 | plugins: [Plugins.Retry], 30 | pluginOptions: { 31 | Retry: { 32 | retryLimit: 3, 33 | // retryDelay: 1000, 34 | backoffStrategy: [1000 * 10, 1000 * 20, 1000 * 30], 35 | }, 36 | }, 37 | perform: function (a, b) { 38 | if (a < 0) { 39 | throw new Error("NEGATIVE NUMBERS ARE HARD :("); 40 | } else { 41 | return a + b; 42 | } 43 | }, 44 | }, 45 | }; 46 | 47 | async function boot() { 48 | // ///////////////// 49 | // START A WORKER // 50 | // ///////////////// 51 | 52 | const worker = new Worker( 53 | { connection: connectionDetails, queues: ["math"] }, 54 | jobs, 55 | ); 56 | await worker.connect(); 57 | worker.start(); 58 | 59 | // //////////////////// 60 | // START A SCHEDULER // 61 | // //////////////////// 62 | 63 | const scheduler = new Scheduler({ connection: connectionDetails }); 64 | await scheduler.connect(); 65 | scheduler.start(); 66 | 67 | // ////////////////////// 68 | // REGESTER FOR EVENTS // 69 | // ////////////////////// 70 | 71 | worker.on("start", () => { 72 | console.log("worker started"); 73 | }); 74 | worker.on("end", () => { 75 | console.log("worker ended"); 76 | }); 77 | worker.on("cleaning_worker", (worker, pid) => { 78 | console.log(`cleaning old worker ${worker}`); 79 | }); 80 | worker.on("poll", (queue) => { 81 | console.log(`worker polling ${queue}`); 82 | }); 83 | worker.on("job", (queue, job) => { 84 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 85 | }); 86 | worker.on("reEnqueue", (queue, job, plugin) => { 87 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 88 | }); 89 | worker.on("success", (queue, job, result) => { 90 | console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); 91 | }); 92 | worker.on("error", (error, queue, job) => { 93 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 94 | }); 95 | worker.on("pause", () => { 96 | console.log("worker paused"); 97 | }); 98 | worker.on("failure", (queue, job, failure) => { 99 | console.log( 100 | "job failure " + queue + " " + JSON.stringify(job) + " >> " + failure, 101 | ); 102 | setTimeout(process.exit, 2000); 103 | }); 104 | 105 | scheduler.on("start", () => { 106 | console.log("scheduler started"); 107 | }); 108 | scheduler.on("end", () => { 109 | console.log("scheduler ended"); 110 | }); 111 | scheduler.on("poll", () => { 112 | console.log("scheduler polling"); 113 | }); 114 | scheduler.on("leader", () => { 115 | console.log("scheduler became leader"); 116 | }); 117 | scheduler.on("error", (error) => { 118 | console.log(`scheduler error >> ${error}`); 119 | }); 120 | scheduler.on("workingTimestamp", (timestamp) => { 121 | console.log(`scheduler working timestamp ${timestamp}`); 122 | }); 123 | scheduler.on("transferredJob", (timestamp, job) => { 124 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 125 | }); 126 | 127 | // ///////////////////////////////// 128 | // CONNECT TO A QUEUE AND WORK IT // 129 | // ///////////////////////////////// 130 | 131 | const queue = new Queue({ connection: connectionDetails }, jobs); 132 | queue.on("error", function (error) { 133 | console.log(error); 134 | }); 135 | await queue.connect(); 136 | queue.enqueue("math", "add", [1, 2]); 137 | queue.enqueue("math", "add", [-1, 2]); 138 | } 139 | 140 | boot(); 141 | -------------------------------------------------------------------------------- /examples/stuckWorker.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Scheduler, Worker } from "../src"; 4 | /* In your projects: 5 | import { Queue, Scheduler, Worker } from "node-resque"; 6 | */ 7 | 8 | async function boot() { 9 | // //////////////////////// 10 | // SET UP THE CONNECTION // 11 | // //////////////////////// 12 | 13 | const connectionDetails = { 14 | pkg: "ioredis", 15 | host: "127.0.0.1", 16 | password: null, 17 | port: 6379, 18 | database: 0, 19 | // namespace: 'resque', 20 | // looping: true, 21 | // options: {password: 'abc'}, 22 | }; 23 | 24 | // /////////////////////////// 25 | // DEFINE YOUR WORKER TASKS // 26 | // /////////////////////////// 27 | 28 | const jobs = { 29 | stuck: { 30 | perform: async function () { 31 | console.log(`${this.name} is starting stuck job...`); 32 | await new Promise((resolve) => { 33 | clearTimeout(this.pingTimer); // stop the worker from checkin in, like the process crashed 34 | setTimeout(resolve, 60 * 60 * 1000); // 1 hour job 35 | }); 36 | }, 37 | }, 38 | }; 39 | 40 | // ///////////////// 41 | // START A WORKER // 42 | // ///////////////// 43 | 44 | const worker = new Worker( 45 | { connection: connectionDetails, queues: ["stuckJobs"] }, 46 | jobs, 47 | ); 48 | await worker.connect(); 49 | worker.start(); 50 | 51 | // //////////////////// 52 | // START A SCHEDULER // 53 | // //////////////////// 54 | 55 | const scheduler = new Scheduler({ 56 | stuckWorkerTimeout: 10 * 1000, 57 | connection: connectionDetails, 58 | }); 59 | 60 | await scheduler.connect(); 61 | scheduler.start(); 62 | 63 | // ////////////////////// 64 | // REGESTER FOR EVENTS // 65 | // ////////////////////// 66 | 67 | worker.on("start", () => { 68 | console.log("worker started"); 69 | }); 70 | worker.on("end", () => { 71 | console.log("worker ended"); 72 | }); 73 | worker.on("cleaning_worker", (worker, pid) => { 74 | console.log(`cleaning old worker ${worker}`); 75 | }); 76 | worker.on("poll", (queue) => { 77 | console.log(`worker polling ${queue}`); 78 | }); 79 | worker.on("ping", (time) => { 80 | console.log(`worker check in @ ${time}`); 81 | }); 82 | worker.on("job", (queue, job) => { 83 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 84 | }); 85 | worker.on("reEnqueue", (queue, job, plugin) => { 86 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 87 | }); 88 | worker.on("success", (queue, job, result) => { 89 | console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); 90 | }); 91 | worker.on("failure", (queue, job, failure) => { 92 | console.log(`job failure ${queue} ${JSON.stringify(job)} >> ${failure}`); 93 | }); 94 | worker.on("error", (error, queue, job) => { 95 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 96 | }); 97 | worker.on("pause", () => { 98 | console.log("worker paused"); 99 | }); 100 | 101 | scheduler.on("start", () => { 102 | console.log("scheduler started"); 103 | }); 104 | scheduler.on("end", () => { 105 | console.log("scheduler ended"); 106 | }); 107 | scheduler.on("poll", () => { 108 | console.log("scheduler polling"); 109 | }); 110 | scheduler.on("leader", () => { 111 | console.log("scheduler became leader"); 112 | }); 113 | scheduler.on("error", (error) => { 114 | console.log(`scheduler error >> ${error}`); 115 | }); 116 | scheduler.on("workingTimestamp", (timestamp) => { 117 | console.log(`scheduler working timestamp ${timestamp}`); 118 | }); 119 | scheduler.on("transferredJob", (timestamp, job) => { 120 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 121 | }); 122 | 123 | scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => { 124 | console.log( 125 | `failing ${workerName} (stuck for ${delta}s) and failing job: ${JSON.stringify( 126 | errorPayload, 127 | )}`, 128 | ); 129 | process.exit(); 130 | }); 131 | 132 | // ////////////////////// 133 | // CONNECT TO A QUEUE // 134 | // ////////////////////// 135 | 136 | const queue = new Queue({ connection: connectionDetails }, jobs); 137 | queue.on("error", function (error) { 138 | console.log(error); 139 | }); 140 | await queue.connect(); 141 | await queue.enqueue("stuckJobs", "stuck", ["oh no"]); 142 | } 143 | 144 | boot(); 145 | -------------------------------------------------------------------------------- /examples/multiWorker.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { MultiWorker, Queue } from "../src"; 4 | /* In your projects: 5 | import { MultiWorker, Queue } from "node-resque"; 6 | */ 7 | 8 | const connectionDetails = { 9 | pkg: "ioredis", 10 | host: "127.0.0.1", 11 | password: null, 12 | port: 6379, 13 | database: 0, 14 | // namespace: 'resque', 15 | // looping: true, 16 | // options: {password: 'abc'}, 17 | }; 18 | 19 | // Or, to share a single connection connection 20 | 21 | // const ioredis = require('ioredis'); 22 | // const connectionDetails = { redis: new ioredis() }; 23 | 24 | async function boot() { 25 | // ////////////// 26 | // DEFINE JOBS // 27 | // ////////////// 28 | 29 | const blockingSleep = function (naptime) { 30 | const now = new Date(); 31 | const startingMSeconds = now.getTime(); 32 | let sleeping = true; 33 | let alarm; 34 | while (sleeping) { 35 | alarm = new Date(); 36 | const alarmMSeconds = alarm.getTime(); 37 | if (alarmMSeconds - startingMSeconds > naptime) { 38 | sleeping = false; 39 | } 40 | } 41 | }; 42 | 43 | const jobs = { 44 | slowSleepJob: { 45 | plugins: [], 46 | pluginOptions: {}, 47 | perform: async () => { 48 | const start = new Date().getTime(); 49 | await new Promise((resolve) => { 50 | setTimeout(resolve, 1000); 51 | }); 52 | return new Date().getTime() - start; 53 | }, 54 | }, 55 | slowCPUJob: { 56 | plugins: [], 57 | pluginOptions: {}, 58 | perform: async () => { 59 | const start = new Date().getTime(); 60 | blockingSleep(1000); 61 | return new Date().getTime() - start; 62 | }, 63 | }, 64 | }; 65 | 66 | // //////////////// 67 | // ENQUEUE TASKS // 68 | // //////////////// 69 | 70 | const queue = new Queue({ connection: connectionDetails }, jobs); 71 | await queue.connect(); 72 | let i = 0; 73 | while (i < 10) { 74 | await queue.enqueue("slowQueue", "slowCPUJob", []); 75 | i++; 76 | } 77 | 78 | i = 0; 79 | while (i < 100) { 80 | await queue.enqueue("slowQueue", "slowSleepJob", []); 81 | i++; 82 | } 83 | 84 | // /////// 85 | // WORK // 86 | // /////// 87 | 88 | const multiWorker = new MultiWorker( 89 | { 90 | connection: connectionDetails, 91 | queues: ["slowQueue"], 92 | }, 93 | jobs, 94 | ); 95 | 96 | // normal worker emitters 97 | multiWorker.on("start", (workerId) => { 98 | console.log(`worker[${workerId}] started`); 99 | }); 100 | multiWorker.on("end", (workerId) => { 101 | console.log(`worker[${workerId}] ended`); 102 | }); 103 | multiWorker.on("cleaning_worker", (workerId, worker, pid) => { 104 | console.log("cleaning old worker " + worker); 105 | }); 106 | multiWorker.on("poll", (workerId, queue) => { 107 | console.log(`worker[${workerId}] polling ${queue}`); 108 | }); 109 | multiWorker.on("job", (workerId, queue, job) => { 110 | console.log( 111 | `worker[${workerId}] working job ${queue} ${JSON.stringify(job)}`, 112 | ); 113 | }); 114 | multiWorker.on("reEnqueue", (workerId, queue, job, plugin) => { 115 | console.log( 116 | `worker[${workerId}] reEnqueue job (${plugin}) ${queue} ${JSON.stringify( 117 | job, 118 | )}`, 119 | ); 120 | }); 121 | multiWorker.on("success", (workerId, queue, job, result, duration) => { 122 | console.log( 123 | `worker[${workerId}] job success ${queue} ${JSON.stringify( 124 | job, 125 | )} >> ${result} (${duration}ms)`, 126 | ); 127 | }); 128 | multiWorker.on("failure", (workerId, queue, job, failure, duration) => { 129 | console.log( 130 | `worker[${workerId}] job failure ${queue} ${JSON.stringify( 131 | job, 132 | )} >> ${failure} (${duration}ms)`, 133 | ); 134 | }); 135 | multiWorker.on("error", (error, workerId, queue, job) => { 136 | console.log( 137 | `worker[${workerId}] error ${queue} ${JSON.stringify(job)} >> ${error}`, 138 | ); 139 | }); 140 | multiWorker.on("pause", (workerId) => { 141 | console.log(`worker[${workerId}] paused`); 142 | }); 143 | 144 | // multiWorker emitters 145 | multiWorker.on("multiWorkerAction", (verb, delay) => { 146 | console.log( 147 | `*** checked for worker status: ${verb} (event loop delay: ${delay}ms)`, 148 | ); 149 | }); 150 | 151 | multiWorker.start(); 152 | 153 | process.on("SIGINT", async () => { 154 | await multiWorker.stop(); 155 | console.log("*** ALL STOPPED ***"); 156 | process.exit(); 157 | }); 158 | } 159 | 160 | boot(); 161 | -------------------------------------------------------------------------------- /examples/scheduledJobs.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | // We'll use https://github.com/tejasmanohar/node-schedule for this example, 4 | // but there are many other excellent node scheduling projects 5 | import * as schedule from "node-schedule"; 6 | import { Queue, Scheduler, Worker } from "../src"; 7 | /* In your projects: 8 | import { Queue, Scheduler, Worker } from "node-resque"; 9 | */ 10 | 11 | // //////////////////////// 12 | // SET UP THE CONNECTION // 13 | // //////////////////////// 14 | 15 | const connectionDetails = { 16 | pkg: "ioredis", 17 | host: "127.0.0.1", 18 | password: null, 19 | port: 6379, 20 | database: 0, 21 | // namespace: 'resque', 22 | // looping: true, 23 | // options: {password: 'abc'}, 24 | }; 25 | 26 | async function boot() { 27 | // /////////////////////////// 28 | // DEFINE YOUR WORKER TASKS // 29 | // /////////////////////////// 30 | 31 | const jobs = { 32 | ticktock: (time, callback) => { 33 | console.log(`*** THE TIME IS ${time} ***`); 34 | return true; 35 | }, 36 | }; 37 | 38 | // ///////////////// 39 | // START A WORKER // 40 | // ///////////////// 41 | 42 | const worker = new Worker( 43 | { connection: connectionDetails, queues: ["time"] }, 44 | jobs, 45 | ); 46 | await worker.connect(); 47 | worker.start(); 48 | 49 | // //////////////////// 50 | // START A SCHEDULER // 51 | // //////////////////// 52 | 53 | const scheduler = new Scheduler({ connection: connectionDetails }); 54 | await scheduler.connect(); 55 | scheduler.start(); 56 | 57 | // ////////////////////// 58 | // REGESTER FOR EVENTS // 59 | // ////////////////////// 60 | 61 | worker.on("start", () => { 62 | console.log("worker started"); 63 | }); 64 | worker.on("end", () => { 65 | console.log("worker ended"); 66 | }); 67 | worker.on("cleaning_worker", (worker, pid) => { 68 | console.log(`cleaning old worker ${worker}`); 69 | }); 70 | worker.on("poll", (queue) => { 71 | console.log(`worker polling ${queue}`); 72 | }); 73 | worker.on("job", (queue, job) => { 74 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 75 | }); 76 | worker.on("reEnqueue", (queue, job, plugin) => { 77 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 78 | }); 79 | worker.on("success", (queue, job, result) => { 80 | console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); 81 | }); 82 | worker.on("failure", (queue, job, failure) => { 83 | console.log(`job failure ${queue} ${JSON.stringify(job)} >> ${failure}`); 84 | }); 85 | worker.on("error", (error, queue, job) => { 86 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 87 | }); 88 | worker.on("pause", () => { 89 | console.log("worker paused"); 90 | }); 91 | 92 | scheduler.on("start", () => { 93 | console.log("scheduler started"); 94 | }); 95 | scheduler.on("end", () => { 96 | console.log("scheduler ended"); 97 | }); 98 | scheduler.on("poll", () => { 99 | console.log("scheduler polling"); 100 | }); 101 | scheduler.on("leader", () => { 102 | console.log("scheduler became leader"); 103 | }); 104 | scheduler.on("error", (error) => { 105 | console.log(`scheduler error >> ${error}`); 106 | }); 107 | scheduler.on("workingTimestamp", (timestamp) => { 108 | console.log(`scheduler working timestamp ${timestamp}`); 109 | }); 110 | scheduler.on("transferredJob", (timestamp, job) => { 111 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 112 | }); 113 | 114 | // ////////////// 115 | // DEFINE JOBS // 116 | // ////////////// 117 | 118 | const queue = new Queue({ connection: connectionDetails }, jobs); 119 | queue.on("error", function (error) { 120 | console.log(error); 121 | }); 122 | await queue.connect(); 123 | schedule.scheduleJob("0,10,20,30,40,50 * * * * *", async () => { 124 | // do this job every 10 seconds, cron style 125 | // we want to ensure that only one instance of this job is scheduled in our enviornment at once, 126 | // no matter how many schedulers we have running 127 | if (scheduler.leader) { 128 | console.log(">>> enquing a job"); 129 | await queue.enqueue("time", "ticktock", [new Date().toString()]); 130 | } 131 | }); 132 | 133 | // //////////////////// 134 | // SHUTDOWN HELPERS // 135 | // //////////////////// 136 | 137 | const shutdown = async () => { 138 | await scheduler.end(); 139 | await worker.end(); 140 | console.log("bye."); 141 | process.exit(); 142 | }; 143 | 144 | process.on("SIGTERM", shutdown); 145 | process.on("SIGINT", shutdown); 146 | } 147 | 148 | boot(); 149 | -------------------------------------------------------------------------------- /__tests__/core/multiWorker.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { MultiWorker, Queue } from "../../src"; 3 | 4 | // we enable this just for this test as the worker scaling is CPU dependent, and other parallel tests can cause shenanigans 5 | jest.retryTimes(3, { logErrorsBeforeRetry: true }); 6 | 7 | let queue: Queue; 8 | let multiWorker: MultiWorker; 9 | const checkTimeout = specHelper.timeout / 10; 10 | const minTaskProcessors = 1; 11 | const maxTaskProcessors = 5; 12 | 13 | const blockingSleep = (naptime: number) => { 14 | let sleeping = true; 15 | const now = new Date(); 16 | let alarm; 17 | const startingMSeconds = now.getTime(); 18 | while (sleeping) { 19 | alarm = new Date(); 20 | const alarmMSeconds = alarm.getTime(); 21 | if (alarmMSeconds - startingMSeconds > naptime) { 22 | sleeping = false; 23 | } 24 | } 25 | }; 26 | 27 | const jobs = { 28 | slowSleepJob: { 29 | plugins: [] as string[], 30 | pluginOptions: {}, 31 | perform: async () => { 32 | await new Promise((resolve) => { 33 | setTimeout(() => { 34 | resolve(new Date().getTime()); 35 | }, 1000); 36 | }); 37 | }, 38 | }, 39 | slowCPUJob: { 40 | plugins: [] as string[], 41 | pluginOptions: {}, 42 | perform: async () => { 43 | blockingSleep(1000); 44 | return new Date().getTime(); 45 | }, 46 | }, 47 | }; 48 | 49 | describe("multiWorker", () => { 50 | beforeAll(async () => { 51 | await specHelper.connect(); 52 | queue = new Queue({ 53 | connection: specHelper.cleanConnectionDetails(), 54 | queue: specHelper.queue, 55 | }); 56 | await queue.connect(); 57 | 58 | multiWorker = new MultiWorker( 59 | { 60 | connection: specHelper.cleanConnectionDetails(), 61 | timeout: specHelper.timeout, 62 | checkTimeout: checkTimeout, 63 | minTaskProcessors: minTaskProcessors, 64 | maxTaskProcessors: maxTaskProcessors, 65 | queues: [specHelper.queue], 66 | }, 67 | jobs, 68 | ); 69 | 70 | await multiWorker.end(); 71 | 72 | multiWorker.on("error", (error) => { 73 | throw error; 74 | }); 75 | }, 30 * 1000); 76 | 77 | afterEach(async () => { 78 | await queue.delQueue(specHelper.queue); 79 | }); 80 | 81 | afterAll(async () => { 82 | await queue.end(); 83 | await specHelper.disconnect(); 84 | }); 85 | 86 | test("should never have less than one worker", async () => { 87 | expect(multiWorker.workers.length).toBe(0); 88 | await multiWorker.start(); 89 | await new Promise((resolve) => { 90 | setTimeout(resolve, checkTimeout * 3 + 500); 91 | }); 92 | 93 | expect(multiWorker.workers.length).toBeGreaterThan(0); 94 | await multiWorker.end(); 95 | }); 96 | 97 | test( 98 | "should stop adding workers when the max is hit & CPU utilization is low", 99 | async () => { 100 | let i = 0; 101 | while (i < 100) { 102 | await queue.enqueue(specHelper.queue, "slowSleepJob", []); 103 | i++; 104 | } 105 | 106 | await multiWorker.start(); 107 | await new Promise((resolve) => { 108 | setTimeout(resolve, checkTimeout * 30); 109 | }); 110 | expect(multiWorker.workers.length).toBe(maxTaskProcessors); 111 | await multiWorker.end(); 112 | }, 113 | 10 * 1000, 114 | ); 115 | 116 | test( 117 | "should not add workers when CPU utilization is high", 118 | async () => { 119 | let i = 0; 120 | while (i < 100) { 121 | await queue.enqueue(specHelper.queue, "slowCPUJob", []); 122 | i++; 123 | } 124 | 125 | await multiWorker.start(); 126 | await new Promise((resolve) => { 127 | setTimeout(resolve, checkTimeout * 30); 128 | }); 129 | expect(multiWorker.workers.length).toBe(minTaskProcessors); 130 | await multiWorker.end(); 131 | }, 132 | 30 * 1000, 133 | ); 134 | 135 | test("should pass on all worker emits to the instance of multiWorker", async () => { 136 | await new Promise(async (resolve) => { 137 | await queue.enqueue(specHelper.queue, "missingJob", []); 138 | 139 | multiWorker.start(); 140 | 141 | multiWorker.on( 142 | "failure", 143 | async (workerId, queue, job, error, duration) => { 144 | expect(String(error)).toBe( 145 | 'Error: No job defined for class "missingJob"', 146 | ); 147 | expect(duration).toBeGreaterThanOrEqual(0); 148 | multiWorker.removeAllListeners("error"); 149 | await multiWorker.end(); 150 | resolve(null); 151 | }, 152 | ); 153 | }); 154 | }); 155 | }); 156 | -------------------------------------------------------------------------------- /examples/docker/worker/src/worker.ts: -------------------------------------------------------------------------------- 1 | import { Worker, Scheduler } from "node-resque"; 2 | 3 | /* In your projects: 4 | const { Worker, Scheduler } = require("node-resque"); 5 | */ 6 | 7 | let worker; 8 | let scheduler; 9 | 10 | async function boot() { 11 | const connectionDetails = { 12 | pkg: "ioredis", 13 | host: process.env.REDIS_HOST, 14 | }; 15 | 16 | const jobs = { 17 | add: { 18 | perform: async (a, b) => { 19 | const answer = a + b; 20 | return answer; 21 | }, 22 | }, 23 | subtract: { 24 | perform: (a, b) => { 25 | const answer = a - b; 26 | return answer; 27 | }, 28 | }, 29 | }; 30 | 31 | worker = new Worker( 32 | { connection: connectionDetails, queues: ["math", "otherQueue"] }, 33 | jobs, 34 | ); 35 | await worker.connect(); 36 | worker.start(); 37 | 38 | worker.on("start", () => { 39 | console.log("worker started"); 40 | }); 41 | worker.on("end", () => { 42 | console.log("worker ended"); 43 | }); 44 | worker.on("cleaning_worker", (worker, pid) => { 45 | console.log(`cleaning old worker ${worker}`); 46 | }); 47 | worker.on("poll", (queue) => { 48 | console.log(`worker polling ${queue}`); 49 | }); 50 | worker.on("ping", (time) => { 51 | console.log(`worker check in @ ${time}`); 52 | }); 53 | worker.on("job", (queue, job) => { 54 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 55 | }); 56 | worker.on("reEnqueue", (queue, job, plugin) => { 57 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 58 | }); 59 | worker.on("success", (queue, job, result, duration) => { 60 | console.log( 61 | `job success ${queue} ${JSON.stringify( 62 | job, 63 | )} >> ${result} (${duration}ms)`, 64 | ); 65 | }); 66 | worker.on("failure", (queue, job, failure, duration) => { 67 | console.log( 68 | `job failure ${queue} ${JSON.stringify( 69 | job, 70 | )} >> ${failure} (${duration}ms)`, 71 | ); 72 | }); 73 | worker.on("error", (error, queue, job) => { 74 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 75 | }); 76 | worker.on("pause", () => { 77 | console.log("worker paused"); 78 | }); 79 | 80 | scheduler = new Scheduler({ connection: connectionDetails }); 81 | await scheduler.connect(); 82 | scheduler.start(); 83 | 84 | scheduler.on("start", () => { 85 | console.log("scheduler started"); 86 | }); 87 | scheduler.on("end", () => { 88 | console.log("scheduler ended"); 89 | }); 90 | scheduler.on("poll", () => { 91 | console.log("scheduler polling"); 92 | }); 93 | scheduler.on("leader", () => { 94 | console.log("scheduler became leader"); 95 | }); 96 | scheduler.on("error", (error) => { 97 | console.log(`scheduler error >> ${error}`); 98 | }); 99 | scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => { 100 | console.log( 101 | `failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`, 102 | ); 103 | }); 104 | scheduler.on("workingTimestamp", (timestamp) => { 105 | console.log(`scheduler working timestamp ${timestamp}`); 106 | }); 107 | scheduler.on("transferredJob", (timestamp, job) => { 108 | console.log( 109 | `scheduler enqueuing job ${timestamp} >> ${JSON.stringify(job)}`, 110 | ); 111 | }); 112 | } 113 | 114 | async function shutdown() { 115 | await scheduler.end(); 116 | await worker.end(); 117 | console.log(`processes gracefully stopped`); 118 | } 119 | 120 | function awaitHardStop() { 121 | const timeout = process.env.SHUTDOWN_TIMEOUT 122 | ? parseInt(process.env.SHUTDOWN_TIMEOUT) 123 | : 1000 * 30; 124 | return setTimeout(() => { 125 | console.error( 126 | `Process did not terminate within ${timeout}ms. Stopping now!`, 127 | ); 128 | process.nextTick(() => process.exit(1)); 129 | }, timeout); 130 | } 131 | 132 | // handle errors & rejections 133 | process.on("uncaughtException", (error) => { 134 | console.error(error.stack); 135 | process.nextTick(() => process.exit(1)); 136 | }); 137 | 138 | process.on("unhandledRejection", (rejection) => { 139 | console.error(rejection["stack"]); 140 | process.nextTick(() => process.exit(1)); 141 | }); 142 | 143 | // handle signals 144 | process.on("SIGINT", async () => { 145 | console.log(`[ SIGNAL ] - SIGINT`); 146 | let timer = awaitHardStop(); 147 | await shutdown(); 148 | clearTimeout(timer); 149 | }); 150 | 151 | process.on("SIGTERM", async () => { 152 | console.log(`[ SIGNAL ] - SIGTERM`); 153 | let timer = awaitHardStop(); 154 | await shutdown(); 155 | clearTimeout(timer); 156 | }); 157 | 158 | process.on("SIGUSR2", async () => { 159 | console.log(`[ SIGNAL ] - SIGUSR2`); 160 | let timer = awaitHardStop(); 161 | await shutdown(); 162 | clearTimeout(timer); 163 | }); 164 | 165 | boot(); 166 | -------------------------------------------------------------------------------- /src/plugins/Retry.ts: -------------------------------------------------------------------------------- 1 | // If a job fails, retry it N times before finally placing it into the failed queue 2 | // a port of some of the features in https://github.com/lantins/resque-retry 3 | 4 | import * as os from "os"; 5 | import { Plugin, Worker, ParsedJob, Queue } from ".."; 6 | export class Retry extends Plugin { 7 | constructor( 8 | worker: Queue | Worker, 9 | func: string, 10 | queue: string, 11 | job: ParsedJob, 12 | args: Array, 13 | options: { 14 | [key: string]: any; 15 | }, 16 | ) { 17 | super(worker, func, queue, job, args, options); 18 | 19 | if (!this.options.retryLimit) { 20 | this.options.retryLimit = 1; 21 | } 22 | if (!this.options.retryDelay) { 23 | this.options.retryDelay = 1000 * 5; 24 | } 25 | if (!this.options.backoffStrategy) { 26 | this.options.backoffStrategy = null; 27 | } 28 | } 29 | 30 | async beforeEnqueue() { 31 | return true; 32 | } 33 | 34 | async afterEnqueue() { 35 | return true; 36 | } 37 | 38 | async beforePerform() { 39 | return true; 40 | } 41 | 42 | async afterPerform() { 43 | if (!this.worker.error) { 44 | await this.cleanup(); 45 | return true; 46 | } 47 | 48 | const remaining = await this.attemptUp(); 49 | await this.saveLastError(); 50 | 51 | if (remaining <= 0) { 52 | await this.cleanup(); 53 | throw this.worker.error; 54 | } 55 | 56 | let nextTryDelay = this.options.retryDelay; 57 | if (Array.isArray(this.options.backoffStrategy)) { 58 | let index = this.options.retryLimit - remaining - 1; 59 | if (index > this.options.backoffStrategy.length - 1) { 60 | index = this.options.backoffStrategy.length - 1; 61 | } 62 | nextTryDelay = this.options.backoffStrategy[index]; 63 | } 64 | 65 | await this.queueObject.enqueueIn( 66 | nextTryDelay, 67 | this.queue, 68 | this.func, 69 | this.args, 70 | ); 71 | 72 | this.job.args = this.args; 73 | this.worker.emit("reEnqueue", this.queue, this.job, { 74 | delay: nextTryDelay, 75 | remainingAttempts: remaining, 76 | err: this.worker.error, 77 | }); 78 | 79 | await this.redis().decr( 80 | this.queueObject.connection.key("stat", "processed"), 81 | ); 82 | await this.redis().decr( 83 | this.queueObject.connection.key("stat", "processed", this.worker.name), 84 | ); 85 | 86 | await this.redis().incr(this.queueObject.connection.key("stat", "failed")); 87 | await this.redis().incr( 88 | this.queueObject.connection.key("stat", "failed", this.worker.name), 89 | ); 90 | 91 | delete this.worker.error; 92 | return true; 93 | } 94 | 95 | argsKey() { 96 | if (!this.args || this.args.length === 0) { 97 | return ""; 98 | } 99 | return this.args 100 | .map(function (elem) { 101 | return typeof elem === "object" ? JSON.stringify(elem) : elem; 102 | }) 103 | .join("-"); 104 | } 105 | 106 | retryKey() { 107 | return this.queueObject.connection 108 | .key("resque-retry", this.func, this.argsKey()) 109 | .replace(/\s/, ""); 110 | } 111 | 112 | failureKey() { 113 | return this.queueObject.connection 114 | .key("failure-resque-retry:" + this.func + ":" + this.argsKey()) 115 | .replace(/\s/, ""); 116 | } 117 | 118 | maxDelay() { 119 | let maxDelay = this.options.retryDelay || 1; 120 | if (Array.isArray(this.options.backoffStrategy)) { 121 | this.options.backoffStrategy.forEach(function (d) { 122 | if (d > maxDelay) { 123 | maxDelay = d; 124 | } 125 | }); 126 | } 127 | 128 | return maxDelay; 129 | } 130 | 131 | redis() { 132 | return this.queueObject.connection.redis; 133 | } 134 | 135 | async attemptUp() { 136 | const key = this.retryKey(); 137 | await this.redis().setnx(key, -1); 138 | const retryCount = await this.redis().incr(key); 139 | await this.redis().expire(key, this.maxDelay()); 140 | 141 | return this.options.retryLimit - retryCount - 1; 142 | } 143 | 144 | async saveLastError() { 145 | const now = new Date(); 146 | const failedAt = 147 | "" + 148 | now.getFullYear() + 149 | "/" + 150 | ("0" + (now.getMonth() + 1)).slice(-2) + 151 | "/" + 152 | ("0" + now.getDate()).slice(-2) + 153 | " " + 154 | ("0" + now.getHours()).slice(-2) + 155 | ":" + 156 | ("0" + now.getMinutes()).slice(-2) + 157 | ":" + 158 | ("0" + now.getSeconds()).slice(-2); 159 | const backtrace = this.worker.error.stack 160 | ? this.worker.error.stack.split(os.EOL) || [] 161 | : []; 162 | 163 | const data = { 164 | failed_at: failedAt, 165 | payload: this.args, 166 | exception: String(this.worker.error), 167 | error: String(this.worker.error), 168 | backtrace: backtrace, 169 | worker: this.func, 170 | queue: this.queue, 171 | }; 172 | 173 | await this.redis().setex( 174 | this.failureKey(), 175 | this.maxDelay(), 176 | JSON.stringify(data), 177 | ); 178 | } 179 | 180 | async cleanup() { 181 | await this.redis().del(this.retryKey()); 182 | await this.redis().del(this.failureKey()); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /examples/cluster.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Plugins, Scheduler, Worker } from "../src"; 4 | /* In your projects: 5 | import { Queue, Plugins, Scheduler, Worker } from "node-resque"; 6 | */ 7 | 8 | import * as Redis from "ioredis"; 9 | 10 | async function boot() { 11 | // //////////////////////// 12 | // SET UP THE CONNECTION // 13 | // //////////////////////// 14 | 15 | const connection = new Redis.Cluster([{ host: "127.0.0.1", port: 7000 }]); 16 | 17 | // /////////////////////////// 18 | // DEFINE YOUR WORKER TASKS // 19 | // /////////////////////////// 20 | 21 | let jobsToComplete = 0; 22 | 23 | const jobs = { 24 | add: { 25 | plugins: [Plugins.JobLock], 26 | pluginOptions: { 27 | JobLock: {}, 28 | }, 29 | perform: async (a: number, b: number) => { 30 | await new Promise((resolve) => { 31 | setTimeout(resolve, 1000); 32 | }); 33 | jobsToComplete--; 34 | tryShutdown(); 35 | 36 | const answer = a + b; 37 | return answer; 38 | }, 39 | }, 40 | subtract: { 41 | perform: async (a: number, b: number) => { 42 | jobsToComplete--; 43 | tryShutdown(); 44 | 45 | const answer = a - b; 46 | return answer; 47 | }, 48 | }, 49 | }; 50 | 51 | // just a helper for this demo 52 | async function tryShutdown() { 53 | if (jobsToComplete === 0) { 54 | await new Promise((resolve) => { 55 | setTimeout(resolve, 500); 56 | }); 57 | await scheduler.end(); 58 | await worker.end(); 59 | process.exit(); 60 | } 61 | } 62 | 63 | // ///////////////// 64 | // START A WORKER // 65 | // ///////////////// 66 | 67 | const worker = new Worker( 68 | { connection, queues: ["math", "otherQueue"] }, 69 | jobs, 70 | ); 71 | await worker.connect(); 72 | worker.start(); 73 | 74 | // //////////////////// 75 | // START A SCHEDULER // 76 | // //////////////////// 77 | 78 | const scheduler = new Scheduler({ connection }); 79 | await scheduler.connect(); 80 | scheduler.start(); 81 | 82 | // ////////////////////// 83 | // REGESTER FOR EVENTS // 84 | // ////////////////////// 85 | 86 | worker.on("start", () => { 87 | console.log("worker started"); 88 | }); 89 | worker.on("end", () => { 90 | console.log("worker ended"); 91 | }); 92 | worker.on("cleaning_worker", (worker, pid) => { 93 | console.log(`cleaning old worker ${worker}`); 94 | }); 95 | worker.on("poll", (queue) => { 96 | console.log(`worker polling ${queue}`); 97 | }); 98 | worker.on("ping", (time) => { 99 | console.log(`worker check in @ ${time}`); 100 | }); 101 | worker.on("job", (queue, job) => { 102 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 103 | }); 104 | worker.on("reEnqueue", (queue, job, plugin) => { 105 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 106 | }); 107 | worker.on("success", (queue, job, result, duration) => { 108 | console.log( 109 | `job success ${queue} ${JSON.stringify( 110 | job, 111 | )} >> ${result} (${duration}ms)`, 112 | ); 113 | }); 114 | worker.on("failure", (queue, job, failure, duration) => { 115 | console.log( 116 | `job failure ${queue} ${JSON.stringify( 117 | job, 118 | )} >> ${failure} (${duration}ms)`, 119 | ); 120 | }); 121 | worker.on("error", (error, queue, job) => { 122 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 123 | }); 124 | worker.on("pause", () => { 125 | console.log("worker paused"); 126 | }); 127 | 128 | scheduler.on("start", () => { 129 | console.log("scheduler started"); 130 | }); 131 | scheduler.on("end", () => { 132 | console.log("scheduler ended"); 133 | }); 134 | scheduler.on("poll", () => { 135 | console.log("scheduler polling"); 136 | }); 137 | scheduler.on("leader", () => { 138 | console.log("scheduler became leader"); 139 | }); 140 | scheduler.on("error", (error) => { 141 | console.log(`scheduler error >> ${error}`); 142 | }); 143 | scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => { 144 | console.log( 145 | `failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`, 146 | ); 147 | }); 148 | scheduler.on("workingTimestamp", (timestamp) => { 149 | console.log(`scheduler working timestamp ${timestamp}`); 150 | }); 151 | scheduler.on("transferredJob", (timestamp, job) => { 152 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 153 | }); 154 | 155 | // ////////////////////// 156 | // CONNECT TO A QUEUE // 157 | // ////////////////////// 158 | 159 | const queue = new Queue({ connection }, jobs); 160 | queue.on("error", function (error) { 161 | console.log(error); 162 | }); 163 | await queue.connect(); 164 | await queue.enqueue("math", "add", [1, 2]); 165 | await queue.enqueue("math", "add", [1, 2]); 166 | await queue.enqueue("math", "add", [2, 3]); 167 | await queue.enqueueIn(3000, "math", "subtract", [2, 1]); 168 | jobsToComplete = 4; 169 | 170 | // check stats 171 | console.log(await queue.stats()); 172 | } 173 | 174 | boot(); 175 | 176 | // and when you are done 177 | // await queue.end() 178 | // await scheduler.end() 179 | // await worker.end() 180 | -------------------------------------------------------------------------------- /examples/example-mock.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Plugins, Scheduler, Worker } from "../src"; 4 | /* In your projects: 5 | import { Queue, Plugins, Scheduler, Worker } from "node-resque"; 6 | */ 7 | 8 | import * as RedisMock from "ioredis-mock"; 9 | 10 | async function boot() { 11 | // //////////////////////// 12 | // SET UP THE CONNECTION // 13 | // //////////////////////// 14 | 15 | // for ioredis-mock, we need to re-use a shared connection 16 | // setting "pkg" is important! 17 | const connectionDetails = { redis: new RedisMock(), pkg: "ioredis-mock" }; 18 | 19 | // /////////////////////////// 20 | // DEFINE YOUR WORKER TASKS // 21 | // /////////////////////////// 22 | 23 | let jobsToComplete = 0; 24 | 25 | const jobs = { 26 | add: { 27 | plugins: [Plugins.JobLock], 28 | pluginOptions: { 29 | JobLock: {}, 30 | }, 31 | perform: async (a, b) => { 32 | await new Promise((resolve) => { 33 | setTimeout(resolve, 1000); 34 | }); 35 | jobsToComplete--; 36 | tryShutdown(); 37 | 38 | const answer = a + b; 39 | return answer; 40 | }, 41 | }, 42 | subtract: { 43 | perform: (a, b) => { 44 | jobsToComplete--; 45 | tryShutdown(); 46 | 47 | const answer = a - b; 48 | return answer; 49 | }, 50 | }, 51 | }; 52 | 53 | // just a helper for this demo 54 | async function tryShutdown() { 55 | if (jobsToComplete === 0) { 56 | await new Promise((resolve) => { 57 | setTimeout(resolve, 500); 58 | }); 59 | await scheduler.end(); 60 | await worker.end(); 61 | process.exit(); 62 | } 63 | } 64 | 65 | // ///////////////// 66 | // START A WORKER // 67 | // ///////////////// 68 | 69 | const worker = new Worker( 70 | { connection: connectionDetails, queues: ["math", "otherQueue"] }, 71 | jobs, 72 | ); 73 | await worker.connect(); 74 | worker.start(); 75 | 76 | // //////////////////// 77 | // START A SCHEDULER // 78 | // //////////////////// 79 | 80 | const scheduler = new Scheduler({ connection: connectionDetails }); 81 | await scheduler.connect(); 82 | scheduler.start(); 83 | 84 | // ////////////////////// 85 | // REGESTER FOR EVENTS // 86 | // ////////////////////// 87 | 88 | worker.on("start", () => { 89 | console.log("worker started"); 90 | }); 91 | worker.on("end", () => { 92 | console.log("worker ended"); 93 | }); 94 | worker.on("cleaning_worker", (worker, pid) => { 95 | console.log(`cleaning old worker ${worker}`); 96 | }); 97 | worker.on("poll", (queue) => { 98 | console.log(`worker polling ${queue}`); 99 | }); 100 | worker.on("ping", (time) => { 101 | console.log(`worker check in @ ${time}`); 102 | }); 103 | worker.on("job", (queue, job) => { 104 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 105 | }); 106 | worker.on("reEnqueue", (queue, job, plugin) => { 107 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 108 | }); 109 | worker.on("success", (queue, job, result, duration) => { 110 | console.log( 111 | `job success ${queue} ${JSON.stringify( 112 | job, 113 | )} >> ${result} (${duration}ms)`, 114 | ); 115 | }); 116 | worker.on("failure", (queue, job, failure, duration) => { 117 | console.log( 118 | `job failure ${queue} ${JSON.stringify( 119 | job, 120 | )} >> ${failure} (${duration}ms)`, 121 | ); 122 | }); 123 | worker.on("error", (error, queue, job) => { 124 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 125 | }); 126 | worker.on("pause", () => { 127 | console.log("worker paused"); 128 | }); 129 | 130 | scheduler.on("start", () => { 131 | console.log("scheduler started"); 132 | }); 133 | scheduler.on("end", () => { 134 | console.log("scheduler ended"); 135 | }); 136 | scheduler.on("poll", () => { 137 | console.log("scheduler polling"); 138 | }); 139 | scheduler.on("leader", () => { 140 | console.log("scheduler became leader"); 141 | }); 142 | scheduler.on("error", (error) => { 143 | console.log(`scheduler error >> ${error}`); 144 | }); 145 | scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => { 146 | console.log( 147 | `failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`, 148 | ); 149 | }); 150 | scheduler.on("workingTimestamp", (timestamp) => { 151 | console.log(`scheduler working timestamp ${timestamp}`); 152 | }); 153 | scheduler.on("transferredJob", (timestamp, job) => { 154 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 155 | }); 156 | 157 | // ////////////////////// 158 | // CONNECT TO A QUEUE // 159 | // ////////////////////// 160 | 161 | const queue = new Queue({ connection: connectionDetails }, jobs); 162 | queue.on("error", function (error) { 163 | console.log(error); 164 | }); 165 | await queue.connect(); 166 | await queue.enqueue("math", "add", [1, 2]); 167 | await queue.enqueue("math", "add", [1, 2]); 168 | await queue.enqueue("math", "add", [2, 3]); 169 | await queue.enqueueIn(3000, "math", "subtract", [2, 1]); 170 | jobsToComplete = 4; 171 | } 172 | 173 | boot(); 174 | 175 | // and when you are done 176 | // await queue.end() 177 | // await scheduler.end() 178 | // await worker.end() 179 | -------------------------------------------------------------------------------- /examples/example.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { Queue, Plugins, Scheduler, Worker } from "../src/index"; 4 | /* In your projects: 5 | import { Queue, Plugins, Scheduler, Worker } from "node-resque"; 6 | */ 7 | 8 | async function boot() { 9 | // //////////////////////// 10 | // SET UP THE CONNECTION // 11 | // //////////////////////// 12 | 13 | const connectionDetails = { 14 | pkg: "ioredis", 15 | host: "127.0.0.1", 16 | password: null as string, 17 | port: 6379, 18 | database: 0, 19 | // namespace: 'resque', 20 | // looping: true, 21 | // options: {password: 'abc'}, 22 | }; 23 | 24 | // /////////////////////////// 25 | // DEFINE YOUR WORKER TASKS // 26 | // /////////////////////////// 27 | 28 | let jobsToComplete = 0; 29 | 30 | const jobs = { 31 | add: { 32 | plugins: [Plugins.JobLock], 33 | pluginOptions: { 34 | JobLock: {}, 35 | }, 36 | perform: async (a: number, b: number) => { 37 | await new Promise((resolve) => { 38 | setTimeout(resolve, 1000); 39 | }); 40 | jobsToComplete--; 41 | tryShutdown(); 42 | 43 | const answer = a + b; 44 | return answer; 45 | }, 46 | }, 47 | subtract: { 48 | perform: async (a: number, b: number) => { 49 | jobsToComplete--; 50 | tryShutdown(); 51 | 52 | const answer = a - b; 53 | return answer; 54 | }, 55 | }, 56 | }; 57 | 58 | // just a helper for this demo 59 | async function tryShutdown() { 60 | if (jobsToComplete === 0) { 61 | await new Promise((resolve) => { 62 | setTimeout(resolve, 500); 63 | }); 64 | await scheduler.end(); 65 | await worker.end(); 66 | process.exit(); 67 | } 68 | } 69 | 70 | // ///////////////// 71 | // START A WORKER // 72 | // ///////////////// 73 | 74 | const worker = new Worker( 75 | { connection: connectionDetails, queues: ["math", "otherQueue"] }, 76 | jobs, 77 | ); 78 | await worker.connect(); 79 | worker.start(); 80 | 81 | // //////////////////// 82 | // START A SCHEDULER // 83 | // //////////////////// 84 | 85 | const scheduler = new Scheduler({ connection: connectionDetails }); 86 | await scheduler.connect(); 87 | scheduler.start(); 88 | 89 | // ////////////////////// 90 | // REGESTER FOR EVENTS // 91 | // ////////////////////// 92 | 93 | worker.on("start", () => { 94 | console.log("worker started"); 95 | }); 96 | worker.on("end", () => { 97 | console.log("worker ended"); 98 | }); 99 | worker.on("cleaning_worker", (worker, pid) => { 100 | console.log(`cleaning old worker ${worker}`); 101 | }); 102 | worker.on("poll", (queue) => { 103 | console.log(`worker polling ${queue}`); 104 | }); 105 | worker.on("ping", (time) => { 106 | console.log(`worker check in @ ${time}`); 107 | }); 108 | worker.on("job", (queue, job) => { 109 | console.log(`working job ${queue} ${JSON.stringify(job)}`); 110 | }); 111 | worker.on("reEnqueue", (queue, job, plugin) => { 112 | console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); 113 | }); 114 | worker.on("success", (queue, job, result, duration) => { 115 | console.log( 116 | `job success ${queue} ${JSON.stringify( 117 | job, 118 | )} >> ${result} (${duration}ms)`, 119 | ); 120 | }); 121 | worker.on("failure", (queue, job, failure, duration) => { 122 | console.log( 123 | `job failure ${queue} ${JSON.stringify( 124 | job, 125 | )} >> ${failure} (${duration}ms)`, 126 | ); 127 | }); 128 | worker.on("error", (error, queue, job) => { 129 | console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); 130 | }); 131 | worker.on("pause", () => { 132 | console.log("worker paused"); 133 | }); 134 | 135 | scheduler.on("start", () => { 136 | console.log("scheduler started"); 137 | }); 138 | scheduler.on("end", () => { 139 | console.log("scheduler ended"); 140 | }); 141 | scheduler.on("poll", () => { 142 | console.log("scheduler polling"); 143 | }); 144 | scheduler.on("leader", () => { 145 | console.log("scheduler became leader"); 146 | }); 147 | scheduler.on("error", (error) => { 148 | console.log(`scheduler error >> ${error}`); 149 | }); 150 | scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => { 151 | console.log( 152 | `failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`, 153 | ); 154 | }); 155 | scheduler.on("workingTimestamp", (timestamp) => { 156 | console.log(`scheduler working timestamp ${timestamp}`); 157 | }); 158 | scheduler.on("transferredJob", (timestamp, job) => { 159 | console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); 160 | }); 161 | 162 | // ////////////////////// 163 | // CONNECT TO A QUEUE // 164 | // ////////////////////// 165 | 166 | const queue = new Queue({ connection: connectionDetails }, jobs); 167 | queue.on("error", function (error) { 168 | console.log(error); 169 | }); 170 | await queue.connect(); 171 | await queue.enqueue("math", "add", [1, 2]); 172 | await queue.enqueue("math", "add", [1, 2]); 173 | await queue.enqueue("math", "add", [2, 3]); 174 | await queue.enqueueIn(3000, "math", "subtract", [2, 1]); 175 | jobsToComplete = 4; 176 | } 177 | 178 | boot(); 179 | 180 | // and when you are done 181 | // await queue.end() 182 | // await scheduler.end() 183 | // await worker.end() 184 | -------------------------------------------------------------------------------- /src/core/connection.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from "events"; 2 | import { Redis, Cluster } from "ioredis"; 3 | import * as fs from "fs"; 4 | import * as path from "path"; 5 | import { ConnectionOptions } from ".."; 6 | 7 | interface EventListeners { 8 | [key: string]: (...args: any[]) => void; 9 | } 10 | 11 | export class Connection extends EventEmitter { 12 | options: ConnectionOptions; 13 | private eventListeners: EventListeners; 14 | connected: boolean; 15 | redis: Redis | Cluster; 16 | 17 | constructor(options: ConnectionOptions = {}) { 18 | super(); 19 | 20 | options.pkg = options.pkg ?? "ioredis"; 21 | options.host = options.host ?? "127.0.0.1"; 22 | options.port = options.port ?? 6379; 23 | options.database = options.database ?? 0; 24 | options.namespace = options.namespace ?? "resque"; 25 | options.scanCount = options.scanCount ?? 10; 26 | options.options = options.options ?? {}; 27 | 28 | this.options = options; 29 | this.eventListeners = {}; 30 | this.connected = false; 31 | } 32 | 33 | async connect() { 34 | const connectionTestAndLoadLua = async () => { 35 | try { 36 | await this.redis.set(this.key("connection_test_key"), "ok"); 37 | const data = await this.redis.get(this.key("connection_test_key")); 38 | if (data !== "ok") { 39 | throw new Error("cannot read connection test key"); 40 | } 41 | this.connected = true; 42 | this.loadLua(); 43 | } catch (error) { 44 | this.connected = false; 45 | this.emit("error", error); 46 | } 47 | }; 48 | 49 | if (this.options.redis) { 50 | this.redis = this.options.redis; 51 | } else { 52 | const Pkg = require(this.options.pkg); 53 | if ( 54 | typeof Pkg.createClient === "function" && 55 | this.options.pkg !== "ioredis" 56 | ) { 57 | this.redis = Pkg.createClient( 58 | this.options.port, 59 | this.options.host, 60 | this.options.options, 61 | ); 62 | } else { 63 | this.options.options.db = this.options.database; 64 | this.redis = new Pkg( 65 | this.options.port, 66 | this.options.host, 67 | this.options.options, 68 | ); 69 | } 70 | } 71 | 72 | this.eventListeners.error = (error: Error) => { 73 | this.emit("error", error); 74 | }; 75 | this.eventListeners.end = () => { 76 | this.connected = false; 77 | }; 78 | Object.entries(this.eventListeners).forEach(([eventName, eventHandler]) => { 79 | this.redis.on(eventName, eventHandler); 80 | }); 81 | 82 | if (!this.options.redis && typeof this.redis.select === "function") { 83 | await this.redis.select(this.options.database); 84 | } 85 | 86 | await connectionTestAndLoadLua(); 87 | } 88 | 89 | loadLua() { 90 | // even though ioredis-mock can run LUA, cjson is not available 91 | if (this.options.pkg === "ioredis-mock") return; 92 | 93 | const luaDir = path.join(__dirname, "..", "..", "lua"); 94 | 95 | const files = fs.readdirSync(luaDir); 96 | for (const file of files) { 97 | const { name } = path.parse(file); 98 | const contents = fs.readFileSync(path.join(luaDir, file)).toString(); 99 | const lines = contents.split("\n"); // see https://github.com/actionhero/node-resque/issues/465 for why we split only on *nix line breaks 100 | const encodedMetadata = lines[0].replace(/^-- /, ""); 101 | const metadata = JSON.parse(encodedMetadata); 102 | 103 | this.redis.defineCommand(name, { 104 | numberOfKeys: metadata.numberOfKeys, 105 | lua: contents, 106 | }); 107 | } 108 | } 109 | 110 | async getKeys( 111 | match: string, 112 | count: number = null, 113 | keysAry: string[] = [], 114 | cursor = 0, 115 | ): Promise { 116 | if (count === null || count === undefined) { 117 | count = this.options.scanCount || 10; 118 | } 119 | 120 | if (this.redis && typeof this.redis.scan === "function") { 121 | const [newCursor, matches] = await this.redis.scan( 122 | cursor, 123 | "MATCH", 124 | match, 125 | "COUNT", 126 | count, 127 | ); 128 | if (matches && matches.length > 0) { 129 | keysAry = keysAry.concat(matches); 130 | } 131 | 132 | if (newCursor === "0") return keysAry; 133 | return this.getKeys(match, count, keysAry, parseInt(newCursor)); 134 | } 135 | 136 | this.emit( 137 | "error", 138 | new Error( 139 | "You must establish a connection to redis before running the getKeys command.", 140 | ), 141 | ); 142 | } 143 | 144 | end() { 145 | Object.entries(this.eventListeners).forEach(([eventName, eventHandler]) => { 146 | this.redis.off(eventName, eventHandler); 147 | }); 148 | 149 | // Only disconnect if we established the redis connection on our own. 150 | if (!this.options.redis && this.connected) { 151 | if (typeof this.redis.disconnect === "function") { 152 | this.redis.disconnect(); 153 | } 154 | if (typeof this.redis.quit === "function") { 155 | this.redis.quit(); 156 | } 157 | } 158 | 159 | this.connected = false; 160 | } 161 | 162 | key(arg: any, arg2?: any, arg3?: any, arg4?: any): string { 163 | let args; 164 | args = arguments.length >= 1 ? [].slice.call(arguments, 0) : []; 165 | if (Array.isArray(this.options.namespace)) { 166 | args.unshift(...this.options.namespace); 167 | } else { 168 | args.unshift(this.options.namespace); 169 | } 170 | args = args.filter((e: any) => { 171 | return String(e).trim(); 172 | }); 173 | return args.join(":"); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /__tests__/plugins/queueLock.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { Plugin, Plugins, Queue, Worker, Job } from "../../src"; 3 | 4 | let queue: Queue; 5 | class NeverRunPlugin extends Plugin { 6 | async beforeEnqueue() { 7 | return true; 8 | } 9 | 10 | async afterEnqueue() { 11 | return true; 12 | } 13 | 14 | async beforePerform() { 15 | return false; 16 | } 17 | 18 | async afterPerform() { 19 | return true; 20 | } 21 | } 22 | 23 | const jobs = { 24 | uniqueJob: { 25 | plugins: [Plugins.QueueLock], 26 | pluginOptions: { queueLock: {}, delayQueueLock: {} }, 27 | perform: (a, b) => a + b, 28 | } as Job, 29 | blockingJob: { 30 | plugins: [Plugins.QueueLock, NeverRunPlugin], 31 | perform: (a, b) => a + b, 32 | } as Job, 33 | jobWithLockTimeout: { 34 | plugins: [Plugins.QueueLock], 35 | pluginOptions: { 36 | QueueLock: { 37 | lockTimeout: specHelper.timeout, 38 | }, 39 | }, 40 | perform: (a, b) => a + b, 41 | } as Job, 42 | stuckJob: { 43 | plugins: [Plugins.QueueLock], 44 | pluginOptions: { 45 | QueueLock: { 46 | lockTimeout: specHelper.smallTimeout, 47 | }, 48 | }, 49 | perform: async (a, b) => { 50 | a + b; 51 | }, 52 | } as Job, 53 | }; 54 | 55 | describe("plugins", () => { 56 | describe("queueLock", () => { 57 | beforeAll(async () => { 58 | await specHelper.connect(); 59 | await specHelper.cleanup(); 60 | queue = new Queue( 61 | { 62 | connection: specHelper.cleanConnectionDetails(), 63 | queue: [specHelper.queue], 64 | }, 65 | jobs, 66 | ); 67 | await queue.connect(); 68 | }); 69 | 70 | beforeEach(async () => { 71 | await specHelper.cleanup(); 72 | }); 73 | afterEach(async () => { 74 | await specHelper.cleanup(); 75 | }); 76 | 77 | afterAll(async () => { 78 | await queue.end(); 79 | await specHelper.disconnect(); 80 | }); 81 | 82 | test("will not enque a job with the same args if it is already in the queue", async () => { 83 | const tryOne = await queue.enqueue(specHelper.queue, "uniqueJob", [1, 2]); 84 | const tryTwo = await queue.enqueue(specHelper.queue, "uniqueJob", [1, 2]); 85 | const length = await queue.length(specHelper.queue); 86 | expect(length).toBe(1); 87 | expect(tryOne).toBe(true); 88 | expect(tryTwo).toBe(false); 89 | }); 90 | 91 | test("will enque a job with the different args", async () => { 92 | const tryOne = await queue.enqueue(specHelper.queue, "uniqueJob", [1, 2]); 93 | const tryTwo = await queue.enqueue(specHelper.queue, "uniqueJob", [3, 4]); 94 | const length = await queue.length(specHelper.queue); 95 | expect(length).toBe(2); 96 | expect(tryOne).toBe(true); 97 | expect(tryTwo).toBe(true); 98 | }); 99 | 100 | test("will enqueue a job with timeout set by QueueLock plugin options and check its ttl", async () => { 101 | let job = "jobWithLockTimeout"; 102 | const enqueue = await queue.enqueue(specHelper.queue, job, [1, 2]); 103 | const length = await queue.length(specHelper.queue); 104 | expect(length).toBe(1); 105 | expect(enqueue).toBe(true); 106 | const result = await specHelper.redis.keys( 107 | specHelper.namespace + ":lock*", 108 | ); 109 | expect(result).toHaveLength(1); 110 | const ttl = await specHelper.redis.ttl( 111 | specHelper.namespace + 112 | ":lock" + 113 | ":" + 114 | job + 115 | ":" + 116 | specHelper.queue + 117 | ":[1,2]", 118 | ); 119 | expect(ttl).toBe(specHelper.timeout); 120 | }); 121 | 122 | test("will enqueue a repeated stuck job after another one to overwrite the ttl and the expiration time of the lock", async () => { 123 | let stuckJob = "stuckJob"; 124 | const tryOne = await queue.enqueue(specHelper.queue, stuckJob, [1, 2]); 125 | await new Promise((resolve) => 126 | setTimeout( 127 | resolve, 128 | Math.min((specHelper.smallTimeout + 1) * 1000, 4000), 129 | ), 130 | ); 131 | const tryTwo = await queue.enqueue(specHelper.queue, stuckJob, [1, 2]); 132 | 133 | const length = await queue.length(specHelper.queue); 134 | expect(length).toBe(2); 135 | expect(tryOne).toBe(true); 136 | expect(tryTwo).toBe(true); 137 | 138 | const result = await specHelper.redis.keys( 139 | specHelper.namespace + ":lock*", 140 | ); 141 | expect(result).toHaveLength(1); 142 | const ttl = await specHelper.redis.ttl( 143 | specHelper.namespace + 144 | ":lock" + 145 | ":" + 146 | stuckJob + 147 | ":" + 148 | specHelper.queue + 149 | ":[1,2]", 150 | ); 151 | expect(ttl).toBe(specHelper.smallTimeout); 152 | }); 153 | 154 | describe("with worker", () => { 155 | let worker: Worker; 156 | 157 | beforeEach(async () => { 158 | worker = new Worker( 159 | { 160 | connection: specHelper.cleanConnectionDetails(), 161 | timeout: specHelper.timeout, 162 | queues: [specHelper.queue], 163 | }, 164 | jobs, 165 | ); 166 | 167 | worker.on("error", (error) => { 168 | throw error; 169 | }); 170 | await worker.connect(); 171 | }); 172 | 173 | test("will remove a lock on a job when the job has been worked", async () => { 174 | const enqueue = await queue.enqueue( 175 | specHelper.queue, 176 | "uniqueJob", 177 | [1, 2], 178 | ); 179 | expect(enqueue).toBe(true); 180 | 181 | await worker.start(); 182 | await worker.end(); 183 | 184 | const result = await specHelper.redis.keys( 185 | specHelper.namespace + ":lock*", 186 | ); 187 | expect(result).toHaveLength(0); 188 | }); 189 | 190 | test("will remove a lock on a job if a plugin does not run the job", async () => { 191 | const enqueue = await queue.enqueue( 192 | specHelper.queue, 193 | "blockingJob", 194 | [1, 2], 195 | ); 196 | expect(enqueue).toBe(true); 197 | 198 | await worker.start(); 199 | await worker.end(); 200 | 201 | const result = await specHelper.redis.keys( 202 | specHelper.namespace + ":lock*", 203 | ); 204 | expect(result).toHaveLength(0); 205 | }); 206 | }); 207 | }); 208 | }); 209 | -------------------------------------------------------------------------------- /__tests__/core/scheduler.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Queue, 3 | Scheduler, 4 | Worker, 5 | Job, 6 | ParsedFailedJobPayload, 7 | } from "../../src"; 8 | import specHelper from "../utils/specHelper"; 9 | 10 | let scheduler: Scheduler; 11 | let queue: Queue; 12 | 13 | describe("scheduler", () => { 14 | test("can connect", async () => { 15 | scheduler = new Scheduler({ 16 | connection: specHelper.connectionDetails, 17 | timeout: specHelper.timeout, 18 | }); 19 | await scheduler.connect(); 20 | await scheduler.end(); 21 | }); 22 | 23 | describe("with specHelper", () => { 24 | beforeAll(async () => await specHelper.connect()); 25 | afterAll(async () => await specHelper.disconnect()); 26 | 27 | describe("locking", () => { 28 | beforeEach(async () => { 29 | await specHelper.cleanup(); 30 | }); 31 | afterAll(async () => { 32 | await specHelper.cleanup(); 33 | }); 34 | 35 | test("should only have one leader, and can failover", async () => { 36 | const shedulerOne = new Scheduler({ 37 | connection: specHelper.connectionDetails, 38 | name: "scheduler_1", 39 | timeout: specHelper.timeout, 40 | }); 41 | const shedulerTwo = new Scheduler({ 42 | connection: specHelper.connectionDetails, 43 | name: "scheduler_2", 44 | timeout: specHelper.timeout, 45 | }); 46 | 47 | await shedulerOne.connect(); 48 | await shedulerTwo.connect(); 49 | await shedulerOne.start(); 50 | await shedulerTwo.start(); 51 | 52 | await new Promise((resolve) => { 53 | setTimeout(resolve, specHelper.timeout * 2); 54 | }); 55 | expect(shedulerOne.leader).toBe(true); 56 | expect(shedulerTwo.leader).toBe(false); 57 | await shedulerOne.end(); 58 | 59 | await new Promise((resolve) => { 60 | setTimeout(resolve, specHelper.timeout * 2); 61 | }); 62 | expect(shedulerOne.leader).toBe(false); 63 | expect(shedulerTwo.leader).toBe(true); 64 | await shedulerTwo.end(); 65 | }); 66 | }); 67 | 68 | describe("[with connection]", () => { 69 | beforeEach(async () => { 70 | await specHelper.cleanup(); 71 | scheduler = new Scheduler({ 72 | connection: specHelper.connectionDetails, 73 | timeout: specHelper.timeout, 74 | stuckWorkerTimeout: 1000, 75 | }); 76 | queue = new Queue({ 77 | connection: specHelper.connectionDetails, 78 | queue: specHelper.queue, 79 | }); 80 | await scheduler.connect(); 81 | await queue.connect(); 82 | }); 83 | 84 | test("can start and stop", async () => { 85 | await scheduler.start(); 86 | await scheduler.end(); 87 | await queue.end(); 88 | }); 89 | 90 | test("queues can see who the leader is", async () => { 91 | await scheduler.poll(); 92 | const leader = await queue.leader(); 93 | expect(leader).toBe(scheduler.options.name); 94 | await scheduler.end(); 95 | }); 96 | 97 | test("will move enqueued jobs when the time comes", async () => { 98 | await queue.enqueueAt( 99 | 1000 * 10, 100 | specHelper.queue, 101 | "someJob", 102 | [1, 2, 3], 103 | ); 104 | await scheduler.poll(); 105 | let obj = await specHelper.popFromQueue(); 106 | expect(obj).toBeDefined(); 107 | obj = JSON.parse(obj); 108 | expect(obj.class).toBe("someJob"); 109 | expect(obj.args).toEqual([1, 2, 3]); 110 | await scheduler.end(); 111 | }); 112 | 113 | test("will not move jobs in the future", async () => { 114 | await queue.enqueueAt( 115 | new Date().getTime() + 10000, 116 | specHelper.queue, 117 | "someJob", 118 | [1, 2, 3], 119 | ); 120 | await scheduler.poll(); 121 | const obj = await specHelper.popFromQueue(); 122 | expect(obj).toBeFalsy(); 123 | await scheduler.end(); 124 | }); 125 | 126 | describe("stuck workers", () => { 127 | let worker: Worker; 128 | const jobs = { 129 | stuck: { 130 | perform: async function () { 131 | await new Promise((resolve) => { 132 | // stop the worker from checking in, like the process crashed 133 | // don't resolve 134 | clearTimeout(this.pingTimer); 135 | }); 136 | }, 137 | } as Job, 138 | }; 139 | 140 | beforeAll(async () => { 141 | worker = new Worker( 142 | { 143 | connection: specHelper.connectionDetails, 144 | timeout: specHelper.timeout, 145 | queues: ["stuckJobs"], 146 | }, 147 | jobs, 148 | ); 149 | await worker.connect(); 150 | }); 151 | 152 | afterAll(async () => { 153 | await scheduler.end(); 154 | }); 155 | 156 | test("will remove stuck workers and fail their jobs", async () => { 157 | await new Promise(async (resolve) => { 158 | await scheduler.connect(); 159 | await scheduler.start(); 160 | await worker.start(); 161 | 162 | const workers = await queue.allWorkingOn(); 163 | const h: { [key: string]: any } = {}; 164 | h[worker.name] = "started"; 165 | expect(workers).toEqual(h); 166 | 167 | await queue.enqueue("stuckJobs", "stuck", ["oh no!"]); 168 | 169 | scheduler.on( 170 | "cleanStuckWorker", 171 | async (workerName, errorPayload, delta) => { 172 | // response data should contain failure 173 | expect(workerName).toEqual(worker.name); 174 | expect(errorPayload.worker).toEqual(worker.name); 175 | expect(errorPayload.error).toEqual( 176 | "Worker Timeout (killed manually)", 177 | ); 178 | 179 | // check the workers list, should be empty now 180 | expect(await queue.allWorkingOn()).toEqual({}); 181 | 182 | // check the failed list 183 | const str = await specHelper.redis.rpop( 184 | specHelper.namespace + ":" + "failed", 185 | ); 186 | const failed = JSON.parse(str) as ParsedFailedJobPayload; 187 | expect(failed.queue).toBe("stuckJobs"); 188 | expect(failed.exception).toBe( 189 | "Worker Timeout (killed manually)", 190 | ); 191 | expect(failed.error).toBe("Worker Timeout (killed manually)"); 192 | 193 | scheduler.removeAllListeners("cleanStuckWorker"); 194 | resolve(null); 195 | }, 196 | ); 197 | }); 198 | }); 199 | }); 200 | }); 201 | }); 202 | }); 203 | -------------------------------------------------------------------------------- /__tests__/core/connection.ts: -------------------------------------------------------------------------------- 1 | import Redis from "ioredis"; 2 | import { Connection } from "../../src"; 3 | import specHelper from "../utils/specHelper"; 4 | 5 | describe("connection", () => { 6 | beforeAll(async () => { 7 | await specHelper.connect(); 8 | await specHelper.cleanup(); 9 | }); 10 | 11 | afterAll(async () => { 12 | await specHelper.cleanup(); 13 | await specHelper.disconnect(); 14 | }); 15 | 16 | test("should stat with no redis keys in the namespace", async () => { 17 | const keys = await specHelper.redis.keys(specHelper.namespace + "*"); 18 | expect(keys.length).toBe(0); 19 | }); 20 | 21 | test("it has loaded Lua commands", async () => { 22 | const connection = new Connection(specHelper.cleanConnectionDetails()); 23 | await connection.connect(); 24 | //@ts-ignore 25 | expect(typeof connection.redis["popAndStoreJob"]).toBe("function"); 26 | connection.end(); 27 | }); 28 | 29 | describe("keys and namespaces", () => { 30 | const db = specHelper.connectionDetails.database; 31 | let connection: Connection; 32 | beforeAll(async () => { 33 | connection = new Connection(specHelper.cleanConnectionDetails()); 34 | await connection.connect(); 35 | }); 36 | 37 | let prefixedConnection: Connection; 38 | let prefixedRedis: Redis; 39 | beforeAll(async () => { 40 | prefixedRedis = new Redis(null, null, { 41 | keyPrefix: "customNamespace:", 42 | db: db, 43 | }); 44 | prefixedConnection = new Connection({ 45 | redis: prefixedRedis, 46 | namespace: specHelper.namespace, 47 | }); 48 | await prefixedConnection.connect(); 49 | }); 50 | 51 | afterAll(async () => { 52 | connection.end(); 53 | prefixedConnection.end(); 54 | prefixedRedis.quit(); 55 | }); 56 | 57 | test("getKeys returns appropriate keys based on matcher given", async () => { 58 | // seed the DB with keys to test with 59 | 60 | for (const v of new Array(5).fill(0).map((v, i) => i + 1)) { 61 | await connection.redis.set(`test-key${v}`, v.toString()); 62 | await connection.redis.set(`test-not-key${v}`, v.toString()); 63 | } 64 | 65 | await connection.redis.set(`test-key2`, 2); 66 | await connection.redis.set(`test-key3`, 3); 67 | await connection.redis.set(`test-key4`, 4); 68 | await connection.redis.set(`test-key5`, 5); 69 | 70 | // sanity checks to confirm keys above are set and exist 71 | expect(await connection.redis.get("test-key1")).toBe("1"); 72 | expect(await connection.redis.get("test-not-key1")).toBe("1"); 73 | expect(await connection.redis.get("test-not-key5")).toBe("5"); 74 | 75 | const foundKeys = await connection.getKeys("test-key*"); 76 | 77 | expect(foundKeys.length).toBe(5); 78 | expect(foundKeys).toContain("test-key1"); 79 | expect(foundKeys).toContain("test-key5"); 80 | expect(foundKeys).not.toContain("test-key50"); 81 | expect(foundKeys).not.toContain("test-not-key1"); 82 | expect(foundKeys).not.toContain("test-not-key3"); 83 | expect(foundKeys).not.toContain("test-not-key5"); 84 | expect(foundKeys).not.toContain("test-not-key50"); 85 | }); 86 | 87 | test("keys built with the default namespace are correct", () => { 88 | expect(connection.key("thing")).toBe(`resque-test-${db}:thing`); 89 | expect(prefixedConnection.key("thing")).toBe(`resque-test-${db}:thing`); 90 | // the value retunred by a redis prefix should match a plain redis connection 91 | expect(connection.key("thing")).toBe(prefixedConnection.key("thing")); 92 | }); 93 | 94 | test("ioredis transparent key prefix writes keys with the prefix even if they are not returned", async () => { 95 | await connection.redis.set(connection.key("testPrefixKey"), "abc123"); 96 | await prefixedConnection.redis.set( 97 | prefixedConnection.key("testPrefixKey"), 98 | "abc123", 99 | ); 100 | 101 | const result = await connection.redis.get( 102 | connection.key("testPrefixKey"), 103 | ); 104 | const prefixedResult = await prefixedConnection.redis.get( 105 | prefixedConnection.key("testPrefixKey"), 106 | ); 107 | expect(result).toBe("abc123"); 108 | expect(prefixedResult).toBe("abc123"); 109 | 110 | const keys = await connection.getKeys("*"); 111 | expect(keys).toContain(`resque-test-${db}:testPrefixKey`); 112 | expect(keys).toContain(`customNamespace:resque-test-${db}:testPrefixKey`); 113 | }); 114 | 115 | test("keys built with a custom namespace are correct", () => { 116 | connection.options.namespace = "customNamespace"; 117 | expect(connection.key("thing")).toBe("customNamespace:thing"); 118 | 119 | prefixedConnection.options.namespace = "customNamespace"; 120 | expect(prefixedConnection.key("thing")).toBe("customNamespace:thing"); 121 | }); 122 | 123 | test("keys built with a array namespace are correct", () => { 124 | //@ts-ignore 125 | connection.options.namespace = ["custom", "namespace"]; 126 | expect(connection.key("thing")).toBe("custom:namespace:thing"); 127 | 128 | prefixedConnection.options.namespace = ["custom", "namespace"]; 129 | expect(prefixedConnection.key("thing")).toBe("custom:namespace:thing"); 130 | }); 131 | 132 | test("will properly build namespace strings dynamically", async () => { 133 | connection.options.namespace = specHelper.namespace; 134 | expect(connection.key("thing")).toBe(specHelper.namespace + ":thing"); 135 | 136 | prefixedConnection.options.namespace = specHelper.namespace; 137 | expect(prefixedConnection.key("thing")).toBe( 138 | specHelper.namespace + ":thing", 139 | ); 140 | 141 | expect(connection.key("thing")).toBe(prefixedConnection.key("thing")); 142 | }); 143 | }); 144 | 145 | test("will select redis db from options", async () => { 146 | const connectionDetails = specHelper.cleanConnectionDetails(); 147 | connectionDetails.database = 9; 148 | const connection = new Connection(connectionDetails); 149 | await connection.connect(); 150 | // expect(connection.redis.options.db).toBe(connectionDetails.database) 151 | connection.end(); 152 | }); 153 | 154 | test("removes empty namespace from generated key", async () => { 155 | const connectionDetails = specHelper.cleanConnectionDetails(); 156 | connectionDetails.namespace = ""; 157 | const connection = new Connection(connectionDetails); 158 | await connection.connect(); 159 | expect(connection.key("thing")).toBe("thing"); 160 | connection.end(); 161 | }); 162 | 163 | test("removes the redis event listeners when end", async () => { 164 | const connectionDetails = specHelper.cleanConnectionDetails(); 165 | const connection = new Connection(connectionDetails); 166 | await connection.connect(); 167 | expect(connection.redis.listenerCount("error")).toBe(1); 168 | expect(connection.redis.listenerCount("end")).toBe(1); 169 | connection.end(); 170 | expect(connection.redis.listenerCount("error")).toBe(0); 171 | expect(connection.redis.listenerCount("end")).toBe(0); 172 | }); 173 | }); 174 | -------------------------------------------------------------------------------- /src/core/multiWorker.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from "events"; 2 | import * as os from "os"; 3 | import { Worker } from "./worker"; 4 | import { EventLoopDelay } from "../utils/eventLoopDelay"; 5 | import { MultiWorkerOptions } from "../types/options"; 6 | import { Jobs } from ".."; 7 | import { ParsedJob } from "./queue"; 8 | 9 | export declare interface MultiWorker { 10 | options: MultiWorkerOptions; 11 | jobs: Jobs; 12 | workers: Array; 13 | name: string; 14 | running: boolean; 15 | working: boolean; 16 | eventLoopBlocked: boolean; 17 | eventLoopDelay: number; 18 | eventLoopCheckCounter: number; 19 | stopInProcess: boolean; 20 | checkTimer: NodeJS.Timeout; 21 | 22 | on(event: "start" | "end", cb: (workerId: number) => void): this; 23 | on( 24 | event: "cleaning_worker", 25 | cb: (workerId: number, worker: Worker, pid: number) => void, 26 | ): this; 27 | on(event: "poll", cb: (workerId: number, queue: string) => void): this; 28 | on(event: "ping", cb: (workerId: number, time: number) => void): this; 29 | on( 30 | event: "job", 31 | cb: (workerId: number, queue: string, job: ParsedJob) => void, 32 | ): this; 33 | on( 34 | event: "reEnqueue", 35 | cb: ( 36 | workerId: number, 37 | queue: string, 38 | job: ParsedJob, 39 | plugin: string, 40 | ) => void, 41 | ): this; 42 | on( 43 | event: "success", 44 | cb: ( 45 | workerId: number, 46 | queue: string, 47 | job: ParsedJob, 48 | result: any, 49 | duration: number, 50 | ) => void, 51 | ): this; 52 | on( 53 | event: "failure", 54 | cb: ( 55 | workerId: number, 56 | queue: string, 57 | job: ParsedJob, 58 | failure: Error, 59 | duration: number, 60 | ) => void, 61 | ): this; 62 | on( 63 | event: "error", 64 | cb: (error: Error, workerId: number, queue: string, job: ParsedJob) => void, 65 | ): this; 66 | on(event: "pause", cb: (workerId: number) => void): this; 67 | on( 68 | event: "multiWorkerAction", 69 | cb: (verb: string, delay: number) => void, 70 | ): this; 71 | } 72 | 73 | export class MultiWorker extends EventEmitter { 74 | constructor(options: MultiWorkerOptions, jobs: Jobs) { 75 | super(); 76 | 77 | options.name = options.name ?? os.hostname(); 78 | options.minTaskProcessors = options.minTaskProcessors ?? 1; 79 | options.maxTaskProcessors = options.maxTaskProcessors ?? 10; 80 | options.timeout = options.timeout ?? 5000; 81 | options.checkTimeout = options.checkTimeout ?? 500; 82 | options.maxEventLoopDelay = options.maxEventLoopDelay ?? 10; 83 | 84 | if ( 85 | options.connection.redis && 86 | typeof options.connection.redis.setMaxListeners === "function" 87 | ) { 88 | options.connection.redis.setMaxListeners( 89 | options.connection.redis.getMaxListeners() + options.maxTaskProcessors, 90 | ); 91 | } 92 | 93 | this.workers = []; 94 | this.options = options; 95 | this.jobs = jobs; 96 | this.running = false; 97 | this.working = false; 98 | this.name = this.options.name; 99 | this.eventLoopBlocked = true; 100 | this.eventLoopDelay = Infinity; 101 | this.eventLoopCheckCounter = 0; 102 | this.stopInProcess = false; 103 | this.checkTimer = null; 104 | 105 | this.PollEventLoopDelay(); 106 | } 107 | 108 | private PollEventLoopDelay() { 109 | EventLoopDelay( 110 | this.options.maxEventLoopDelay, 111 | this.options.checkTimeout, 112 | (blocked: boolean, ms: number) => { 113 | this.eventLoopBlocked = blocked; 114 | this.eventLoopDelay = ms; 115 | this.eventLoopCheckCounter++; 116 | }, 117 | ); 118 | } 119 | 120 | private async startWorker() { 121 | const id = this.workers.length + 1; 122 | 123 | const worker = new Worker( 124 | { 125 | connection: this.options.connection, 126 | queues: this.options.queues, 127 | timeout: this.options.timeout, 128 | name: this.options.name + ":" + process.pid + "+" + id, 129 | }, 130 | this.jobs, 131 | ); 132 | 133 | worker.id = id; 134 | 135 | worker.on("start", () => { 136 | this.emit("start", worker.id); 137 | }); 138 | worker.on("end", () => { 139 | this.emit("end", worker.id); 140 | }); 141 | worker.on("cleaning_worker", (worker, pid) => { 142 | this.emit("cleaning_worker", worker.id, worker, pid); 143 | }); 144 | worker.on("poll", (queue) => { 145 | this.emit("poll", worker.id, queue); 146 | }); 147 | worker.on("ping", (time) => { 148 | this.emit("ping", worker.id, time); 149 | }); 150 | worker.on("job", (queue, job) => { 151 | this.emit("job", worker.id, queue, job); 152 | }); 153 | worker.on("reEnqueue", (queue, job, plugin) => { 154 | this.emit("reEnqueue", worker.id, queue, job, plugin); 155 | }); 156 | worker.on("success", (queue, job, result, duration) => { 157 | this.emit("success", worker.id, queue, job, result, duration); 158 | }); 159 | worker.on("failure", (queue, job, failure, duration) => { 160 | this.emit("failure", worker.id, queue, job, failure, duration); 161 | }); 162 | worker.on("error", (error, queue, job) => { 163 | this.emit("error", error, worker.id, queue, job); 164 | }); 165 | worker.on("pause", () => { 166 | this.emit("pause", worker.id); 167 | }); 168 | 169 | this.workers.push(worker); 170 | 171 | await worker.connect(); 172 | await worker.start(); 173 | } 174 | 175 | private async checkWorkers() { 176 | let verb; 177 | let worker; 178 | let workingCount = 0; 179 | 180 | this.workers.forEach((worker) => { 181 | if (worker.working === true) { 182 | workingCount++; 183 | } 184 | }); 185 | 186 | this.working = workingCount > 0; 187 | 188 | if (this.running === false && this.workers.length > 0) { 189 | verb = "--"; 190 | } else if (this.running === false && this.workers.length === 0) { 191 | verb = "x"; 192 | } else if ( 193 | this.eventLoopBlocked && 194 | this.workers.length > this.options.minTaskProcessors 195 | ) { 196 | verb = "-"; 197 | } else if ( 198 | this.eventLoopBlocked && 199 | this.workers.length === this.options.minTaskProcessors 200 | ) { 201 | verb = "x"; 202 | } else if ( 203 | !this.eventLoopBlocked && 204 | this.workers.length < this.options.minTaskProcessors 205 | ) { 206 | verb = "+"; 207 | } else if ( 208 | !this.eventLoopBlocked && 209 | this.workers.length < this.options.maxTaskProcessors && 210 | (this.workers.length === 0 || workingCount / this.workers.length > 0.5) 211 | ) { 212 | verb = "+"; 213 | } else if ( 214 | !this.eventLoopBlocked && 215 | this.workers.length > this.options.minTaskProcessors && 216 | workingCount / this.workers.length < 0.5 217 | ) { 218 | verb = "-"; 219 | } else { 220 | verb = "x"; 221 | } 222 | 223 | if (verb === "x") { 224 | return { verb, eventLoopDelay: this.eventLoopDelay }; 225 | } 226 | 227 | if (verb === "-") { 228 | worker = this.workers.pop(); 229 | await worker.end(); 230 | await this.cleanupWorker(worker); 231 | return { verb, eventLoopDelay: this.eventLoopDelay }; 232 | } 233 | 234 | if (verb === "--") { 235 | this.stopInProcess = true; 236 | 237 | const promises: Promise[] = []; 238 | this.workers.forEach((worker) => { 239 | promises.push( 240 | new Promise(async (resolve) => { 241 | await worker.end(); 242 | await this.cleanupWorker(worker); 243 | return resolve(null); 244 | }), 245 | ); 246 | }); 247 | 248 | await Promise.all(promises); 249 | 250 | this.stopInProcess = false; 251 | this.workers = []; 252 | return { verb, eventLoopDelay: this.eventLoopDelay }; 253 | } 254 | 255 | if (verb === "+") { 256 | await this.startWorker(); 257 | return { verb, eventLoopDelay: this.eventLoopDelay }; 258 | } 259 | } 260 | 261 | private async cleanupWorker(worker: Worker) { 262 | [ 263 | "start", 264 | "end", 265 | "cleaning_worker", 266 | "poll", 267 | "ping", 268 | "job", 269 | "reEnqueue", 270 | "success", 271 | "failure", 272 | "error", 273 | "pause", 274 | "multiWorkerAction", 275 | ].forEach((e) => { 276 | worker.removeAllListeners(e); 277 | }); 278 | } 279 | 280 | private async checkWrapper() { 281 | clearTimeout(this.checkTimer); 282 | const { verb, eventLoopDelay } = await this.checkWorkers(); 283 | this.emit("multiWorkerAction", verb, eventLoopDelay); 284 | this.checkTimer = setTimeout(() => { 285 | this.checkWrapper(); 286 | }, this.options.checkTimeout); 287 | } 288 | 289 | start() { 290 | this.running = true; 291 | this.checkWrapper(); 292 | } 293 | 294 | async stop() { 295 | this.running = false; 296 | await this.stopWait(); 297 | } 298 | 299 | async end() { 300 | return this.stop(); 301 | } 302 | 303 | private async stopWait(): Promise { 304 | if ( 305 | this.workers.length === 0 && 306 | this.working === false && 307 | !this.stopInProcess 308 | ) { 309 | clearTimeout(this.checkTimer); 310 | return; 311 | } 312 | 313 | await new Promise((resolve) => { 314 | setTimeout(resolve, this.options.checkTimeout); 315 | }); 316 | return this.stopWait(); 317 | } 318 | } 319 | -------------------------------------------------------------------------------- /__tests__/plugins/jobLock.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { Queue, Plugins, Worker, ParsedJob, Job } from "../../src"; 3 | 4 | let queue: Queue; 5 | const jobDelay = 1000; 6 | let worker1: Worker; 7 | let worker2: Worker; 8 | 9 | const jobs = { 10 | slowAdd: { 11 | plugins: [Plugins.JobLock], 12 | pluginOptions: { jobLock: {} }, 13 | perform: async (a: number, b: number) => { 14 | const answer = a + b; 15 | await new Promise((resolve) => { 16 | setTimeout(resolve, jobDelay); 17 | }); 18 | return answer; 19 | }, 20 | }, 21 | withoutReEnqueue: { 22 | plugins: [Plugins.JobLock], 23 | pluginOptions: { JobLock: { reEnqueue: false } }, 24 | perform: async () => { 25 | await new Promise((resolve) => { 26 | setTimeout(resolve, jobDelay); 27 | }); 28 | }, 29 | }, 30 | }; 31 | 32 | describe("plugins", () => { 33 | beforeAll(async () => { 34 | await specHelper.connect(); 35 | await specHelper.cleanup(); 36 | queue = new Queue( 37 | { 38 | connection: specHelper.cleanConnectionDetails(), 39 | queue: [specHelper.queue], 40 | }, 41 | jobs, 42 | ); 43 | await queue.connect(); 44 | }); 45 | 46 | afterEach(async () => { 47 | await specHelper.cleanup(); 48 | }); 49 | 50 | afterAll(async () => { 51 | await queue.end(); 52 | await specHelper.disconnect(); 53 | }); 54 | 55 | describe("jobLock", () => { 56 | test("will not lock jobs since arg objects are different", async () => { 57 | worker1 = new Worker( 58 | { 59 | connection: specHelper.cleanConnectionDetails(), 60 | timeout: specHelper.timeout, 61 | queues: [specHelper.queue], 62 | }, 63 | jobs, 64 | ); 65 | worker2 = new Worker( 66 | { 67 | connection: specHelper.cleanConnectionDetails(), 68 | timeout: specHelper.timeout, 69 | queues: [specHelper.queue], 70 | }, 71 | jobs, 72 | ); 73 | 74 | worker1.on("error", (error) => { 75 | throw error; 76 | }); 77 | worker2.on("error", (error) => { 78 | throw error; 79 | }); 80 | 81 | await worker1.connect(); 82 | await worker2.connect(); 83 | 84 | await new Promise((resolve) => { 85 | const startTime = new Date().getTime(); 86 | let completed = 0; 87 | 88 | const onComplete = function () { 89 | completed++; 90 | if (completed === 2) { 91 | worker1.end(); 92 | worker2.end(); 93 | expect(new Date().getTime() - startTime).toBeLessThan(jobDelay * 3); 94 | resolve(null); 95 | } 96 | }; 97 | 98 | worker1.on("success", onComplete); 99 | worker2.on("success", onComplete); 100 | 101 | queue.enqueue(specHelper.queue, "slowAdd", [ 102 | { name: "Walter White" }, 103 | 2, 104 | ]); 105 | queue.enqueue(specHelper.queue, "slowAdd", [ 106 | { name: "Jesse Pinkman" }, 107 | 2, 108 | ]); 109 | 110 | worker1.start(); 111 | worker2.start(); 112 | }); 113 | }); 114 | 115 | test("allows the key to be specified as a function", async () => { 116 | await new Promise(async (resolve) => { 117 | let calls = 0; 118 | 119 | const functionJobs = { 120 | //@ts-ignore 121 | jobLockAdd: { 122 | plugins: [Plugins.JobLock], 123 | pluginOptions: { 124 | JobLock: { 125 | key: function () { 126 | // Once to create, once to delete 127 | if (++calls === 2) { 128 | worker1.end(); 129 | resolve(null); 130 | } 131 | const key = this.worker.connection.key( 132 | "customKey", 133 | Math.max.apply(Math.max, this.args), 134 | ); 135 | return key; 136 | }, 137 | }, 138 | }, 139 | perform: (a: number, b: number) => { 140 | return a + b; 141 | }, 142 | } as Job, 143 | }; 144 | 145 | worker1 = new Worker( 146 | { 147 | connection: specHelper.cleanConnectionDetails(), 148 | timeout: specHelper.timeout, 149 | queues: [specHelper.queue], 150 | }, 151 | functionJobs, 152 | ); 153 | worker1.on("error", (error) => { 154 | throw error; 155 | }); 156 | await worker1.connect(); 157 | await queue.enqueue(specHelper.queue, "jobLockAdd", [1, 2]); 158 | worker1.start(); 159 | }); 160 | }); 161 | 162 | test("will not run 2 jobs with the same args at the same time", async () => { 163 | await new Promise(async (resolve) => { 164 | let count = 0; 165 | worker1 = new Worker( 166 | { 167 | connection: specHelper.cleanConnectionDetails(), 168 | timeout: specHelper.timeout, 169 | queues: [specHelper.queue], 170 | }, 171 | jobs, 172 | ); 173 | worker2 = new Worker( 174 | { 175 | connection: specHelper.cleanConnectionDetails(), 176 | timeout: specHelper.timeout, 177 | queues: [specHelper.queue], 178 | }, 179 | jobs, 180 | ); 181 | 182 | worker1.on("error", (error) => { 183 | throw error; 184 | }); 185 | worker2.on("error", (error) => { 186 | throw error; 187 | }); 188 | 189 | await worker1.connect(); 190 | await worker2.connect(); 191 | 192 | const onComplete = async () => { 193 | count++; 194 | expect(count).toBe(1); 195 | await worker1.end(); 196 | await worker2.end(); 197 | 198 | const timestamps = await queue.timestamps(); 199 | let str = await specHelper.redis.lpop( 200 | specHelper.namespace + 201 | ":delayed:" + 202 | Math.round(timestamps[0] / 1000), 203 | ); 204 | expect(str).toBeDefined(); 205 | const dealyedJob = JSON.parse(str) as ParsedJob; 206 | expect(dealyedJob.class).toBe("slowAdd"); 207 | expect(dealyedJob.args).toEqual([1, 2]); 208 | 209 | resolve(null); 210 | }; 211 | 212 | worker1.on("success", onComplete); 213 | worker2.on("success", onComplete); 214 | 215 | await queue.enqueue(specHelper.queue, "slowAdd", [1, 2]); 216 | await queue.enqueue(specHelper.queue, "slowAdd", [1, 2]); 217 | 218 | worker1.start(); 219 | worker2.start(); 220 | }); 221 | }); 222 | 223 | test("can be configured not to re-enqueue a duplicate task", async () => { 224 | await new Promise(async (resolve) => { 225 | let count = 0; 226 | worker1 = new Worker( 227 | { 228 | connection: specHelper.cleanConnectionDetails(), 229 | timeout: specHelper.timeout, 230 | queues: [specHelper.queue], 231 | }, 232 | jobs, 233 | ); 234 | worker2 = new Worker( 235 | { 236 | connection: specHelper.cleanConnectionDetails(), 237 | timeout: specHelper.timeout, 238 | queues: [specHelper.queue], 239 | }, 240 | jobs, 241 | ); 242 | 243 | worker1.on("error", (error) => { 244 | throw error; 245 | }); 246 | worker2.on("error", (error) => { 247 | throw error; 248 | }); 249 | 250 | await worker1.connect(); 251 | await worker2.connect(); 252 | 253 | const onComplete = async () => { 254 | count++; 255 | expect(count).toBe(1); 256 | await worker1.end(); 257 | await worker2.end(); 258 | 259 | const timestamps = await queue.timestamps(); 260 | expect(timestamps).toEqual([]); 261 | 262 | resolve(null); 263 | }; 264 | 265 | worker1.on("success", onComplete); 266 | worker2.on("success", onComplete); 267 | 268 | await queue.enqueue(specHelper.queue, "withoutReEnqueue"); 269 | await queue.enqueue(specHelper.queue, "withoutReEnqueue"); 270 | 271 | worker1.start(); 272 | worker2.start(); 273 | }); 274 | }); 275 | 276 | test("will run 2 jobs with the different args at the same time", async () => { 277 | await new Promise(async (resolve) => { 278 | worker1 = new Worker( 279 | { 280 | connection: specHelper.cleanConnectionDetails(), 281 | timeout: specHelper.timeout, 282 | queues: [specHelper.queue], 283 | }, 284 | jobs, 285 | ); 286 | worker2 = new Worker( 287 | { 288 | connection: specHelper.cleanConnectionDetails(), 289 | timeout: specHelper.timeout, 290 | queues: [specHelper.queue], 291 | }, 292 | jobs, 293 | ); 294 | 295 | worker1.on("error", (error) => { 296 | throw error; 297 | }); 298 | worker2.on("error", (error) => { 299 | throw error; 300 | }); 301 | 302 | await worker1.connect(); 303 | await worker2.connect(); 304 | 305 | const startTime = new Date().getTime(); 306 | let completed = 0; 307 | 308 | const onComplete = async function () { 309 | completed++; 310 | if (completed === 2) { 311 | await worker1.end(); 312 | await worker2.end(); 313 | const delta = new Date().getTime() - startTime; 314 | expect(delta).toBeLessThan(jobDelay * 3); 315 | resolve(null); 316 | } 317 | }; 318 | 319 | worker1.on("success", onComplete); 320 | worker2.on("success", onComplete); 321 | 322 | await queue.enqueue(specHelper.queue, "slowAdd", [1, 2]); 323 | await queue.enqueue(specHelper.queue, "slowAdd", [3, 4]); 324 | 325 | worker1.start(); 326 | worker2.start(); 327 | }); 328 | }); 329 | }); 330 | }); 331 | -------------------------------------------------------------------------------- /src/core/scheduler.ts: -------------------------------------------------------------------------------- 1 | // To read notes about the leader locking scheme, check out: 2 | // https://github.com/resque/resque-scheduler/blob/master/lib/resque/scheduler/locking.rb 3 | 4 | import { EventEmitter } from "events"; 5 | import * as os from "os"; 6 | import { ErrorPayload, Job, Jobs } from ".."; 7 | import { SchedulerOptions } from "../types/options"; 8 | import { Connection } from "./connection"; 9 | import { Queue } from "./queue"; 10 | 11 | export declare interface Scheduler { 12 | options: SchedulerOptions; 13 | jobs: Jobs; 14 | name: string; 15 | leader: boolean; 16 | running: boolean; 17 | processing: boolean; 18 | queue: Queue; 19 | connection: Connection; 20 | timer: NodeJS.Timeout; 21 | 22 | on(event: "start" | "end" | "poll" | "leader", cb: () => void): this; 23 | on( 24 | event: "cleanStuckWorker", 25 | cb: (workerName: string, errorPayload: ErrorPayload, delta: number) => void, 26 | ): this; 27 | on(event: "error", cb: (error: Error, queue: string) => void): this; 28 | on(event: "workingTimestamp", cb: (timestamp: number) => void): this; 29 | on( 30 | event: "transferredJob", 31 | cb: (timestamp: number, job: Job) => void, 32 | ): this; 33 | 34 | once(event: "start" | "end" | "poll" | "leader", cb: () => void): this; 35 | once( 36 | event: "cleanStuckWorker", 37 | cb: (workerName: string, errorPayload: ErrorPayload, delta: number) => void, 38 | ): this; 39 | once(event: "error", cb: (error: Error, queue: string) => void): this; 40 | once(event: "workingTimestamp", cb: (timestamp: number) => void): this; 41 | once( 42 | event: "transferredJob", 43 | cb: (timestamp: number, job: Job) => void, 44 | ): this; 45 | 46 | removeAllListeners(event: SchedulerEvent): this; 47 | } 48 | 49 | export type SchedulerEvent = 50 | | "start" 51 | | "end" 52 | | "poll" 53 | | "leader" 54 | | "cleanStuckWorker" 55 | | "error" 56 | | "workingTimestamp" 57 | | "transferredJob"; 58 | 59 | export class Scheduler extends EventEmitter { 60 | constructor(options: SchedulerOptions, jobs: Jobs = {}) { 61 | super(); 62 | 63 | options.timeout = options.timeout ?? 5000; // in ms 64 | options.stuckWorkerTimeout = options.stuckWorkerTimeout ?? 60 * 60 * 1000; // 60 minutes in ms 65 | options.leaderLockTimeout = options.leaderLockTimeout ?? 60 * 3; // in seconds 66 | options.name = options.name ?? os.hostname() + ":" + process.pid; // assumes only one worker per node process 67 | options.retryStuckJobs = options.retryStuckJobs ?? false; 68 | 69 | this.options = options; 70 | this.name = this.options.name; 71 | this.leader = false; 72 | this.running = false; 73 | this.processing = false; 74 | 75 | this.queue = new Queue({ connection: options.connection }, jobs); 76 | this.queue.on("error", (error) => { 77 | this.emit("error", error); 78 | }); 79 | } 80 | 81 | async connect() { 82 | await this.queue.connect(); 83 | this.connection = this.queue.connection; 84 | } 85 | 86 | async start() { 87 | this.processing = false; 88 | 89 | if (!this.running) { 90 | this.emit("start"); 91 | this.running = true; 92 | this.pollAgainLater(); 93 | } 94 | } 95 | 96 | async end() { 97 | this.running = false; 98 | clearTimeout(this.timer); 99 | 100 | if (this.processing === false) { 101 | if ( 102 | this.connection && 103 | (this.connection.connected === true || 104 | this.connection.connected === undefined || 105 | this.connection.connected === null) 106 | ) { 107 | try { 108 | await this.releaseLeaderLock(); 109 | } catch (error) { 110 | this.emit("error", error); 111 | } 112 | } 113 | 114 | try { 115 | await this.queue.end(); 116 | this.emit("end"); 117 | } catch (error) { 118 | this.emit("error", error); 119 | } 120 | } else { 121 | return new Promise((resolve) => { 122 | setTimeout(async () => { 123 | await this.end(); 124 | resolve(null); 125 | }, this.options.timeout / 2); 126 | }); 127 | } 128 | } 129 | 130 | async poll(): Promise { 131 | this.processing = true; 132 | clearTimeout(this.timer); 133 | const isLeader = await this.tryForLeader(); 134 | 135 | if (!isLeader) { 136 | this.leader = false; 137 | this.processing = false; 138 | return this.pollAgainLater(); 139 | } 140 | 141 | if (!this.leader) { 142 | this.leader = true; 143 | this.emit("leader"); 144 | } 145 | 146 | this.emit("poll"); 147 | const timestamp = await this.nextDelayedTimestamp(); 148 | if (timestamp) { 149 | this.emit("workingTimestamp", timestamp); 150 | await this.enqueueDelayedItemsForTimestamp(parseInt(timestamp)); 151 | return this.poll(); 152 | } else { 153 | await this.checkStuckWorkers(); 154 | this.processing = false; 155 | return this.pollAgainLater(); 156 | } 157 | } 158 | 159 | private async pollAgainLater() { 160 | if (this.running === true) { 161 | this.timer = setTimeout(() => { 162 | this.poll(); 163 | }, this.options.timeout); 164 | } 165 | } 166 | 167 | private async tryForLeader() { 168 | const leaderKey = this.queue.leaderKey(); 169 | if (!this.connection || !this.connection.redis) { 170 | return; 171 | } 172 | 173 | try { 174 | const lockedByMe = await this.connection.redis.set( 175 | leaderKey, 176 | this.options.name, 177 | "EX", 178 | this.options.leaderLockTimeout, 179 | "NX", 180 | ); 181 | 182 | if (lockedByMe && lockedByMe.toUpperCase() === "OK") { 183 | return true; 184 | } 185 | 186 | const currentLeaderName = await this.connection.redis.get(leaderKey); 187 | if (currentLeaderName === this.options.name) { 188 | await this.connection.redis.expire( 189 | leaderKey, 190 | this.options.leaderLockTimeout, 191 | ); 192 | return true; 193 | } 194 | } catch (error) { 195 | this.emit("error", error); 196 | return false; 197 | } 198 | 199 | return false; 200 | } 201 | 202 | private async releaseLeaderLock() { 203 | if (!this.connection || !this.connection.redis) { 204 | return; 205 | } 206 | 207 | const isLeader = await this.tryForLeader(); 208 | if (!isLeader) { 209 | return false; 210 | } 211 | 212 | const deleted = await this.connection.redis.del(this.queue.leaderKey()); 213 | this.leader = false; 214 | return deleted === 1 || deleted.toString() === "true"; 215 | } 216 | 217 | private async nextDelayedTimestamp() { 218 | const time = Math.round(new Date().getTime() / 1000); 219 | const items = await this.connection.redis.zrangebyscore( 220 | this.connection.key("delayed_queue_schedule"), 221 | 0, 222 | time, 223 | "LIMIT", 224 | 0, 225 | 1, 226 | ); 227 | if (items.length === 0) return; 228 | return items[0]; 229 | } 230 | 231 | private async enqueueDelayedItemsForTimestamp(timestamp: number) { 232 | const job = await this.nextItemForTimestamp(timestamp); 233 | if (job) { 234 | await this.transfer(timestamp, job); 235 | await this.enqueueDelayedItemsForTimestamp(timestamp); 236 | } else { 237 | await this.cleanupTimestamp(timestamp); 238 | } 239 | } 240 | 241 | private async nextItemForTimestamp(timestamp: number) { 242 | const key = this.connection.key("delayed:" + timestamp); 243 | const job = await this.connection.redis.lpop(key); 244 | await this.connection.redis.srem( 245 | this.connection.key("timestamps:" + job), 246 | "delayed:" + timestamp, 247 | ); 248 | return JSON.parse(job); 249 | } 250 | 251 | private async transfer(timestamp: number, job: any) { 252 | await this.queue.enqueue(job.queue, job.class, job.args); 253 | this.emit("transferredJob", timestamp, job); 254 | } 255 | 256 | private async cleanupTimestamp(timestamp: number) { 257 | const key = this.connection.key("delayed:" + timestamp); 258 | await this.watchIfPossible(key); 259 | await this.watchIfPossible(this.connection.key("delayed_queue_schedule")); 260 | const length = await this.connection.redis.llen(key); 261 | if (length === 0) { 262 | const response = await this.connection.redis 263 | .multi() 264 | .del(key) 265 | .zrem(this.connection.key("delayed_queue_schedule"), timestamp) 266 | .exec(); 267 | if (response !== null) { 268 | response.forEach((res) => { 269 | if (res[0] !== null) { 270 | throw res[0]; 271 | } 272 | }); 273 | } 274 | } 275 | await this.unwatchIfPossible(); 276 | } 277 | 278 | private async checkStuckWorkers() { 279 | interface Payload { 280 | time: number; 281 | name: string; 282 | } 283 | 284 | if (!this.options.stuckWorkerTimeout) { 285 | return; 286 | } 287 | 288 | const keys = await this.connection.getKeys( 289 | this.connection.key("worker", "ping", "*"), 290 | ); 291 | const payloads: Array = await Promise.all( 292 | keys.map(async (k) => { 293 | return JSON.parse(await this.connection.redis.get(k)); 294 | }), 295 | ); 296 | 297 | const nowInSeconds = Math.round(new Date().getTime() / 1000); 298 | const stuckWorkerTimeoutInSeconds = Math.round( 299 | this.options.stuckWorkerTimeout / 1000, 300 | ); 301 | 302 | for (let i in payloads) { 303 | if (!payloads[i]) continue; 304 | const { name, time } = payloads[i]; 305 | const delta = nowInSeconds - time; 306 | if (delta > stuckWorkerTimeoutInSeconds) { 307 | await this.forceCleanWorker(name, delta); 308 | } 309 | } 310 | 311 | if (this.options.retryStuckJobs === true) { 312 | await this.queue.retryStuckJobs(); 313 | } 314 | } 315 | 316 | async forceCleanWorker(workerName: string, delta: number) { 317 | const errorPayload = await this.queue.forceCleanWorker(workerName); 318 | this.emit("cleanStuckWorker", workerName, errorPayload, delta); 319 | } 320 | 321 | private async watchIfPossible(key: string) { 322 | if (this.canWatch()) return this.connection.redis.watch(key); 323 | } 324 | 325 | private async unwatchIfPossible() { 326 | if (this.canWatch()) return this.connection.redis.unwatch(); 327 | } 328 | 329 | private canWatch() { 330 | if ( 331 | ["RedisMock", "_RedisMock"].includes( 332 | this.connection.redis?.constructor?.name, 333 | ) 334 | ) { 335 | return false; 336 | } 337 | if (typeof this.connection.redis.unwatch !== "function") return false; 338 | return true; 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /__tests__/plugins/retry.ts: -------------------------------------------------------------------------------- 1 | import specHelper from "../utils/specHelper"; 2 | import { 3 | Scheduler, 4 | Plugins, 5 | Queue, 6 | Worker, 7 | Job, 8 | ParsedFailedJobPayload, 9 | } from "../../src"; 10 | 11 | let queue: Queue; 12 | let scheduler: Scheduler; 13 | 14 | const jobs: { [key: string]: Job } = { 15 | brokenJob: { 16 | plugins: [Plugins.Retry], 17 | pluginOptions: { 18 | Retry: { 19 | retryLimit: 3, 20 | retryDelay: 100, 21 | }, 22 | }, 23 | perform: () => { 24 | throw new Error("BUSTED"); 25 | }, 26 | }, 27 | happyJob: { 28 | plugins: [Plugins.Retry], 29 | pluginOptions: { 30 | Retry: { 31 | retryLimit: 3, 32 | retryDelay: 100, 33 | }, 34 | }, 35 | //@ts-ignore 36 | perform: () => { 37 | // no return 38 | }, 39 | }, 40 | }; 41 | 42 | describe("plugins", () => { 43 | describe("retry", () => { 44 | beforeAll(async () => { 45 | await specHelper.connect(); 46 | await specHelper.cleanup(); 47 | queue = new Queue( 48 | { 49 | connection: specHelper.cleanConnectionDetails(), 50 | queue: [specHelper.queue], 51 | }, 52 | jobs, 53 | ); 54 | scheduler = new Scheduler({ 55 | connection: specHelper.cleanConnectionDetails(), 56 | timeout: specHelper.timeout, 57 | }); 58 | await scheduler.connect(); 59 | scheduler.start(); 60 | await queue.connect(); 61 | }); 62 | 63 | afterAll(async () => { 64 | await scheduler.end(); 65 | await queue.end(); 66 | await specHelper.disconnect(); 67 | }); 68 | 69 | afterEach(async () => { 70 | await specHelper.cleanup(); 71 | }); 72 | 73 | test("will work fine with non-crashing jobs", async () => { 74 | await new Promise(async (resolve) => { 75 | await queue.enqueue(specHelper.queue, "happyJob", [1, 2]); 76 | const length = await queue.length(specHelper.queue); 77 | expect(length).toBe(1); 78 | 79 | const worker = new Worker( 80 | { 81 | connection: specHelper.cleanConnectionDetails(), 82 | timeout: specHelper.timeout, 83 | queues: [specHelper.queue], 84 | }, 85 | jobs, 86 | ); 87 | 88 | worker.on("failure", () => { 89 | throw new Error("should not get here"); 90 | }); 91 | 92 | await worker.connect(); 93 | 94 | worker.on("success", async () => { 95 | const length = await specHelper.redis.llen( 96 | `${specHelper.namespace}:failed`, 97 | ); 98 | expect(length).toBe(0); 99 | await worker.end(); 100 | resolve(null); 101 | }); 102 | 103 | worker.start(); 104 | }); 105 | }); 106 | 107 | test("will retry the job n times before finally failing", async () => { 108 | await new Promise(async (resolve) => { 109 | await queue.enqueue(specHelper.queue, "brokenJob"); 110 | const length = await queue.length(specHelper.queue); 111 | expect(length).toBe(1); 112 | 113 | let failButRetryCount = 0; 114 | let failureCount = 0; 115 | 116 | const worker = new Worker( 117 | { 118 | connection: specHelper.cleanConnectionDetails(), 119 | timeout: specHelper.timeout, 120 | queues: [specHelper.queue], 121 | }, 122 | jobs, 123 | ); 124 | 125 | worker.on("success", () => { 126 | failButRetryCount++; 127 | }); 128 | 129 | await worker.connect(); 130 | 131 | worker.on("failure", async () => { 132 | failureCount++; 133 | expect(failButRetryCount).toBe(2); 134 | expect(failureCount).toBe(1); 135 | expect(failButRetryCount + failureCount).toBe(3); 136 | 137 | const length = await specHelper.redis.llen( 138 | `${specHelper.namespace}:failed`, 139 | ); 140 | expect(length).toBe(1); 141 | await worker.end(); 142 | resolve(null); 143 | }); 144 | 145 | worker.start(); 146 | }); 147 | }); 148 | 149 | test("can have a retry count set", async () => { 150 | await new Promise(async (resolve) => { 151 | const customJobs = { 152 | jobWithRetryCount: { 153 | plugins: [Plugins.Retry], 154 | pluginOptions: { 155 | Retry: { 156 | retryLimit: 5, 157 | retryDelay: 100, 158 | }, 159 | }, 160 | perform: () => { 161 | throw new Error("BUSTED"); 162 | }, 163 | }, 164 | }; 165 | 166 | await queue.enqueue(specHelper.queue, "jobWithRetryCount", [1, 2]); 167 | const length = await queue.length(specHelper.queue); 168 | expect(length).toBe(1); 169 | 170 | let failButRetryCount = 0; 171 | let failureCount = 0; 172 | 173 | const worker = new Worker( 174 | { 175 | connection: specHelper.cleanConnectionDetails(), 176 | timeout: specHelper.timeout, 177 | queues: [specHelper.queue], 178 | }, 179 | customJobs, 180 | ); 181 | 182 | worker.on("success", () => { 183 | failButRetryCount++; 184 | }); 185 | 186 | await worker.connect(); 187 | 188 | worker.on("failure", async () => { 189 | failureCount++; 190 | expect(failButRetryCount).toBe(4); 191 | expect(failureCount).toBe(1); 192 | expect(failButRetryCount + failureCount).toBe(5); 193 | 194 | const length = await specHelper.redis.llen( 195 | `${specHelper.namespace}:failed`, 196 | ); 197 | expect(length).toBe(1); 198 | await worker.end(); 199 | resolve(null); 200 | }); 201 | 202 | worker.start(); 203 | }); 204 | }); 205 | 206 | test("can have custom retry times set", async () => { 207 | await new Promise(async (resolve) => { 208 | const customJobs = { 209 | //@ts-ignore 210 | jobWithBackoffStrategy: { 211 | plugins: [Plugins.Retry], 212 | pluginOptions: { 213 | Retry: { 214 | retryLimit: 5, 215 | backoffStrategy: [1, 2, 3, 4, 5], 216 | }, 217 | }, 218 | perform: function (a, b, callback) { 219 | callback(new Error("BUSTED"), null); 220 | }, 221 | } as Job, 222 | }; 223 | 224 | await queue.enqueue(specHelper.queue, "jobWithBackoffStrategy", [1, 2]); 225 | const length = await queue.length(specHelper.queue); 226 | expect(length).toBe(1); 227 | 228 | let failButRetryCount = 0; 229 | let failureCount = 0; 230 | 231 | const worker = new Worker( 232 | { 233 | connection: specHelper.cleanConnectionDetails(), 234 | timeout: specHelper.timeout, 235 | queues: [specHelper.queue], 236 | }, 237 | customJobs, 238 | ); 239 | 240 | worker.on("success", () => { 241 | failButRetryCount++; 242 | }); 243 | 244 | await worker.connect(); 245 | 246 | worker.on("failure", async () => { 247 | failureCount++; 248 | expect(failButRetryCount).toBe(4); 249 | expect(failureCount).toBe(1); 250 | expect(failButRetryCount + failureCount).toBe(5); 251 | 252 | const length = await specHelper.redis.llen( 253 | `${specHelper.namespace}:failed`, 254 | ); 255 | expect(length).toBe(1); 256 | await worker.end(); 257 | resolve(null); 258 | }); 259 | 260 | worker.start(); 261 | }); 262 | }); 263 | 264 | test("when a job fails it should be re-enqueued (and not go to the failure queue)", async () => { 265 | await new Promise(async (resolve) => { 266 | await queue.enqueue(specHelper.queue, "brokenJob", [1, 2]); 267 | 268 | const worker = new Worker( 269 | { 270 | connection: specHelper.cleanConnectionDetails(), 271 | timeout: specHelper.timeout, 272 | queues: [specHelper.queue], 273 | }, 274 | jobs, 275 | ); 276 | 277 | await worker.connect(); 278 | worker.on("success", async () => { 279 | const timestamps = await queue.scheduledAt( 280 | specHelper.queue, 281 | "brokenJob", 282 | [1, 2], 283 | ); 284 | expect(timestamps.length).toBe(1); 285 | const length = await specHelper.redis.llen( 286 | `${specHelper.namespace}:failed`, 287 | ); 288 | expect(length).toBe(0); 289 | await worker.end(); 290 | resolve(null); 291 | }); 292 | 293 | worker.start(); 294 | }); 295 | }); 296 | 297 | test("will handle the stats properly for failing jobs", async () => { 298 | await new Promise(async (resolve) => { 299 | await queue.enqueue(specHelper.queue, "brokenJob", [1, 2]); 300 | 301 | const worker = new Worker( 302 | { 303 | connection: specHelper.cleanConnectionDetails(), 304 | timeout: specHelper.timeout, 305 | queues: [specHelper.queue], 306 | }, 307 | jobs, 308 | ); 309 | 310 | await worker.connect(); 311 | 312 | worker.on("success", async () => { 313 | const globalProcessed = await specHelper.redis.get( 314 | `${specHelper.namespace}:stat:processed`, 315 | ); 316 | const globalFailed = await specHelper.redis.get( 317 | `${specHelper.namespace}:stat:failed`, 318 | ); 319 | const workerProcessed = await specHelper.redis.get( 320 | `${specHelper.namespace}:stat:processed:${worker.name}`, 321 | ); 322 | const workerFailed = await specHelper.redis.get( 323 | `${specHelper.namespace}:stat:failed:${worker.name}`, 324 | ); 325 | expect(String(globalProcessed)).toBe("0"); 326 | expect(String(globalFailed)).toBe("1"); 327 | expect(String(workerProcessed)).toBe("0"); 328 | expect(String(workerFailed)).toBe("1"); 329 | await worker.end(); 330 | resolve(null); 331 | }); 332 | 333 | worker.start(); 334 | }); 335 | }); 336 | 337 | test("will set the retry counter & retry data", async () => { 338 | await new Promise(async (resolve) => { 339 | await queue.enqueue(specHelper.queue, "brokenJob", [1, 2]); 340 | 341 | const worker = new Worker( 342 | { 343 | connection: specHelper.cleanConnectionDetails(), 344 | timeout: specHelper.timeout, 345 | queues: [specHelper.queue], 346 | }, 347 | jobs, 348 | ); 349 | 350 | await worker.connect(); 351 | worker.on("success", async () => { 352 | const retryAttempts = await specHelper.redis.get( 353 | `${specHelper.namespace}:resque-retry:brokenJob:1-2`, 354 | ); 355 | let failureData = await specHelper.redis.get( 356 | `${specHelper.namespace}:failure-resque-retry:brokenJob:1-2`, 357 | ); 358 | expect(String(retryAttempts)).toBe("0"); 359 | const failure = JSON.parse(failureData) as ParsedFailedJobPayload; 360 | expect(failure.payload).toEqual([1, 2]); 361 | expect(failure.exception).toBe("Error: BUSTED"); 362 | expect(failure.worker).toBe("brokenJob"); 363 | expect(failure.queue).toBe("test_queue"); 364 | await worker.end(); 365 | resolve(null); 366 | }); 367 | 368 | worker.start(); 369 | }); 370 | }); 371 | }); 372 | }); 373 | -------------------------------------------------------------------------------- /__tests__/core/worker.ts: -------------------------------------------------------------------------------- 1 | import { ParsedFailedJobPayload, Job, Queue, Worker, Plugin } from "../../src"; 2 | import specHelper from "../utils/specHelper"; 3 | 4 | class MyPlugin extends Plugin { 5 | async beforeEnqueue() { 6 | return true; 7 | } 8 | async afterEnqueue() { 9 | return true; 10 | } 11 | async beforePerform() { 12 | return true; 13 | } 14 | async afterPerform() { 15 | this.options.afterPerform(this); 16 | return true; 17 | } 18 | } 19 | 20 | const jobs: { [key: string]: Job } = { 21 | add: { 22 | perform: (a, b) => { 23 | return a + b; 24 | }, 25 | } as Job, 26 | //@ts-ignore 27 | badAdd: { 28 | perform: () => { 29 | throw new Error("Blue Smoke"); 30 | }, 31 | } as Job, 32 | messWithData: { 33 | perform: (a) => { 34 | a.data = "new thing"; 35 | return a; 36 | }, 37 | } as Job, 38 | async: { 39 | perform: async () => { 40 | await new Promise((resolve) => { 41 | setTimeout(resolve, 100); 42 | }); 43 | return "yay"; 44 | }, 45 | } as Job, 46 | twoSeconds: { 47 | perform: async () => { 48 | await new Promise((resolve) => { 49 | setTimeout(resolve, 1000 * 2); 50 | }); 51 | return "slow"; 52 | }, 53 | } as Job, 54 | //@ts-ignore 55 | quickDefine: async () => { 56 | return "ok"; 57 | }, 58 | }; 59 | 60 | let worker: Worker; 61 | let queue: Queue; 62 | 63 | describe("worker", () => { 64 | afterAll(async () => { 65 | await specHelper.disconnect(); 66 | }); 67 | 68 | test("can connect", async () => { 69 | const worker = new Worker( 70 | { connection: specHelper.connectionDetails, queues: [specHelper.queue] }, 71 | {}, 72 | ); 73 | await worker.connect(); 74 | await worker.end(); 75 | }); 76 | 77 | describe("performInline", () => { 78 | beforeAll(() => { 79 | worker = new Worker( 80 | { 81 | connection: specHelper.connectionDetails, 82 | timeout: specHelper.timeout, 83 | queues: [specHelper.queue], 84 | }, 85 | jobs, 86 | ); 87 | }); 88 | 89 | test("can run a successful job", async () => { 90 | const result = await worker.performInline("add", [1, 2]); 91 | expect(result).toBe(3); 92 | }); 93 | 94 | test("can run a successful async job", async () => { 95 | const result = await worker.performInline("async"); 96 | expect(result).toBe("yay"); 97 | }); 98 | 99 | test("can run a failing job", async () => { 100 | try { 101 | await worker.performInline("badAdd", [1, 2]); 102 | throw new Error("should not get here"); 103 | } catch (error) { 104 | expect(String(error)).toBe("Error: Blue Smoke"); 105 | } 106 | }); 107 | 108 | test("can call a Plugin's afterPerform given the job throws an error", async () => { 109 | let actual = null; 110 | let expected = new TypeError("John"); 111 | 112 | let failingJob = { 113 | plugins: [MyPlugin], 114 | pluginOptions: { 115 | MyPlugin: { 116 | afterPerform: (plugin: Plugin) => { 117 | actual = plugin.worker.error; 118 | delete plugin.worker.error; 119 | }, 120 | }, 121 | }, 122 | perform: (x: string) => { 123 | throw new TypeError(x); 124 | }, 125 | }; 126 | let worker = new Worker({}, { failingJob }); 127 | await worker.performInline("failingJob", ["John"]); 128 | 129 | expect(actual).toEqual(expected); 130 | }); 131 | }); 132 | 133 | describe("[with connection]", () => { 134 | beforeAll(async () => { 135 | await specHelper.connect(); 136 | queue = new Queue({ connection: specHelper.connectionDetails }, {}); 137 | await queue.connect(); 138 | }); 139 | 140 | afterAll(async () => { 141 | await specHelper.cleanup(); 142 | }); 143 | 144 | test("can boot and stop", async () => { 145 | worker = new Worker( 146 | { 147 | connection: specHelper.connectionDetails, 148 | timeout: specHelper.timeout, 149 | queues: [specHelper.queue], 150 | }, 151 | jobs, 152 | ); 153 | await worker.connect(); 154 | await worker.start(); 155 | await worker.end(); 156 | }); 157 | 158 | test("will determine the proper queue names", async () => { 159 | const worker = new Worker( 160 | { 161 | connection: specHelper.connectionDetails, 162 | timeout: specHelper.timeout, 163 | }, 164 | jobs, 165 | ); 166 | await worker.connect(); 167 | expect(worker.queues).toEqual([]); 168 | await queue.enqueue(specHelper.queue, "badAdd", [1, 2]); 169 | await worker.checkQueues(); 170 | expect(worker.queues).toEqual([specHelper.queue]); 171 | 172 | //@ts-ignore 173 | await queue.del(specHelper.queue); 174 | await worker.end(); 175 | }); 176 | 177 | describe("integration", () => { 178 | test("will notice new job queues when started with queues=*", async () => { 179 | await new Promise(async (resolve) => { 180 | const wildcardWorker = new Worker( 181 | { 182 | connection: specHelper.connectionDetails, 183 | timeout: specHelper.timeout, 184 | queues: ["*"], 185 | }, 186 | jobs, 187 | ); 188 | 189 | await wildcardWorker.connect(); 190 | await wildcardWorker.start(); 191 | 192 | setTimeout(async () => { 193 | await queue.enqueue("__newQueue", "add", [1, 2]); 194 | }, 501); 195 | 196 | wildcardWorker.on("success", async (q, job, result, duration) => { 197 | expect(q).toBe("__newQueue"); 198 | expect(job.class).toBe("add"); 199 | expect(result).toBe(3); 200 | expect(wildcardWorker.result).toBe(result); 201 | expect(duration).toBeGreaterThanOrEqual(0); 202 | 203 | wildcardWorker.removeAllListeners("success"); 204 | await wildcardWorker.end(); 205 | resolve(null); 206 | }); 207 | }); 208 | }); 209 | 210 | describe("with worker", () => { 211 | beforeEach(async () => { 212 | worker = new Worker( 213 | { 214 | connection: specHelper.connectionDetails, 215 | timeout: specHelper.timeout, 216 | queues: [specHelper.queue], 217 | }, 218 | jobs, 219 | ); 220 | await worker.connect(); 221 | }); 222 | 223 | afterEach(async () => { 224 | await worker.end(); 225 | }); 226 | 227 | test("will mark a job as failed", async () => { 228 | await new Promise(async (resolve) => { 229 | await queue.enqueue(specHelper.queue, "badAdd", [1, 2]); 230 | 231 | await worker.start(); 232 | 233 | worker.on("failure", (q, job, failire) => { 234 | expect(q).toBe(specHelper.queue); 235 | expect(job.class).toBe("badAdd"); 236 | expect(failire.message).toBe("Blue Smoke"); 237 | 238 | worker.removeAllListeners("failure"); 239 | resolve(null); 240 | }); 241 | }); 242 | }); 243 | 244 | test("can work a job and return successful things", async () => { 245 | await new Promise(async (resolve) => { 246 | await queue.enqueue(specHelper.queue, "add", [1, 2]); 247 | 248 | worker.start(); 249 | 250 | worker.on("success", (q, job, result, duration) => { 251 | expect(q).toBe(specHelper.queue); 252 | expect(job.class).toBe("add"); 253 | expect(result).toBe(3); 254 | expect(worker.result).toBe(result); 255 | expect(duration).toBeGreaterThanOrEqual(0); 256 | 257 | worker.removeAllListeners("success"); 258 | resolve(null); 259 | }); 260 | }); 261 | }); 262 | 263 | // TODO: Typescript seems to have trouble with frozen objects 264 | // test('job arguments are immutable', async (done) => { 265 | // await queue.enqueue(specHelper.queue, 'messWithData', { a: 'starting value' }) 266 | 267 | // worker.start() 268 | 269 | // worker.on('success', (q, job, result) => { 270 | // expect(result.a).toBe('starting value') 271 | // expect(worker.result).toBe(result) 272 | 273 | // worker.removeAllListeners('success') 274 | // done() 275 | // }) 276 | // }) 277 | 278 | test("can accept jobs that are simple functions", async () => { 279 | await new Promise(async (resolve) => { 280 | await queue.enqueue(specHelper.queue, "quickDefine"); 281 | 282 | worker.start(); 283 | 284 | worker.on("success", (q, job, result, duration) => { 285 | expect(result).toBe("ok"); 286 | expect(duration).toBeGreaterThanOrEqual(0); 287 | worker.removeAllListeners("success"); 288 | resolve(null); 289 | }); 290 | }); 291 | }); 292 | 293 | test("will not work jobs that are not defined", async () => { 294 | await new Promise(async (resolve) => { 295 | await queue.enqueue(specHelper.queue, "somethingFake"); 296 | 297 | worker.start(); 298 | 299 | worker.on("failure", (q, job, failure, duration) => { 300 | expect(q).toBe(specHelper.queue); 301 | expect(String(failure)).toBe( 302 | 'Error: No job defined for class "somethingFake"', 303 | ); 304 | expect(duration).toBeGreaterThanOrEqual(0); 305 | 306 | worker.removeAllListeners("failure"); 307 | resolve(null); 308 | }); 309 | }); 310 | }); 311 | 312 | test("will place failed jobs in the failed queue", async () => { 313 | let str = await specHelper.redis.rpop( 314 | specHelper.namespace + ":" + "failed", 315 | ); 316 | const data = JSON.parse(str) as ParsedFailedJobPayload; 317 | expect(data.queue).toBe(specHelper.queue); 318 | expect(data.exception).toBe("Error"); 319 | expect(data.error).toBe('No job defined for class "somethingFake"'); 320 | }); 321 | 322 | test("will ping with status even when working a slow job", async () => { 323 | await new Promise(async (resolve) => { 324 | const nowInSeconds = Math.round(new Date().getTime() / 1000); 325 | await worker.start(); 326 | await new Promise((resolve) => 327 | setTimeout(resolve, worker.options.timeout * 2), 328 | ); 329 | const pingKey = worker.connection.key( 330 | "worker", 331 | "ping", 332 | worker.name, 333 | ); 334 | const firstPayload = JSON.parse( 335 | await specHelper.redis.get(pingKey), 336 | ); 337 | expect(firstPayload.name).toEqual(worker.name); 338 | expect(firstPayload.time).toBeGreaterThanOrEqual(nowInSeconds); 339 | 340 | await queue.enqueue(specHelper.queue, "twoSeconds"); 341 | 342 | worker.on("success", (q, job, result) => { 343 | expect(result).toBe("slow"); 344 | worker.removeAllListeners("success"); 345 | resolve(null); 346 | }); 347 | 348 | const secondPayload = JSON.parse( 349 | await specHelper.redis.get(pingKey), 350 | ); 351 | expect(secondPayload.name).toEqual(worker.name); 352 | expect(secondPayload.time).toBeGreaterThanOrEqual( 353 | firstPayload.time, 354 | ); 355 | }); 356 | }); 357 | }); 358 | }); 359 | }); 360 | }); 361 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/core/worker.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from "events"; 2 | import { Cluster } from "ioredis"; 3 | import * as os from "os"; 4 | import { Jobs } from ".."; 5 | import { WorkerOptions } from "../types/options"; 6 | import { Connection } from "./connection"; 7 | import { RunPlugins } from "./pluginRunner"; 8 | import { ParsedJob, Queue } from "./queue"; 9 | 10 | function prepareJobs(jobs: Jobs) { 11 | return Object.keys(jobs).reduce((h: { [key: string]: any }, k) => { 12 | const job = jobs[k]; 13 | h[k] = typeof job === "function" ? { perform: job } : job; 14 | return h; 15 | }, {}); 16 | } 17 | 18 | export declare interface Worker { 19 | options: WorkerOptions; 20 | jobs: Jobs; 21 | started: boolean; 22 | name: string; 23 | queues: Array | string; 24 | queue: string; 25 | originalQueue: string | null; 26 | error: Error | null; 27 | result: any; 28 | ready: boolean; 29 | running: boolean; 30 | working: boolean; 31 | pollTimer: NodeJS.Timeout; 32 | endTimer: NodeJS.Timeout; 33 | pingTimer: NodeJS.Timeout; 34 | job: ParsedJob; 35 | connection: Connection; 36 | queueObject: Queue; 37 | id: number; 38 | 39 | on(event: "start" | "end" | "pause", cb: () => void): this; 40 | on(event: "cleaning_worker", cb: (worker: Worker, pid: string) => void): this; 41 | on(event: "poll", cb: (queue: string) => void): this; 42 | on(event: "ping", cb: (time: number) => void): this; 43 | on(event: "job", cb: (queue: string, job: ParsedJob) => void): this; 44 | on( 45 | event: "reEnqueue", 46 | cb: (queue: string, job: ParsedJob, plugin: string) => void, 47 | ): this; 48 | on( 49 | event: "success", 50 | cb: (queue: string, job: ParsedJob, result: any, duration: number) => void, 51 | ): this; 52 | on( 53 | event: "failure", 54 | cb: ( 55 | queue: string, 56 | job: ParsedJob, 57 | failure: Error, 58 | duration: number, 59 | ) => void, 60 | ): this; 61 | on( 62 | event: "error", 63 | cb: (error: Error, queue: string, job: ParsedJob) => void, 64 | ): this; 65 | 66 | once(event: "start" | "end" | "pause", cb: () => void): this; 67 | once( 68 | event: "cleaning_worker", 69 | cb: (worker: Worker, pid: string) => void, 70 | ): this; 71 | once(event: "poll", cb: (queue: string) => void): this; 72 | once(event: "ping", cb: (time: number) => void): this; 73 | once(event: "job", cb: (queue: string, job: ParsedJob) => void): this; 74 | once( 75 | event: "reEnqueue", 76 | cb: (queue: string, job: ParsedJob, plugin: string) => void, 77 | ): this; 78 | once( 79 | event: "success", 80 | cb: (queue: string, job: ParsedJob, result: any) => void, 81 | ): this; 82 | once( 83 | event: "failure", 84 | cb: (queue: string, job: ParsedJob, failure: any) => void, 85 | ): this; 86 | once( 87 | event: "error", 88 | cb: (error: Error, queue: string, job: ParsedJob) => void, 89 | ): this; 90 | 91 | removeAllListeners(event: string): this; 92 | } 93 | 94 | export type WorkerEvent = 95 | | "start" 96 | | "end" 97 | | "cleaning_worker" 98 | | "poll" 99 | | "ping" 100 | | "job" 101 | | "reEnqueue" 102 | | "success" 103 | | "failure" 104 | | "error" 105 | | "pause"; 106 | 107 | export class Worker extends EventEmitter { 108 | constructor(options: WorkerOptions, jobs: Jobs = {}) { 109 | super(); 110 | 111 | options.name = options.name ?? os.hostname() + ":" + process.pid; // assumes only one worker per node process 112 | options.id = options.id ?? 1; 113 | options.queues = options.queues ?? "*"; 114 | options.timeout = options.timeout ?? 5000; 115 | options.looping = options.looping ?? true; 116 | 117 | this.options = options; 118 | this.jobs = prepareJobs(jobs); 119 | this.name = this.options.name; 120 | this.queues = this.options.queues; 121 | this.queue = null; 122 | this.originalQueue = null; 123 | this.error = null; 124 | this.result = null; 125 | this.ready = true; 126 | this.running = false; 127 | this.working = false; 128 | this.job = null; 129 | this.pollTimer = null; 130 | this.endTimer = null; 131 | this.pingTimer = null; 132 | this.started = false; 133 | 134 | this.queueObject = new Queue({ connection: options.connection }, this.jobs); 135 | this.queueObject.on("error", (error) => { 136 | this.emit("error", error); 137 | }); 138 | } 139 | 140 | async connect() { 141 | await this.queueObject.connect(); 142 | this.connection = this.queueObject.connection; 143 | await this.checkQueues(); 144 | } 145 | 146 | async start() { 147 | if (this.ready) { 148 | this.started = true; 149 | this.emit("start", new Date()); 150 | await this.init(); 151 | this.poll(); 152 | } 153 | } 154 | 155 | async init() { 156 | await this.track(); 157 | await this.connection.redis.set( 158 | this.connection.key("worker", this.name, this.stringQueues(), "started"), 159 | Math.round(new Date().getTime() / 1000), 160 | ); 161 | await this.ping(); 162 | this.pingTimer = setInterval(this.ping.bind(this), this.options.timeout); 163 | } 164 | 165 | async end(): Promise { 166 | this.running = false; 167 | 168 | if (this.working === true) { 169 | await new Promise((resolve) => { 170 | this.endTimer = setTimeout(() => { 171 | resolve(null); 172 | }, this.options.timeout); 173 | }); 174 | return this.end(); 175 | } 176 | 177 | clearTimeout(this.pollTimer); 178 | clearTimeout(this.endTimer); 179 | clearInterval(this.pingTimer); 180 | 181 | if ( 182 | this.connection && 183 | (this.connection.connected === true || 184 | this.connection.connected === undefined || 185 | this.connection.connected === null) 186 | ) { 187 | await this.untrack(); 188 | } 189 | 190 | await this.queueObject.end(); 191 | this.emit("end", new Date()); 192 | } 193 | 194 | private async poll(nQueue = 0): Promise { 195 | if (!this.running) return; 196 | 197 | this.queue = this.queues[nQueue]; 198 | this.emit("poll", this.queue); 199 | 200 | if (this.queue === null || this.queue === undefined) { 201 | await this.checkQueues(); 202 | await this.pause(); 203 | return null; 204 | } 205 | 206 | if (this.working === true) { 207 | const error = new Error("refusing to get new job, already working"); 208 | this.emit("error", error, this.queue); 209 | return null; 210 | } 211 | 212 | this.working = true; 213 | 214 | try { 215 | const currentJob = await this.getJob(); 216 | if (currentJob) { 217 | if (this.options.looping) { 218 | this.result = null; 219 | await this.perform(currentJob); 220 | } else { 221 | return currentJob; 222 | } 223 | } else { 224 | this.working = false; 225 | if (nQueue === this.queues.length - 1) { 226 | if (this.originalQueue === "*") await this.checkQueues(); 227 | await this.pause(); 228 | return null; 229 | } else { 230 | return this.poll(nQueue + 1); 231 | } 232 | } 233 | } catch (error) { 234 | this.emit("error", error, this.queue); 235 | this.working = false; 236 | await this.pause(); 237 | return null; 238 | } 239 | } 240 | 241 | private async perform(job: ParsedJob) { 242 | this.job = job; 243 | this.error = null; 244 | let toRun; 245 | const startedAt = new Date().getTime(); 246 | 247 | if (!this.jobs[job.class]) { 248 | this.error = new Error(`No job defined for class "${job.class}"`); 249 | return this.completeJob(false, startedAt); 250 | } 251 | 252 | const perform = this.jobs[job.class].perform; 253 | if (!perform || typeof perform !== "function") { 254 | this.error = new Error(`Missing Job: "${job.class}"`); 255 | return this.completeJob(false, startedAt); 256 | } 257 | this.emit("job", this.queue, this.job); 258 | 259 | let triedAfterPerform = false; 260 | try { 261 | toRun = await RunPlugins( 262 | this, 263 | "beforePerform", 264 | job.class, 265 | this.queue, 266 | this.jobs[job.class], 267 | job.args, 268 | ); 269 | if (toRun === false) { 270 | return this.completeJob(false, startedAt); 271 | } 272 | 273 | let callableArgs = [job.args]; 274 | if (job.args === undefined || job.args instanceof Array) { 275 | callableArgs = job.args; 276 | } 277 | 278 | for (const i in callableArgs) { 279 | if (typeof callableArgs[i] === "object" && callableArgs[i] !== null) { 280 | Object.freeze(callableArgs[i]); 281 | } 282 | } 283 | 284 | this.result = await perform.apply(this, callableArgs); 285 | triedAfterPerform = true; 286 | toRun = await RunPlugins( 287 | this, 288 | "afterPerform", 289 | job.class, 290 | this.queue, 291 | this.jobs[job.class], 292 | job.args, 293 | ); 294 | return this.completeJob(true, startedAt); 295 | } catch (error) { 296 | this.error = error; 297 | if (!triedAfterPerform) { 298 | try { 299 | await RunPlugins( 300 | this, 301 | "afterPerform", 302 | job.class, 303 | this.queue, 304 | this.jobs[job.class], 305 | job.args, 306 | ); 307 | } catch (error) { 308 | if (error && !this.error) { 309 | this.error = error; 310 | } 311 | } 312 | } 313 | return this.completeJob(!this.error, startedAt); 314 | } 315 | } 316 | 317 | // #performInline is used to run a job payload directly. 318 | // If you are planning on running a job via #performInline, this worker should also not be started, nor should be using event emitters to monitor this worker. 319 | // This method will also not write to redis at all, including logging errors, modify resque's stats, etc. 320 | async performInline(func: string, args: any[] = []) { 321 | const q = "_direct-queue-" + this.name; 322 | let toRun; 323 | 324 | if (!(args instanceof Array)) { 325 | args = [args]; 326 | } 327 | 328 | if (this.started) { 329 | throw new Error( 330 | "Worker#performInline can not be used on a started worker", 331 | ); 332 | } 333 | if (!this.jobs[func]) { 334 | throw new Error(`No job defined for class "${func}"`); 335 | } 336 | if (!this.jobs[func].perform) { 337 | throw new Error(`Missing Job: "${func}"`); 338 | } 339 | 340 | let triedAfterPerform = false; 341 | try { 342 | toRun = await RunPlugins( 343 | this, 344 | "beforePerform", 345 | func, 346 | q, 347 | this.jobs[func], 348 | args, 349 | ); 350 | if (toRun === false) { 351 | return; 352 | } 353 | this.result = await this.jobs[func].perform.apply(this, args); 354 | triedAfterPerform = true; 355 | toRun = await RunPlugins( 356 | this, 357 | "afterPerform", 358 | func, 359 | q, 360 | this.jobs[func], 361 | args, 362 | ); 363 | return this.result; 364 | } catch (error) { 365 | this.error = error; 366 | if (!triedAfterPerform) { 367 | try { 368 | await RunPlugins( 369 | this, 370 | "afterPerform", 371 | func, 372 | this.queue, 373 | this.jobs[func], 374 | args, 375 | ); 376 | } catch (error) { 377 | if (error && !this.error) { 378 | this.error = error; 379 | } 380 | } 381 | } 382 | // Allow afterPerform to clear the error 383 | if (this.error) throw this.error; 384 | } 385 | } 386 | 387 | private async completeJob(toRespond: boolean, startedAt: number) { 388 | const duration = new Date().getTime() - startedAt; 389 | if (this.error) { 390 | await this.fail(this.error, duration); 391 | } else if (toRespond) { 392 | await this.succeed(this.job, duration); 393 | } 394 | 395 | this.working = false; 396 | await this.connection.redis.del( 397 | this.connection.key("worker", this.name, this.stringQueues()), 398 | ); 399 | this.job = null; 400 | 401 | if (this.options.looping) { 402 | this.poll(); 403 | } 404 | } 405 | 406 | private async succeed(job: ParsedJob, duration: number) { 407 | const response = await this.connection.redis 408 | .multi() 409 | .incr(this.connection.key("stat", "processed")) 410 | .incr(this.connection.key("stat", "processed", this.name)) 411 | .exec(); 412 | 413 | response.forEach((res) => { 414 | if (res[0] !== null) { 415 | throw res[0]; 416 | } 417 | }); 418 | 419 | this.emit("success", this.queue, job, this.result, duration); 420 | } 421 | 422 | private async fail(err: Error, duration: number) { 423 | const response = await this.connection.redis 424 | .multi() 425 | .incr(this.connection.key("stat", "failed")) 426 | .incr(this.connection.key("stat", "failed", this.name)) 427 | .rpush( 428 | this.connection.key("failed"), 429 | JSON.stringify(this.failurePayload(err, this.job)), 430 | ) 431 | .exec(); 432 | 433 | response.forEach((res) => { 434 | if (res[0] !== null) { 435 | throw res[0]; 436 | } 437 | }); 438 | 439 | this.emit("failure", this.queue, this.job, err, duration); 440 | } 441 | 442 | private async pause() { 443 | this.emit("pause"); 444 | await new Promise((resolve) => { 445 | this.pollTimer = setTimeout(() => { 446 | this.poll(); 447 | resolve(null); 448 | }, this.options.timeout); 449 | }); 450 | } 451 | 452 | private async getJob() { 453 | let currentJob: ParsedJob; 454 | const queueKey = this.connection.key("queue", this.queue); 455 | const workerKey = this.connection.key( 456 | "worker", 457 | this.name, 458 | this.stringQueues(), 459 | ); 460 | 461 | let encodedJob: string; 462 | 463 | if ( 464 | // We cannot use the atomic Lua script if we are using redis cluster - the shard storing the queue and worker may not be the same 465 | !(this.connection.redis instanceof Cluster) && 466 | //@ts-ignore 467 | this.connection.redis["popAndStoreJob"] 468 | ) { 469 | //@ts-ignore 470 | encodedJob = await this.connection.redis["popAndStoreJob"]( 471 | queueKey, 472 | workerKey, 473 | new Date().toString(), 474 | this.queue, 475 | this.name, 476 | ); 477 | } else { 478 | encodedJob = await this.connection.redis.lpop(queueKey); 479 | if (encodedJob) { 480 | await this.connection.redis.set( 481 | workerKey, 482 | JSON.stringify({ 483 | run_at: new Date().toString(), 484 | queue: this.queue, 485 | worker: this.name, 486 | payload: JSON.parse(encodedJob), 487 | }), 488 | ); 489 | } 490 | } 491 | 492 | if (encodedJob) currentJob = JSON.parse(encodedJob); 493 | 494 | return currentJob; 495 | } 496 | 497 | private async track() { 498 | this.running = true; 499 | return this.connection.redis.sadd( 500 | this.connection.key("workers"), 501 | this.name + ":" + this.stringQueues(), 502 | ); 503 | } 504 | 505 | private async ping() { 506 | if (!this.running) return; 507 | 508 | const name = this.name; 509 | const nowSeconds = Math.round(new Date().getTime() / 1000); 510 | this.emit("ping", nowSeconds); 511 | const payload = JSON.stringify({ 512 | time: nowSeconds, 513 | name: name, 514 | queues: this.stringQueues(), 515 | }); 516 | await this.connection.redis.set( 517 | this.connection.key("worker", "ping", name), 518 | payload, 519 | ); 520 | } 521 | 522 | private async untrack() { 523 | const name = this.name; 524 | const queues = this.stringQueues(); 525 | if (!this.connection || !this.connection.redis) { 526 | return; 527 | } 528 | 529 | const response = await this.connection.redis 530 | .multi() 531 | .srem(this.connection.key("workers"), name + ":" + queues) 532 | .del(this.connection.key("worker", "ping", name)) 533 | .del(this.connection.key("worker", name, queues)) 534 | .del(this.connection.key("worker", name, queues, "started")) 535 | .del(this.connection.key("stat", "failed", name)) 536 | .del(this.connection.key("stat", "processed", name)) 537 | .exec(); 538 | 539 | response.forEach((res) => { 540 | if (res[0] !== null) { 541 | throw res[0]; 542 | } 543 | }); 544 | } 545 | 546 | async checkQueues() { 547 | if (Array.isArray(this.queues) && this.queues.length > 0) { 548 | this.ready = true; 549 | } 550 | 551 | if ( 552 | (this.queues[0] === "*" && this.queues.length === 1) || 553 | this.queues.length === 0 || 554 | this.originalQueue === "*" 555 | ) { 556 | this.originalQueue = "*"; 557 | await this.untrack(); 558 | const response = await this.connection.redis.smembers( 559 | this.connection.key("queues"), 560 | ); 561 | this.queues = response ? response.sort() : []; 562 | await this.track(); 563 | } 564 | } 565 | 566 | private failurePayload(err: Error, job: ParsedJob) { 567 | return { 568 | worker: this.name, 569 | queue: this.queue, 570 | payload: job, 571 | exception: err.name, 572 | error: err.message, 573 | backtrace: err.stack ? err.stack.split("\n").slice(1) : null, 574 | failed_at: new Date().toString(), 575 | }; 576 | } 577 | 578 | private stringQueues() { 579 | if (this.queues.length === 0) { 580 | return ["*"].join(","); 581 | } else { 582 | try { 583 | return Array.isArray(this.queues) ? this.queues.join(",") : this.queues; 584 | } catch (e) { 585 | return ""; 586 | } 587 | } 588 | } 589 | } 590 | 591 | exports.Worker = Worker; 592 | --------------------------------------------------------------------------------