joyent/node — pull request #2388 by AndreasMadsen (2011-12-20 16:45:49+00:00)
Title: Cluster 2.0 – step 4 : Worker class and isolate internal messages

I know this is a big patch, but it is the foundation of the `cluster 2.0` and cannot be split without creating a hopeless design.

The important part here is that there now exist a Worker class/object this exist in both workers and clusters and are used in the same way. The worker object is a worker accessed using `cluster.worker` and in the cluster the object is return from `fork` and stored in `cluster.workers` and a callback argument in a lot of functions and events.

**Example on worker object:**
In the master you send a message to the worker using `worker.send`. In a worker you send a message to the master using `worker.send`.

The next important part is the message system, this now isolate internal messages from userland, and support callbacks both ways.

This changes may seam to have nothing to do with each other, but the Worker object use internal messages more and the message system don't make sense without a standardized Worker object.

**The API changes are:**

* `cluster.fork` do no longer extend directly on on `child_process.fork`. The object return by `child_process.fork` must now be accessed from `cluster.fork().process`.
* `worker.kill` is renamed to `worker.destroy`.
* `worker.on('exit')` is now `worker.on('death')`
* You should not use `process.send` but `cluster.worker.send` in the worker.
* You should not use `process.on('message')` but `cluster.worker.on('message')` in the worker.
* You should not use `process.exit` but `cluster.worker.destroy`, the difference is that `destroy` send a suicide message to the `master`, this indicate that we won't want to restart the worker (not implemented yet).
* You may want to know that the env property `CLUSTER_WORKER_ID` is now called `CLUSTER_UNIQUE_ID`, but this was not a part of the official API.
* The `worker.send()` has change a lot internal, but should not cause any problems, the old function exist now as `worker.process.send()`

**The API additions are:**

* New events in the `cluster` object `fork, online, listening`
* New events in the `worker` object `online, listening`
* A state property in the worker object `worker.state` this can be `none, online, listening, dead`
* A suicide property in the worker object `worker.suicide` if `undefined` the worker is alive, if `false` the worker died `accidently`, if `true` the worker died by purpose.
* New `cluster.eachWorker` use it to run a function on every living worker.
* A uniqueID is assigned to each worker and can be read from `worker.workerID`.
* The send function now support callback in both worker and master, the callback will be called when the message is received.

_This is about the merging in the `cluster 2.0` ( see #2038 ) pull request_