Giter Club home page Giter Club logo

node-forky's Introduction

node-forky

Build Status

Forky makes using the cluster module easier without preventing you from using it directly.

Problem: using require('cluster') properly is difficult, error prone, and hard to test.
Solution:

master.js

var forky = require('forky');
forky(__dirname + '/worker.js');

worker.js

var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'content-type': 'text/html'});
  res.end('Hello from worker ' + require('cluster').worker.id);
});

bash

$ node master
For a more complete example please check out the detailed example implementation

installation

npm install forky

usage

Forky is meant to work with your existing http server without modifying the server.
To take advantage of a multi-core system create a new file called master.js and require forky:

master.js

var forky = require('forky');

Once this file is created, call forky by passing it the file path to your existing http server or your old entry point to your application.

example: if you used to type node index.js to start your application, your master.js file should look like this

master.js

var forky = require('forky');
forky(__dirname + '/index.js');

What forky will do is spawn a number of workers equal to the number of cores you have available on your system.
If one of these workers disconnects for any reason due to a process.uncaughtException or even a kill -9 <pid> to the worker process, forky will spawn a new worker immedately.
After forky has spawned a new worker it will attempt to gracefully shut down your disconnecte worker. After a timeout if your disconnected worker is still running, forky will forcefully kill it.

The best way to handle unexpected errors in node is to shut down your process and spawn a new one. Forky makes clean process shutdown & respawn easy as pie.

Let's implement an http server in node that throws an uncatchable exception.

index.js

var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'content-type': 'text/html'});
  res.end('everything is groovy');
  setTimeout(function() {
    throw new Error("This will crash your node process");
  }, 1000);
});

Now if someone hits our server, 1 second later the server will crash. The easy but wrong way to handle this is by adding a process.on('uncaughtException') handler and just keep going forward as if nothing has happend:

index.js

var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'content-type': 'text/html'});
  res.end('everything is groovy');
  setTimeout(function() {
    throw new Error("This will crash your node process");
  }, 1000);
});

process.on('uncaughtException', function(err) {
  //log the error
  console.error(err);
  //continue on as if nothing has happend...
  //but something HAS happened.  What if the error wasn't in a timeout?
  //what if our error came from somewhere deep down and left some dangling
  //uncloses sockets or connections to database or open files?  We could be leaking
  //resources slowly and not even know it. oh no!
});

Instead of doing that let's use our master.js file we created above and modify our worker to gracefully disconnect to cleanup the problems caused by the unexpected error:

index.js

var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'content-type': 'text/html'});
  res.end('everything is groovy');
  setTimeout(function() {
    throw new Error("This will crash your node process");
  }, 1000);
});

process.on('uncaughtException', function(err) {
  //log the error
  console.error(err);
  //let's tell our master we need to be disconnected
  require('forky').disconnect();
  //in a worker process, this will signal the master that something is wrong
  //the master will immediately spawn a new worker
  //and the master will disconnect our server, allowing all existing traffic to end naturally
  //but not allowing this process to accept any new traffic
});

All of the above is to help with graceful shutdowns. Forky doesn't actually need you to signal disconnect from your workers. You can just let the exception crash the process, you can call process.exit(), or do anything else you want to clean up. Once your worker closes, regardless of the reason, forky will spawn a new one.

setting number of workers

Forky takes an optional second argument, an integer, and will use that as the number of workers to spawn instead of spawning based on the number of cores you have. Example:

var forky = require('forky')
forky(__dirname + '/index.js', 100, function(err) {
  console.log("you spawned 100 workers. That's a lot.")
})

Contributing

I love contributions. If you'd like to contribute a bug fix, send in yer pull requests!

If you want to add a more substantial feature open an issue, and let's discuss it. We can turn that issue into a pull request and get new features added. Open Source Is Awesome. ๐Ÿ‘

Due to the race-condition type nature of managing a cluster of workers the tests don't use a test framework, they just batter the hell out of the example server and make sure it never returns an unexpected result. To run the tests just type make after cloning & doing an npm install

License

Copyright (c) 2013 Brian M. Carlson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-forky's People

Contributors

brianc avatar freewil avatar jtrautman avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.