Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ponos

Package Overview
Dependencies
Maintainers
3
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ponos

An opinionated queue based worker server for node.

  • 1.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
19
decreased by-38.71%
Maintainers
3
Weekly downloads
 
Created
Source

Ponos

travis coveralls dependencies devdependencies

An opinionated queue based worker server for node.

For ease of use we provide options to set the host, port, username, and password to the RabbitMQ server. If not present in options, the server will attempt to use the following environment variables and final defaults:

optionsenvironmentdefault
opts.hostnameRABBITMQ_HOSTNAME'localhost'
opts.portRABBITMQ_PORT'5672'
opts.usernameRABBITMQ_USERNAME'guest'
opts.passwordRABBITMQ_PASSWORD'guest'
opts.logN/ABasic bunyan instance with stdout stream (for logging)
opts.errorCatN/ABasic error-cat instance (for rollbar error reporting)

Other options for Ponos are as follows:

Environmentdefaultdescription
WORKER_MAX_RETRY_DELAY0The maximum time, in milliseconds, that the worker will wait before retrying a task. The timeout will exponentially increase from MIN_RETRY_DELAY to MAX_RETRY_DELAY if the latter is set higher than the former. If this value is not set, the worker will not exponentially back off.
WORKER_MIN_RETRY_DELAY1Time, in milliseconds, the worker will wait at minimum will wait before retrying a task.
WORKER_TIMEOUT0Timeout, in milliseconds, at which the worker task will be retried.

Usage

From a high level, Ponos is used to create a worker server that responds to jobs provided from RabbitMQ. The user defines handlers for each queue's jobs that are invoked by Ponos.

Ponos has built in support for retrying and catching specific errors, which are described below.

Workers

Workers need to be defined as a function that takes a Object job an returns a promise. For example:

function myWorker (job) {
  return Promise.resolve()
    .then(function () {
      return doSomeWork(job);
    });
}

This worker takes the job, does work with it, and returns the result. Since (in theory) this does not throw any errors, the worker will see this resolution and acknowledge the job.

Worker Errors

Ponos's worker is designed to retry any error that is not specifically a fatal error. A fatal error is defined with the TaskFatalError class. If a worker rejects with a TaskFatalError, the worker will automatically assume the job can never be completed and will acknowledge the job.

As an example, a TaskFatalError can be used to fail a task given an invalid job:

var TaskFatalError = require('ponos').TaskFatalError;
function myWorker (job) {
  return Promise.resolve()
    .then(function () {
      if (!job.host) { throw new TaskFatalError('host is required'); }
    })
    .then(function () {
      return doSomethingWithHost(job);
    })
    .catch(function (err) {
      myErrorReporter(err);
      throw err;
    });
}

This worker will reject the promise with a TaskFatalError. Ponos will log the error itself, acknowledge the job to remove it from the queue, and continue with other jobs. It is up to the user to additionally catch the error and log it to any other external service.

Finally, as was mentioned before, Ponos will retry any other errors. Ponos provides a TaskError class you may use, or you may throw normal Errors. If you do, the worker will catch these and retry according to the server's configuration (retry delay, back-off, max delay, etc.).

var TaskError = require('ponos').TaskError;
var TaskFatalError = require('ponos').TaskFatalError;
function myWorker (job) {
  return Promise.resolve()
    .then(function () {
      return externalService.something(job);
    })
    // Note: w/o this catch, the error would simply propagate to the worker and
    // be handled.
    .catch(function (err) {
      logErrorToService(err);
      // If the error is 'recoverable' (e.g., network fluke, temporary outage),
      // we want to be able to retry.
      if (err.isRecoverable) {
        throw new Error('hit a momentary issue. try again.');
      } else {
        // maybe we know we can't recover from this
        throw new TaskFatalError('cannot recover. acknowledge and remove job');
      }
    });
}

Worker Options

Currently workers can be defined with a msTimeout option. This value defaults to process.env.WORKER_TIMEOUT || 0. One can set a specific millisecond timeout for a worker like so:

server.setTask('my-queue', workerFunction, { msTimeout: 1234 });

Or one can set this option via setAllTasks:

server.setAllTasks({
  // This will use the default timeout...
  'queue-1': queueOneTaskFn,
  // This will use the specified timeout...
  'queue-2': {
    task: queueTwoTaskFn,
    msTimeout: 1337
  }
});

Full Example

var ponos = require('ponos');

var tasks = {
  'queue-1': function (job) { return Promise.resolve(job); },
  'queue-2': function (job) { return Promise.resolve(job); }
};

// Create the server
var server = new ponos.Server({
  queues: Object.keys(tasks);
});

// Set tasks for workers handling jobs on each queue
server.setAllTasks(tasks);

// Start the server!
server.start()
  .then(function () { console.log('Server started!'); })
  .catch(function (err) { console.error('Server failed', err); });

// Or, start using your own hermes client
var hermes = require('runnable-hermes');
var server = new ponos.Server({ hermes: hermes.hermesSingletonFactory({...}) });

// You can also nicely chain the promises!
server.setAllTasks()
  .then(server.start())
  .then(function () { /*...*/ })
  .catch(function (err) { /*...*/ });

License

MIT

Keywords

FAQs

Package last updated on 15 Oct 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc