Created
May 19, 2012 13:31
-
-
Save jinroh/2730863 to your computer and use it in GitHub Desktop.
Iterative Deferred with finish conditions...and timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 !