Skip to content

Reactor

jinroh edited this page May 20, 2012 · 1 revision

Reactor is the object responsible for handling network activity. Reactor consumes and produces requests delivered concurrently and encapsulated in simple RPC objects.

Reactor helps you deal with asynchronous events through simple Deferred RPC objects, so that you can simply concentrate on the logical aspectw of your network activity. This is useful in distributed systems which generate lots of complex network events.

Example

The RPC class is extended to specific classes corresponding to the different RPC methods (PingRPC, FindNodeRPC, FindValueRPC, StoreRPC) used in Kademlia. These extensions allows to perform specific handling of query parameters and response arguments. You can define your own RPCs by extending RPC. And because RPCs are only Deferred objects, you can imagine complex flow of events using standard patterns.

Here is an example of how an RPC is built and sent through the reactor. Notice how you can attack asynchronous callbacks :

Querying Peer:

// Example of an RPC:
//   - first parameter is the queried Peer
//   - next parameters are the parameters of your RPC
rpc = new MyRPC(peer, 'foo', ['bar'], /* ... */);

function errback(error) { /* ... */ }
function callback(response) { /* ... */ }

// attach the success and errors handlers
// which will be when the query is completed with the
// parameters you specified in MyRPC
rpc.then(callback, errback);

// send it through the reactor
reactor.sendQuery(rpc);

To handle incoming request, the RPC can be handled by listening to the queried event of the reactor. This event can be attached to a function which takes an RPC as a parameter. Notice that the incoming RPC are the same object than the one you send. That way clients queried and querying peers handle the exact same objects sent through the reactor.

Queried Peer:

reactor.on('queried', function(rpc) {

  if(rpc instanceof MyRPC) {
    var response = /* ... */;
    /* .. do whatever you have to do with it .. */
    /* .. the rpc object contains the 'foo' and ['bar'] parameters .. */

    // resolve the rpc to respond to the request
    // you could also reject it if any problem
    rpc.resolve(response); // will call `callback` function
    // or
    rpc.reject(response);  // will call `errback` function
  }

});

API

TODO

Events

TODO