@push.rocks/smartnetwork 3.0.2 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist_ts/00_commitinfo_data.d.ts +1 -1
- package/dist_ts/00_commitinfo_data.js +5 -5
- package/dist_ts/errors.d.ts +10 -0
- package/dist_ts/errors.js +19 -0
- package/dist_ts/helpers/stats.js +1 -1
- package/dist_ts/index.d.ts +3 -0
- package/dist_ts/index.js +3 -1
- package/dist_ts/logging.d.ts +22 -0
- package/dist_ts/logging.js +15 -0
- package/dist_ts/smartnetwork.classes.cloudflarespeed.d.ts +10 -17
- package/dist_ts/smartnetwork.classes.cloudflarespeed.js +93 -35
- package/dist_ts/smartnetwork.classes.smartnetwork.d.ts +97 -9
- package/dist_ts/smartnetwork.classes.smartnetwork.js +250 -55
- package/dist_ts/smartnetwork.plugins.d.ts +3 -3
- package/dist_ts/smartnetwork.plugins.js +4 -4
- package/npmextra.json +20 -5
- package/package.json +39 -18
- package/readme.hints.md +1 -0
- package/readme.md +167 -45
- package/ts/00_commitinfo_data.ts +4 -4
- package/ts/errors.ts +20 -0
- package/ts/index.ts +3 -0
- package/ts/logging.ts +30 -0
- package/ts/smartnetwork.classes.cloudflarespeed.ts +124 -75
- package/ts/smartnetwork.classes.smartnetwork.ts +287 -54
- package/ts/smartnetwork.plugins.ts +3 -3
package/readme.md
CHANGED
|
@@ -1,61 +1,183 @@
|
|
|
1
|
-
# @
|
|
1
|
+
# @push.rocks/smartnetwork
|
|
2
|
+
|
|
2
3
|
network diagnostics
|
|
3
4
|
|
|
4
|
-
##
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
Platform support | [](https://lossless.cloud) [](https://lossless.cloud)
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
To install `@push.rocks/smartnetwork`, run the following command in your terminal:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @push.rocks/smartnetwork --save
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
### Performing a Traceroute
|
|
14
|
+
|
|
15
|
+
You can perform a hop-by-hop traceroute to measure latency per hop. Falls back to a single-hop stub if the `traceroute` binary is unavailable.
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
const hops = await myNetwork.traceroute('google.com', { maxHops: 10, timeout: 5000 });
|
|
19
|
+
hops.forEach(h =>
|
|
20
|
+
console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`),
|
|
21
|
+
);
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file.
|
|
25
25
|
|
|
26
26
|
## Usage
|
|
27
27
|
|
|
28
|
+
In this section, we will dive deep into the capabilities of the `@push.rocks/smartnetwork` package, exploring its various features through TypeScript examples. The package is designed to simplify network diagnostics tasks, including speed tests, port availability checks, ping operations, and more.
|
|
29
|
+
|
|
30
|
+
### Basic Setup
|
|
31
|
+
|
|
32
|
+
First, import the package into your project:
|
|
33
|
+
|
|
28
34
|
```typescript
|
|
29
|
-
import
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
// the structure of speedResult is self explanatory using TypeScript (or the linked TypeDoc above)
|
|
34
|
-
const speedResult: smartnetwork.SpeedResult = testSmartNetwork.getSpeed(5000);
|
|
35
|
+
import { SmartNetwork } from '@push.rocks/smartnetwork';
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Then, create an instance of `SmartNetwork`:
|
|
35
39
|
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
```typescript
|
|
41
|
+
const myNetwork = new SmartNetwork();
|
|
42
|
+
```
|
|
38
43
|
|
|
39
|
-
|
|
40
|
-
const isRemotePortAvailable: boolean = await testSmartNetwork.isRemotePortAvailable(
|
|
41
|
-
'google.com:80'
|
|
42
|
-
);
|
|
44
|
+
### Performing a Speed Test
|
|
43
45
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
46
|
+
You can measure the network speed using the `getSpeed` method. It supports optional parameters:
|
|
47
|
+
- `parallelStreams`: number of concurrent streams (default: 1)
|
|
48
|
+
- `duration`: test duration in seconds (default: fixed segments)
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
const speedTest = async () => {
|
|
52
|
+
// Default fixed-segment test
|
|
53
|
+
let r = await myNetwork.getSpeed();
|
|
54
|
+
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
|
|
55
|
+
|
|
56
|
+
// Parallel + duration-based test
|
|
57
|
+
r = await myNetwork.getSpeed({ parallelStreams: 3, duration: 5 });
|
|
58
|
+
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
speedTest();
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Checking Port Availability Locally
|
|
65
|
+
|
|
66
|
+
The `isLocalPortUnused` method allows you to check if a specific port on your local machine is available for use.
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
const checkLocalPort = async (port: number) => {
|
|
70
|
+
const isUnused = await myNetwork.isLocalPortUnused(port);
|
|
71
|
+
if (isUnused) {
|
|
72
|
+
console.log(`Port ${port} is available.`);
|
|
73
|
+
} else {
|
|
74
|
+
console.log(`Port ${port} is in use.`);
|
|
75
|
+
}
|
|
49
76
|
};
|
|
77
|
+
|
|
78
|
+
checkLocalPort(8080); // Example port number
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Checking Remote Port Availability
|
|
82
|
+
|
|
83
|
+
To verify if a port is available on a remote server, use `isRemotePortAvailable`. You can specify target as `"host:port"` or host plus a numeric port.
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
// Using "host:port"
|
|
87
|
+
await myNetwork.isRemotePortAvailable('example.com:443');
|
|
88
|
+
|
|
89
|
+
// Using host + port
|
|
90
|
+
await myNetwork.isRemotePortAvailable('example.com', 443);
|
|
91
|
+
|
|
92
|
+
// UDP is not supported:
|
|
93
|
+
try {
|
|
94
|
+
await myNetwork.isRemotePortAvailable('example.com', { port: 53, protocol: 'udp' });
|
|
95
|
+
} catch (e) {
|
|
96
|
+
console.error((e as any).code); // ENOTSUP
|
|
97
|
+
}
|
|
50
98
|
```
|
|
51
99
|
|
|
52
|
-
|
|
100
|
+
### Using Ping
|
|
101
|
+
|
|
102
|
+
The `ping` method sends ICMP echo requests and optionally repeats them to collect statistics.
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
// Single ping
|
|
106
|
+
const p1 = await myNetwork.ping('google.com');
|
|
107
|
+
console.log(`Alive: ${p1.alive}, RTT: ${p1.time} ms`);
|
|
108
|
+
|
|
109
|
+
// Multiple pings with statistics
|
|
110
|
+
const stats = await myNetwork.ping('google.com', { count: 5 });
|
|
111
|
+
console.log(
|
|
112
|
+
`min=${stats.min} ms, max=${stats.max} ms, avg=${stats.avg.toFixed(2)} ms, loss=${stats.packetLoss}%`,
|
|
113
|
+
);
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Getting Network Gateways
|
|
117
|
+
|
|
118
|
+
You can also retrieve network interfaces (gateways) and determine the default gateway. Caching with TTL is supported via constructor options.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
// Create with cache TTL of 60 seconds
|
|
122
|
+
const netCached = new SmartNetwork({ cacheTtl: 60000 });
|
|
123
|
+
|
|
124
|
+
// List all interfaces
|
|
125
|
+
const gateways = await netCached.getGateways();
|
|
126
|
+
console.log(gateways);
|
|
127
|
+
|
|
128
|
+
// Get default gateway
|
|
129
|
+
const defaultGw = await netCached.getDefaultGateway();
|
|
130
|
+
console.log(defaultGw);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Discovering Public IP Addresses
|
|
134
|
+
|
|
135
|
+
To find out your public IPv4 and IPv6 addresses (with caching):
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
const publicIps = await netCached.getPublicIps();
|
|
139
|
+
console.log(`Public IPv4: ${publicIps.v4}`);
|
|
140
|
+
console.log(`Public IPv6: ${publicIps.v6}`);
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The `@push.rocks/smartnetwork` package provides an easy-to-use, comprehensive suite of tools for network diagnostics and monitoring, encapsulating complex network operations into simple asynchronous methods. By leveraging TypeScript, developers can benefit from type checking, ensuring that they can work with clear structures and expectations.
|
|
144
|
+
|
|
145
|
+
These examples offer a glimpse into the module's utility in real-world scenarios, demonstrating its versatility in handling common network tasks. Whether you're developing a network-sensitive application, diagnosing connectivity issues, or simply curious about your network performance, `@push.rocks/smartnetwork` equips you with the tools you need.
|
|
146
|
+
### Plugin Architecture
|
|
147
|
+
|
|
148
|
+
You can extend `SmartNetwork` with custom plugins by registering them at runtime:
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
import { SmartNetwork } from '@push.rocks/smartnetwork';
|
|
152
|
+
|
|
153
|
+
// Define your plugin class or constructor
|
|
154
|
+
class MyCustomPlugin {
|
|
155
|
+
// plugin implementation goes here
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Register and unregister your plugin by name
|
|
159
|
+
SmartNetwork.registerPlugin('myPlugin', MyCustomPlugin);
|
|
160
|
+
// Later, remove it if no longer needed
|
|
161
|
+
SmartNetwork.unregisterPlugin('myPlugin');
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Plugins enable you to dynamically augment the core functionality without altering the library's source.
|
|
165
|
+
|
|
166
|
+
## License and Legal Information
|
|
167
|
+
|
|
168
|
+
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|
169
|
+
|
|
170
|
+
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|
171
|
+
|
|
172
|
+
### Trademarks
|
|
173
|
+
|
|
174
|
+
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
|
53
175
|
|
|
54
|
-
|
|
176
|
+
### Company Information
|
|
55
177
|
|
|
56
|
-
|
|
178
|
+
Task Venture Capital GmbH
|
|
179
|
+
Registered at District court Bremen HRB 35230 HB, Germany
|
|
57
180
|
|
|
58
|
-
|
|
59
|
-
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
|
181
|
+
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
|
60
182
|
|
|
61
|
-
|
|
183
|
+
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
package/ts/00_commitinfo_data.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* autocreated commitinfo by @
|
|
2
|
+
* autocreated commitinfo by @push.rocks/commitinfo
|
|
3
3
|
*/
|
|
4
4
|
export const commitinfo = {
|
|
5
|
-
name: '@
|
|
6
|
-
version: '
|
|
7
|
-
description: 'network diagnostics'
|
|
5
|
+
name: '@push.rocks/smartnetwork',
|
|
6
|
+
version: '4.0.0',
|
|
7
|
+
description: 'A toolkit for network diagnostics including speed tests, port availability checks, and more.'
|
|
8
8
|
}
|
package/ts/errors.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom error classes for network operations
|
|
3
|
+
*/
|
|
4
|
+
export class NetworkError extends Error {
|
|
5
|
+
public code?: string;
|
|
6
|
+
constructor(message?: string, code?: string) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'NetworkError';
|
|
9
|
+
this.code = code;
|
|
10
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class TimeoutError extends NetworkError {
|
|
15
|
+
constructor(message?: string) {
|
|
16
|
+
super(message, 'ETIMEOUT');
|
|
17
|
+
this.name = 'TimeoutError';
|
|
18
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
19
|
+
}
|
|
20
|
+
}
|
package/ts/index.ts
CHANGED
package/ts/logging.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Injectable logging interface and global logger
|
|
3
|
+
*/
|
|
4
|
+
export interface Logger {
|
|
5
|
+
/** Debug-level messages */
|
|
6
|
+
debug?(...args: unknown[]): void;
|
|
7
|
+
/** Informational messages */
|
|
8
|
+
info(...args: unknown[]): void;
|
|
9
|
+
/** Warning messages */
|
|
10
|
+
warn?(...args: unknown[]): void;
|
|
11
|
+
/** Error messages */
|
|
12
|
+
error(...args: unknown[]): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
let globalLogger: Logger = console;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Replace the global logger implementation
|
|
19
|
+
* @param logger Custom logger adhering to Logger interface
|
|
20
|
+
*/
|
|
21
|
+
export function setLogger(logger: Logger): void {
|
|
22
|
+
globalLogger = logger;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Retrieve the current global logger
|
|
27
|
+
*/
|
|
28
|
+
export function getLogger(): Logger {
|
|
29
|
+
return globalLogger;
|
|
30
|
+
}
|
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import * as plugins from './smartnetwork.plugins.js';
|
|
2
|
+
import { getLogger } from './logging.js';
|
|
3
|
+
import { NetworkError, TimeoutError } from './errors.js';
|
|
2
4
|
import * as stats from './helpers/stats.js';
|
|
3
5
|
|
|
6
|
+
export interface SpeedOptions {
|
|
7
|
+
parallelStreams?: number;
|
|
8
|
+
duration?: number;
|
|
9
|
+
}
|
|
4
10
|
export class CloudflareSpeed {
|
|
5
|
-
|
|
11
|
+
private opts: SpeedOptions;
|
|
12
|
+
constructor(opts?: SpeedOptions) {
|
|
13
|
+
this.opts = opts || {};
|
|
14
|
+
}
|
|
6
15
|
|
|
7
16
|
public async speedTest() {
|
|
8
17
|
const latency = await this.measureLatency();
|
|
@@ -10,20 +19,71 @@ export class CloudflareSpeed {
|
|
|
10
19
|
const serverLocations = await this.fetchServerLocations();
|
|
11
20
|
const cgiData = await this.fetchCfCdnCgiTrace();
|
|
12
21
|
|
|
13
|
-
//
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
22
|
+
// speed tests: either fixed segments or duration-based mode
|
|
23
|
+
const parallel = this.opts.parallelStreams ?? 1;
|
|
24
|
+
const measureDownloadParallel = (bytes: number, iterations: number) => {
|
|
25
|
+
if (parallel <= 1) {
|
|
26
|
+
return this.measureDownload(bytes, iterations);
|
|
27
|
+
}
|
|
28
|
+
return Promise.all(
|
|
29
|
+
Array(parallel)
|
|
30
|
+
.fill(null)
|
|
31
|
+
.map(() => this.measureDownload(bytes, iterations)),
|
|
32
|
+
).then((arrays) => arrays.flat());
|
|
33
|
+
};
|
|
34
|
+
let downloadTests: number[];
|
|
35
|
+
if (this.opts.duration && this.opts.duration > 0) {
|
|
36
|
+
// duration-based download: run for specified seconds
|
|
37
|
+
downloadTests = [];
|
|
38
|
+
const durMs = this.opts.duration * 1000;
|
|
39
|
+
const startMs = Date.now();
|
|
40
|
+
// use medium chunk size for download
|
|
41
|
+
const chunkBytes = 25001000;
|
|
42
|
+
while (Date.now() - startMs < durMs) {
|
|
43
|
+
const speeds = await measureDownloadParallel(chunkBytes, 1);
|
|
44
|
+
downloadTests.push(...speeds);
|
|
45
|
+
}
|
|
46
|
+
if (downloadTests.length === 0) downloadTests = [0];
|
|
47
|
+
} else {
|
|
48
|
+
// fixed download segments
|
|
49
|
+
const t1 = await measureDownloadParallel(101000, 10);
|
|
50
|
+
const t2 = await measureDownloadParallel(1001000, 8);
|
|
51
|
+
const t3 = await measureDownloadParallel(10001000, 6);
|
|
52
|
+
const t4 = await measureDownloadParallel(25001000, 4);
|
|
53
|
+
const t5 = await measureDownloadParallel(100001000, 1);
|
|
54
|
+
downloadTests = [...t1, ...t2, ...t3, ...t4, ...t5];
|
|
55
|
+
}
|
|
20
56
|
const speedDownload = stats.quartile(downloadTests, 0.9).toFixed(2);
|
|
21
57
|
|
|
22
|
-
// lets test the upload speed
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
58
|
+
// lets test the upload speed with configurable parallel streams
|
|
59
|
+
const measureUploadParallel = (bytes: number, iterations: number) => {
|
|
60
|
+
if (parallel <= 1) {
|
|
61
|
+
return this.measureUpload(bytes, iterations);
|
|
62
|
+
}
|
|
63
|
+
return Promise.all(
|
|
64
|
+
Array(parallel)
|
|
65
|
+
.fill(null)
|
|
66
|
+
.map(() => this.measureUpload(bytes, iterations)),
|
|
67
|
+
).then((arrays) => arrays.flat());
|
|
68
|
+
};
|
|
69
|
+
let uploadTests: number[];
|
|
70
|
+
if (this.opts.duration && this.opts.duration > 0) {
|
|
71
|
+
// duration-based upload: run for specified seconds
|
|
72
|
+
uploadTests = [];
|
|
73
|
+
const durMsUp = this.opts.duration * 1000;
|
|
74
|
+
const startMsUp = Date.now();
|
|
75
|
+
const chunkBytesUp = 1001000;
|
|
76
|
+
while (Date.now() - startMsUp < durMsUp) {
|
|
77
|
+
const speeds = await measureUploadParallel(chunkBytesUp, 1);
|
|
78
|
+
uploadTests.push(...speeds);
|
|
79
|
+
}
|
|
80
|
+
if (uploadTests.length === 0) uploadTests = [0];
|
|
81
|
+
} else {
|
|
82
|
+
const u1 = await measureUploadParallel(11000, 10);
|
|
83
|
+
const u2 = await measureUploadParallel(101000, 10);
|
|
84
|
+
const u3 = await measureUploadParallel(1001000, 8);
|
|
85
|
+
uploadTests = [...u1, ...u2, ...u3];
|
|
86
|
+
}
|
|
27
87
|
const speedUpload = stats.quartile(uploadTests, 0.9).toFixed(2);
|
|
28
88
|
|
|
29
89
|
return {
|
|
@@ -49,8 +109,8 @@ export class CloudflareSpeed {
|
|
|
49
109
|
measurements.push(response[4] - response[0] - response[6]);
|
|
50
110
|
},
|
|
51
111
|
(error) => {
|
|
52
|
-
|
|
53
|
-
}
|
|
112
|
+
getLogger().error('Error measuring latency:', error);
|
|
113
|
+
},
|
|
54
114
|
);
|
|
55
115
|
}
|
|
56
116
|
|
|
@@ -73,8 +133,8 @@ export class CloudflareSpeed {
|
|
|
73
133
|
measurements.push(await this.measureSpeed(bytes, transferTime));
|
|
74
134
|
},
|
|
75
135
|
(error) => {
|
|
76
|
-
|
|
77
|
-
}
|
|
136
|
+
getLogger().error('Error measuring download chunk:', error);
|
|
137
|
+
},
|
|
78
138
|
);
|
|
79
139
|
}
|
|
80
140
|
|
|
@@ -91,8 +151,8 @@ export class CloudflareSpeed {
|
|
|
91
151
|
measurements.push(await this.measureSpeed(bytes, transferTime));
|
|
92
152
|
},
|
|
93
153
|
(error) => {
|
|
94
|
-
|
|
95
|
-
}
|
|
154
|
+
getLogger().error('Error measuring upload chunk:', error);
|
|
155
|
+
},
|
|
96
156
|
);
|
|
97
157
|
}
|
|
98
158
|
|
|
@@ -104,15 +164,16 @@ export class CloudflareSpeed {
|
|
|
104
164
|
}
|
|
105
165
|
|
|
106
166
|
public async fetchServerLocations(): Promise<{ [key: string]: string }> {
|
|
107
|
-
const res = JSON.parse(
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
167
|
+
const res = JSON.parse(
|
|
168
|
+
await this.get('speed.cloudflare.com', '/locations'),
|
|
169
|
+
) as Array<{ iata: string; city: string }>;
|
|
170
|
+
return res.reduce(
|
|
171
|
+
(data: Record<string, string>, optionsArg) => {
|
|
172
|
+
data[optionsArg.iata] = optionsArg.city;
|
|
173
|
+
return data;
|
|
174
|
+
},
|
|
175
|
+
{} as Record<string, string>,
|
|
176
|
+
);
|
|
116
177
|
}
|
|
117
178
|
|
|
118
179
|
public async get(hostname: string, path: string): Promise<string> {
|
|
@@ -122,6 +183,8 @@ export class CloudflareSpeed {
|
|
|
122
183
|
hostname,
|
|
123
184
|
path,
|
|
124
185
|
method: 'GET',
|
|
186
|
+
// disable connection pooling to avoid listener accumulation
|
|
187
|
+
agent: false,
|
|
125
188
|
},
|
|
126
189
|
(res) => {
|
|
127
190
|
const body: Array<Buffer> = [];
|
|
@@ -135,10 +198,10 @@ export class CloudflareSpeed {
|
|
|
135
198
|
reject(e);
|
|
136
199
|
}
|
|
137
200
|
});
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
201
|
+
req.on('error', (err: Error & { code?: string }) => {
|
|
202
|
+
reject(new NetworkError(err.message, err.code));
|
|
203
|
+
});
|
|
204
|
+
},
|
|
142
205
|
);
|
|
143
206
|
|
|
144
207
|
req.end();
|
|
@@ -179,39 +242,42 @@ export class CloudflareSpeed {
|
|
|
179
242
|
|
|
180
243
|
return new Promise((resolve, reject) => {
|
|
181
244
|
started = plugins.perfHooks.performance.now();
|
|
182
|
-
|
|
245
|
+
// disable connection pooling to avoid listener accumulation across requests
|
|
246
|
+
const reqOptions = { ...options, agent: false };
|
|
247
|
+
const req = plugins.https.request(reqOptions, (res) => {
|
|
183
248
|
res.once('readable', () => {
|
|
184
249
|
ttfb = plugins.perfHooks.performance.now();
|
|
185
250
|
});
|
|
186
251
|
res.on('data', () => {});
|
|
187
252
|
res.on('end', () => {
|
|
188
253
|
ended = plugins.perfHooks.performance.now();
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
254
|
+
resolve([
|
|
255
|
+
started,
|
|
256
|
+
dnsLookup,
|
|
257
|
+
tcpHandshake,
|
|
258
|
+
sslHandshake,
|
|
259
|
+
ttfb,
|
|
260
|
+
ended,
|
|
261
|
+
parseFloat((res.headers['server-timing'] as string).slice(22)),
|
|
262
|
+
]);
|
|
198
263
|
});
|
|
199
264
|
});
|
|
200
265
|
|
|
201
|
-
|
|
202
|
-
|
|
266
|
+
// Listen for timing events once per new socket
|
|
267
|
+
req.once('socket', (socket) => {
|
|
268
|
+
socket.once('lookup', () => {
|
|
203
269
|
dnsLookup = plugins.perfHooks.performance.now();
|
|
204
270
|
});
|
|
205
|
-
socket.
|
|
271
|
+
socket.once('connect', () => {
|
|
206
272
|
tcpHandshake = plugins.perfHooks.performance.now();
|
|
207
273
|
});
|
|
208
|
-
socket.
|
|
274
|
+
socket.once('secureConnect', () => {
|
|
209
275
|
sslHandshake = plugins.perfHooks.performance.now();
|
|
210
276
|
});
|
|
211
277
|
});
|
|
212
278
|
|
|
213
|
-
req.on('error', (error) => {
|
|
214
|
-
reject(error);
|
|
279
|
+
req.on('error', (error: Error & { code?: string }) => {
|
|
280
|
+
reject(new NetworkError(error.message, error.code));
|
|
215
281
|
});
|
|
216
282
|
|
|
217
283
|
req.write(data);
|
|
@@ -219,39 +285,22 @@ export class CloudflareSpeed {
|
|
|
219
285
|
});
|
|
220
286
|
}
|
|
221
287
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
ts: string;
|
|
227
|
-
visit_scheme: string;
|
|
228
|
-
uag: string;
|
|
229
|
-
colo: string;
|
|
230
|
-
http: string;
|
|
231
|
-
loc: string;
|
|
232
|
-
tls: string;
|
|
233
|
-
sni: string;
|
|
234
|
-
warp: string;
|
|
235
|
-
gateway: string;
|
|
236
|
-
}> {
|
|
288
|
+
/**
|
|
289
|
+
* Fetch Cloudflare's trace endpoint and parse key=value lines to a record.
|
|
290
|
+
*/
|
|
291
|
+
public async fetchCfCdnCgiTrace(): Promise<Record<string, string>> {
|
|
237
292
|
const parseCfCdnCgiTrace = (text: string) =>
|
|
238
293
|
text
|
|
239
294
|
.split('\n')
|
|
240
295
|
.map((i) => {
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
return [j[0], j[1]];
|
|
296
|
+
const parts = i.split('=');
|
|
297
|
+
return [parts[0], parts[1]];
|
|
244
298
|
})
|
|
245
|
-
.reduce((data:
|
|
299
|
+
.reduce((data: Record<string, string>, [k, v]) => {
|
|
246
300
|
if (v === undefined) return data;
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
// Object.fromEntries is only supported by Node.js 12 or newer
|
|
251
|
-
data1[k] = v;
|
|
252
|
-
|
|
253
|
-
return data1;
|
|
254
|
-
}, {});
|
|
301
|
+
data[k] = v;
|
|
302
|
+
return data;
|
|
303
|
+
}, {} as Record<string, string>);
|
|
255
304
|
|
|
256
305
|
return this.get('speed.cloudflare.com', '/cdn-cgi/trace').then(parseCfCdnCgiTrace);
|
|
257
306
|
}
|