-
Notifications
You must be signed in to change notification settings - Fork 48
/
path.js
67 lines (60 loc) · 1.9 KB
/
path.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var log = require("../lib/util/log")("Path")
// implements https://github.com/telehash/telehash.org/blob/v3/v3/channels/path.md
exports.name = 'path';
exports.mesh = function(mesh, cbExt)
{
var ext = {open:{}};
// path sync requests
ext.open.path = function(args, open, cbOpen){
var link = this;
var did = [];
function pong(pipe)
{
if(did.indexOf(pipe) >= 0) return;
did.push(pipe);
var json = {c:open.json.c};
if(pipe.path) json.path = pipe.path;
link.x.send({json:json},pipe);
}
// go through all the pipes we have already and send a response
link.pipes.forEach(pong);
// add any of the included paths, and send to them too
if(Array.isArray(open.json.paths)) open.json.paths.forEach(function(path){
link.addPath(path,pong);
});
}
ext.link = function(link, cbLink)
{
/** force a path sync to confirm connectivity and record latency for paths
* @memberOf TLink
* @param {function} done - called when/if the first 'pong' is received, receives status and latency as arguments
*/
link.ping = function(done)
{
if(typeof done != 'function') done = function(){};
if(link.down) return done(link.down);
var json = {type:'path'};
json.paths = mesh.paths();
var channel = link.x.channel({json:json});
var start = Date.now();
channel.receiving = function(err, packet, cbChan)
{
// process any responses
if(packet)
{
log.debug('path response, TODO get public udp paths',packet.json);
}
// only callback once w/ status and latency
if(done) done(err, Date.now() - start);
done = false;
cbChan();
}
log.debug('sending path ping to',link.hashname,json.paths);
channel.send({json:json});
}
// auto-ping on first status
link.on('status',link.ping);
cbLink();
}
cbExt(undefined, ext);
}