Skip to content

Instantly share code, notes, and snippets.

@jinroh
Created May 19, 2012 13:31
Show Gist options
  • Save jinroh/2730863 to your computer and use it in GitHub Desktop.
Save jinroh/2730863 to your computer and use it in GitHub Desktop.
Iterative Deferred with finish conditions...and timeout
var lookup = function(target) {
var send = function() { /* ... */ },
iterative = new IterativeFind(),
init = new XORSortedPeerArray().relativeNodeID(target),
staled = false;
function map(peer) {
var rpc = new FindNodeRPC(peer, this._target);
send(rpc);
return rpc;
}
function reduce(peers, newPeers, map, queried, reached) {
peers.add(newPeers);
if(queried.getID() === target) {
iterative.resolve(queried, new XORSortedPeerArray(reached, target));
return;
}
closestIndex = peers.newClosestIndex();
if(closestIndex < globals.ALPHA && closestIndex >= 0) {
peers.pickOutFirst(globals.ALPHA).forEach(map);
}
return peers;
}
function finish(peers, map, reached, unreached) {
if (reached.length >= minimum) {
iterative.resolve(reached, unreached);
} else {
// We don't want to stale protect twice
if (staled) {
iterative.reject(reached, unreached);
} else {
peers.pickOutFirst(globals.K).forEach(map);
staled = true;
}
}
}
// Could be nice to a have a way to stop
// the process with a `cancel` or `stop` function
// to perform lookup timeout...
setTimeout(function iterativeTimeout() {
iterative.stop();
}, 30 * 1000);
return iterative
.map(map)
.reduce(reduce)
.init(init)
.start();
}
@jinroh
Copy link
Author

jinroh commented May 19, 2012

@alexstrat here is how we could implement the "stale protection" algorithm. We only need to make the finish function able to relaunch the process with a map().

There may be other way to do it though !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment