-
Notifications
You must be signed in to change notification settings - Fork 0
/
probe.js
109 lines (99 loc) · 2.33 KB
/
probe.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { Endpoint } from "@ndn/endpoint";
import { Forwarder } from "@ndn/fw";
import { splitHostPort, UdpTransport } from "@ndn/node-transport";
import { Name } from "@ndn/packet";
import { WsTransport } from "@ndn/ws-transport";
import hirestime from "hirestime";
import WebSocket from "ws";
const getNow = hirestime();
/** @typedef {{ ok: boolean; rtt?: number; error?: string; }} ProbeResult */
/** Transport probe. */
export class Probe {
/**
* @param {import("./request.js").Request} request
*/
constructor(request) {
this.request = request;
this.fw = Forwarder.create();
this.endpoint = new Endpoint({
fw: this.fw,
modifyInterest: {
mustBeFresh: true,
hopLimit: 64,
},
retx: 1,
});
}
/**
* Run the probe.
* @returns {Promise<{ connected: boolean; connectError?: string; probes?: ProbeResult[] }>}
*/
async run() {
const result = {
connected: false,
};
try {
this.face = await this.openFace();
} catch (err) {
result.connectError = `${err}`;
return result;
}
result.connected = true;
this.face.addRoute(new Name(), false);
result.probes = await Promise.all(this.request.names.map((name) => this.probeName(name)));
this.face.close();
return result;
}
/**
* @param {Name} name
* @returns {Promise<ProbeResult>}
*/
async probeName(name) {
try {
const t0 = getNow();
await this.endpoint.consume(name);
const t1 = getNow();
return {
ok: true,
rtt: t1 - t0,
};
} catch (err) {
return {
ok: false,
error: `${err}`,
};
}
}
/**
* Open the face.
* @returns {Promise<import("@ndn/fw").FwFace>}
* @abstract
*/
async openFace() {
throw new Error("must override");
}
}
/** UDP transport probe. */
export class UdpProbe extends Probe {
/** @override */
async openFace() {
return UdpTransport.createFace({
fw: this.fw,
}, {
family: this.request.family,
...splitHostPort(this.request.router),
});
}
}
/** WebSocket transport probe. */
export class WsProbe extends Probe {
/** @override */
async openFace() {
const ws = new WebSocket(this.request.router, {
family: this.request.family,
});
return WsTransport.createFace({
fw: this.fw,
}, ws);
}
}