@push.rocks/smartnetwork 3.0.2 → 4.0.1
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 +248 -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 +120 -67
- package/ts/smartnetwork.classes.smartnetwork.ts +278 -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
|
-
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
|
23
|
-
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
|
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) => console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`));
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file.
|
|
25
23
|
|
|
26
24
|
## Usage
|
|
27
25
|
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
### Basic Setup
|
|
29
|
+
|
|
30
|
+
First, import the package into your project:
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { SmartNetwork } from '@push.rocks/smartnetwork';
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Then, create an instance of `SmartNetwork`:
|
|
37
|
+
|
|
28
38
|
```typescript
|
|
29
|
-
|
|
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);
|
|
39
|
+
const myNetwork = new SmartNetwork();
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Performing a Speed Test
|
|
35
43
|
|
|
36
|
-
|
|
37
|
-
const isLocalPortUnused: boolean = await testSmartNetwork.isLocalPortUnused(1234);
|
|
44
|
+
You can measure the network speed using the `getSpeed` method. It supports optional parameters:
|
|
38
45
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
'google.com:80'
|
|
42
|
-
);
|
|
46
|
+
- `parallelStreams`: number of concurrent streams (default: 1)
|
|
47
|
+
- `duration`: test duration in seconds (default: fixed segments)
|
|
43
48
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
);
|
|
49
|
+
```typescript
|
|
50
|
+
const speedTest = async () => {
|
|
51
|
+
// Default fixed-segment test
|
|
52
|
+
let r = await myNetwork.getSpeed();
|
|
53
|
+
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
|
|
54
|
+
|
|
55
|
+
// Parallel + duration-based test
|
|
56
|
+
r = await myNetwork.getSpeed({ parallelStreams: 3, duration: 5 });
|
|
57
|
+
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
|
|
49
58
|
};
|
|
59
|
+
|
|
60
|
+
speedTest();
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Checking Port Availability Locally
|
|
64
|
+
|
|
65
|
+
The `isLocalPortUnused` method allows you to check if a specific port on your local machine is available for use.
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
const checkLocalPort = async (port: number) => {
|
|
69
|
+
const isUnused = await myNetwork.isLocalPortUnused(port);
|
|
70
|
+
if (isUnused) {
|
|
71
|
+
console.log(`Port ${port} is available.`);
|
|
72
|
+
} else {
|
|
73
|
+
console.log(`Port ${port} is in use.`);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
checkLocalPort(8080); // Example port number
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Checking Remote Port Availability
|
|
81
|
+
|
|
82
|
+
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.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
// Using "host:port"
|
|
86
|
+
await myNetwork.isRemotePortAvailable('example.com:443');
|
|
87
|
+
|
|
88
|
+
// Using host + port
|
|
89
|
+
await myNetwork.isRemotePortAvailable('example.com', 443);
|
|
90
|
+
|
|
91
|
+
// UDP is not supported:
|
|
92
|
+
try {
|
|
93
|
+
await myNetwork.isRemotePortAvailable('example.com', { port: 53, protocol: 'udp' });
|
|
94
|
+
} catch (e) {
|
|
95
|
+
console.error((e as any).code); // ENOTSUP
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Using Ping
|
|
100
|
+
|
|
101
|
+
The `ping` method sends ICMP echo requests and optionally repeats them to collect statistics.
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// Single ping
|
|
105
|
+
const p1 = await myNetwork.ping('google.com');
|
|
106
|
+
console.log(`Alive: ${p1.alive}, RTT: ${p1.time} ms`);
|
|
107
|
+
|
|
108
|
+
// Multiple pings with statistics
|
|
109
|
+
const stats = await myNetwork.ping('google.com', { count: 5 });
|
|
110
|
+
console.log(
|
|
111
|
+
`min=${stats.min} ms, max=${stats.max} ms, avg=${stats.avg.toFixed(2)} ms, loss=${stats.packetLoss}%`,
|
|
112
|
+
);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Getting Network Gateways
|
|
116
|
+
|
|
117
|
+
You can also retrieve network interfaces (gateways) and determine the default gateway. Caching with TTL is supported via constructor options.
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
// Create with cache TTL of 60 seconds
|
|
121
|
+
const netCached = new SmartNetwork({ cacheTtl: 60000 });
|
|
122
|
+
|
|
123
|
+
// List all interfaces
|
|
124
|
+
const gateways = await netCached.getGateways();
|
|
125
|
+
console.log(gateways);
|
|
126
|
+
|
|
127
|
+
// Get default gateway
|
|
128
|
+
const defaultGw = await netCached.getDefaultGateway();
|
|
129
|
+
console.log(defaultGw);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Discovering Public IP Addresses
|
|
133
|
+
|
|
134
|
+
To find out your public IPv4 and IPv6 addresses (with caching):
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
const publicIps = await netCached.getPublicIps();
|
|
138
|
+
console.log(`Public IPv4: ${publicIps.v4}`);
|
|
139
|
+
console.log(`Public IPv6: ${publicIps.v6}`);
|
|
50
140
|
```
|
|
51
141
|
|
|
52
|
-
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
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.
|
|
145
|
+
|
|
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.1',
|
|
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,17 @@ export class CloudflareSpeed {
|
|
|
104
164
|
}
|
|
105
165
|
|
|
106
166
|
public async fetchServerLocations(): Promise<{ [key: string]: string }> {
|
|
107
|
-
const res = JSON.parse(await this.get('speed.cloudflare.com', '/locations'))
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
167
|
+
const res = JSON.parse(await this.get('speed.cloudflare.com', '/locations')) as Array<{
|
|
168
|
+
iata: string;
|
|
169
|
+
city: string;
|
|
170
|
+
}>;
|
|
171
|
+
return res.reduce(
|
|
172
|
+
(data: Record<string, string>, optionsArg) => {
|
|
173
|
+
data[optionsArg.iata] = optionsArg.city;
|
|
174
|
+
return data;
|
|
175
|
+
},
|
|
176
|
+
{} as Record<string, string>,
|
|
177
|
+
);
|
|
116
178
|
}
|
|
117
179
|
|
|
118
180
|
public async get(hostname: string, path: string): Promise<string> {
|
|
@@ -122,6 +184,8 @@ export class CloudflareSpeed {
|
|
|
122
184
|
hostname,
|
|
123
185
|
path,
|
|
124
186
|
method: 'GET',
|
|
187
|
+
// disable connection pooling to avoid listener accumulation
|
|
188
|
+
agent: false,
|
|
125
189
|
},
|
|
126
190
|
(res) => {
|
|
127
191
|
const body: Array<Buffer> = [];
|
|
@@ -135,10 +199,10 @@ export class CloudflareSpeed {
|
|
|
135
199
|
reject(e);
|
|
136
200
|
}
|
|
137
201
|
});
|
|
138
|
-
req.on('error', (err) => {
|
|
139
|
-
reject(err);
|
|
202
|
+
req.on('error', (err: Error & { code?: string }) => {
|
|
203
|
+
reject(new NetworkError(err.message, err.code));
|
|
140
204
|
});
|
|
141
|
-
}
|
|
205
|
+
},
|
|
142
206
|
);
|
|
143
207
|
|
|
144
208
|
req.end();
|
|
@@ -179,7 +243,9 @@ export class CloudflareSpeed {
|
|
|
179
243
|
|
|
180
244
|
return new Promise((resolve, reject) => {
|
|
181
245
|
started = plugins.perfHooks.performance.now();
|
|
182
|
-
|
|
246
|
+
// disable connection pooling to avoid listener accumulation across requests
|
|
247
|
+
const reqOptions = { ...options, agent: false };
|
|
248
|
+
const req = plugins.https.request(reqOptions, (res) => {
|
|
183
249
|
res.once('readable', () => {
|
|
184
250
|
ttfb = plugins.perfHooks.performance.now();
|
|
185
251
|
});
|
|
@@ -193,25 +259,26 @@ export class CloudflareSpeed {
|
|
|
193
259
|
sslHandshake,
|
|
194
260
|
ttfb,
|
|
195
261
|
ended,
|
|
196
|
-
parseFloat(res.headers['server-timing'].slice(22)
|
|
262
|
+
parseFloat((res.headers['server-timing'] as string).slice(22)),
|
|
197
263
|
]);
|
|
198
264
|
});
|
|
199
265
|
});
|
|
200
266
|
|
|
201
|
-
|
|
202
|
-
|
|
267
|
+
// Listen for timing events once per new socket
|
|
268
|
+
req.once('socket', (socket) => {
|
|
269
|
+
socket.once('lookup', () => {
|
|
203
270
|
dnsLookup = plugins.perfHooks.performance.now();
|
|
204
271
|
});
|
|
205
|
-
socket.
|
|
272
|
+
socket.once('connect', () => {
|
|
206
273
|
tcpHandshake = plugins.perfHooks.performance.now();
|
|
207
274
|
});
|
|
208
|
-
socket.
|
|
275
|
+
socket.once('secureConnect', () => {
|
|
209
276
|
sslHandshake = plugins.perfHooks.performance.now();
|
|
210
277
|
});
|
|
211
278
|
});
|
|
212
279
|
|
|
213
|
-
req.on('error', (error) => {
|
|
214
|
-
reject(error);
|
|
280
|
+
req.on('error', (error: Error & { code?: string }) => {
|
|
281
|
+
reject(new NetworkError(error.message, error.code));
|
|
215
282
|
});
|
|
216
283
|
|
|
217
284
|
req.write(data);
|
|
@@ -219,39 +286,25 @@ export class CloudflareSpeed {
|
|
|
219
286
|
});
|
|
220
287
|
}
|
|
221
288
|
|
|
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
|
-
}> {
|
|
289
|
+
/**
|
|
290
|
+
* Fetch Cloudflare's trace endpoint and parse key=value lines to a record.
|
|
291
|
+
*/
|
|
292
|
+
public async fetchCfCdnCgiTrace(): Promise<Record<string, string>> {
|
|
237
293
|
const parseCfCdnCgiTrace = (text: string) =>
|
|
238
294
|
text
|
|
239
295
|
.split('\n')
|
|
240
296
|
.map((i) => {
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
return [j[0], j[1]];
|
|
297
|
+
const parts = i.split('=');
|
|
298
|
+
return [parts[0], parts[1]];
|
|
244
299
|
})
|
|
245
|
-
.reduce(
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
return data1;
|
|
254
|
-
}, {});
|
|
300
|
+
.reduce(
|
|
301
|
+
(data: Record<string, string>, [k, v]) => {
|
|
302
|
+
if (v === undefined) return data;
|
|
303
|
+
data[k] = v;
|
|
304
|
+
return data;
|
|
305
|
+
},
|
|
306
|
+
{} as Record<string, string>,
|
|
307
|
+
);
|
|
255
308
|
|
|
256
309
|
return this.get('speed.cloudflare.com', '/cdn-cgi/trace').then(parseCfCdnCgiTrace);
|
|
257
310
|
}
|