Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
fix: OOM on Chrome (#1)
Browse files* fix: OOM on Chrome
* fix: disable logging of bandwidth data in server.ts
* fix: use speedtest lib
---------
Co-authored-by: Hugo Larcher <[email protected]>
- src/lib/index.ts +19 -118
- src/routes/+page.svelte +90 -78
- src/routes/analytics/+server.ts +1 -1
- static/speedtest.js +379 -0
- static/speedtest_worker.js +724 -0
src/lib/index.ts
CHANGED
@@ -2,124 +2,6 @@
|
|
2 |
|
3 |
import { majorAirportIATAs } from '$lib/icao';
|
4 |
|
5 |
-
interface BandwidthCallback {
|
6 |
-
(
|
7 |
-
elapsedMs: number,
|
8 |
-
loadedBytes: number,
|
9 |
-
totalBytes: number,
|
10 |
-
bytesPerSecond: number,
|
11 |
-
done: boolean
|
12 |
-
): boolean;
|
13 |
-
}
|
14 |
-
|
15 |
-
export async function bandwidthTest(
|
16 |
-
onProgress: BandwidthCallback,
|
17 |
-
onLatency: (latency: number) => void,
|
18 |
-
onServerLocation: (location: string) => void
|
19 |
-
) {
|
20 |
-
// performance.setResourceTimingBufferSize(100);
|
21 |
-
// performance.clearResourceTimings();
|
22 |
-
const url = 'https://cdn-test-cloudfront.hf.co/5gb.safetensors';
|
23 |
-
// const url = 'https://cdn-test-cloudfront.hf.co/15mb.json';
|
24 |
-
|
25 |
-
// issue HEAD requests to estimate latency (round trip time), and average
|
26 |
-
let latencySum = 0;
|
27 |
-
const numLatencyTests = 5;
|
28 |
-
for (let i = 0; i < numLatencyTests; i++) {
|
29 |
-
const startTime = performance.now();
|
30 |
-
const response = await fetch(url, { method: 'HEAD' });
|
31 |
-
if (!response.ok) {
|
32 |
-
throw new Error(`Network response was not ok: ${response.status}`);
|
33 |
-
}
|
34 |
-
const latency = performance.now() - startTime;
|
35 |
-
latencySum += latency;
|
36 |
-
}
|
37 |
-
onLatency(latencySum / numLatencyTests);
|
38 |
-
|
39 |
-
const startTime = performance.now();
|
40 |
-
const response = await fetch(url);
|
41 |
-
if (!response.ok) {
|
42 |
-
throw new Error(`Network response was not ok: ${response.status}`);
|
43 |
-
}
|
44 |
-
// setTimeout(() => {
|
45 |
-
// const entries = performance.getEntriesByType('resource');
|
46 |
-
// const resourceEntry = entries.find((e) => e.name === url);
|
47 |
-
// if (!resourceEntry) {
|
48 |
-
// return
|
49 |
-
// }
|
50 |
-
// console.log(resourceEntry);
|
51 |
-
// const { requestStart, responseStart } = resourceEntry;
|
52 |
-
// const latency = responseStart - requestStart;
|
53 |
-
// onLatency(latency);
|
54 |
-
// }, 2000);
|
55 |
-
|
56 |
-
// extract content-length
|
57 |
-
const contentLengthHeader = response.headers.get('content-length');
|
58 |
-
const totalBytes = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 1e99;
|
59 |
-
|
60 |
-
// extract pop location
|
61 |
-
let cdnPop = response.headers.get('x-amz-cf-pop');
|
62 |
-
if (cdnPop !== null) {
|
63 |
-
cdnPop = cdnPop.toUpperCase().slice(0, 3);
|
64 |
-
// try to map to IATA
|
65 |
-
if (cdnPop in majorAirportIATAs) {
|
66 |
-
cdnPop = majorAirportIATAs[cdnPop].city + ', ' + majorAirportIATAs[cdnPop].country;
|
67 |
-
} else {
|
68 |
-
cdnPop = 'Unknown';
|
69 |
-
}
|
70 |
-
} else {
|
71 |
-
cdnPop = 'Unknown';
|
72 |
-
}
|
73 |
-
onServerLocation(cdnPop);
|
74 |
-
|
75 |
-
const reader = response.body.getReader();
|
76 |
-
let loadedBytes = 0;
|
77 |
-
let lastTimestamp = performance.now();
|
78 |
-
let lastLoaded = 0;
|
79 |
-
const REPORT_INTERVAL_MS = 500;
|
80 |
-
onProgress(0, loadedBytes, totalBytes, 0, false);
|
81 |
-
let bytesPerSecond = 0;
|
82 |
-
while (true) {
|
83 |
-
const { done, value } = await reader.read();
|
84 |
-
if (done) {
|
85 |
-
// stream is finished
|
86 |
-
const elapsedMs = performance.now() - startTime;
|
87 |
-
onProgress(elapsedMs, loadedBytes, totalBytes, bytesPerSecond, true);
|
88 |
-
// send analytics data
|
89 |
-
await sendAnalyticsData(bytesPerSecond, latencySum / numLatencyTests, cdnPop, 1.);
|
90 |
-
break;
|
91 |
-
}
|
92 |
-
|
93 |
-
// `value` is a Uint8Array for this chunk
|
94 |
-
loadedBytes += value.byteLength;
|
95 |
-
|
96 |
-
// Current time
|
97 |
-
const now = performance.now();
|
98 |
-
const deltaMs = now - lastTimestamp;
|
99 |
-
|
100 |
-
if (deltaMs >= REPORT_INTERVAL_MS) {
|
101 |
-
// compute bytes downloaded since last report
|
102 |
-
const deltaBytes = loadedBytes - lastLoaded;
|
103 |
-
// convert ms to seconds
|
104 |
-
const deltaSeconds = deltaMs / 1000;
|
105 |
-
bytesPerSecond = deltaBytes / deltaSeconds;
|
106 |
-
|
107 |
-
// Invoke callback
|
108 |
-
const elapsedMs = performance.now() - startTime;
|
109 |
-
const stop = onProgress(elapsedMs, loadedBytes, totalBytes, bytesPerSecond, false);
|
110 |
-
if (stop) {
|
111 |
-
// stop the test
|
112 |
-
console.log(`Stopping bandwidth test at ${loadedBytes} bytes after ${elapsedMs} ms`);
|
113 |
-
break;
|
114 |
-
}
|
115 |
-
|
116 |
-
// Reset our “last” markers
|
117 |
-
lastLoaded = loadedBytes;
|
118 |
-
lastTimestamp = now;
|
119 |
-
}
|
120 |
-
}
|
121 |
-
}
|
122 |
-
|
123 |
interface ClientInfo {
|
124 |
clientIp: string;
|
125 |
clientLocation: string;
|
@@ -177,3 +59,22 @@ export async function sendAnalyticsData(bytesPerSecond: number, latency: number,
|
|
177 |
});
|
178 |
});
|
179 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
import { majorAirportIATAs } from '$lib/icao';
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
interface ClientInfo {
|
6 |
clientIp: string;
|
7 |
clientLocation: string;
|
|
|
59 |
});
|
60 |
});
|
61 |
}
|
62 |
+
|
63 |
+
export async function getServerLocation(url: string): Promise<string> {
|
64 |
+
// Get server location
|
65 |
+
const response = await fetch(url, { method: 'HEAD' });
|
66 |
+
let cdnPop = response.headers.get('x-amz-cf-pop');
|
67 |
+
if (cdnPop !== null) {
|
68 |
+
cdnPop = cdnPop.toUpperCase().slice(0, 3);
|
69 |
+
// try to map to IATA
|
70 |
+
if (cdnPop in majorAirportIATAs) {
|
71 |
+
cdnPop = majorAirportIATAs[cdnPop].city + ', ' + majorAirportIATAs[cdnPop].country;
|
72 |
+
} else {
|
73 |
+
cdnPop = 'Unknown';
|
74 |
+
}
|
75 |
+
} else {
|
76 |
+
cdnPop = 'Unknown';
|
77 |
+
}
|
78 |
+
|
79 |
+
return cdnPop;
|
80 |
+
}
|
src/routes/+page.svelte
CHANGED
@@ -1,16 +1,12 @@
|
|
1 |
<script lang="ts">
|
2 |
-
import {
|
3 |
import { Chart, registerables } from 'chart.js';
|
4 |
import type { Action } from 'svelte/action';
|
5 |
import { onMount } from 'svelte';
|
6 |
|
7 |
Chart.register(...registerables);
|
8 |
|
9 |
-
const MaxTestDurationSec = 20;
|
10 |
-
|
11 |
let currentBandwidth = $state(0);
|
12 |
-
let accumulatedBandwidth = 0;
|
13 |
-
let numBandwidthMeasurements = 0;
|
14 |
let currentLatency = $state(0);
|
15 |
let serverLocation = $state('-');
|
16 |
let clientIp = $state('Detecting...');
|
@@ -18,91 +14,103 @@
|
|
18 |
let progress = $state(0);
|
19 |
let bandwidthMeasurements: number[] = $state([]);
|
20 |
let timeMeasurements: string[] = $state([]);
|
21 |
-
let testStatus = $state('Idle');
|
|
|
|
|
|
|
22 |
|
23 |
// run ip info to get client IP and location
|
24 |
onMount(async () => {
|
25 |
-
let
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
});
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
totalBytes: number,
|
35 |
-
bw: number,
|
36 |
-
done: boolean
|
37 |
-
) => {
|
38 |
-
if (testStatus == 'Stopped' || testStatus == 'Completed') {
|
39 |
-
return true;
|
40 |
}
|
41 |
-
let mbps = (bw / 1000000) * 8; // convert Bps to Mbps
|
42 |
-
// update the accumulated bandwidth
|
43 |
-
accumulatedBandwidth += mbps;
|
44 |
-
numBandwidthMeasurements++;
|
45 |
-
// calculate the average bandwidth
|
46 |
-
if (numBandwidthMeasurements > 0) {
|
47 |
-
currentBandwidth = accumulatedBandwidth / numBandwidthMeasurements;
|
48 |
-
} else {
|
49 |
-
currentBandwidth = 0;
|
50 |
-
}
|
51 |
-
// update the bandwidth measurements array
|
52 |
-
bandwidthMeasurements.push(mbps); // convert Bps to Mbps
|
53 |
-
timeMeasurements.push((elapsedMs / 1000).toFixed(1)); // convert ms to seconds
|
54 |
-
// only keep the last 20 measurements
|
55 |
-
if (bandwidthMeasurements.length > 20) {
|
56 |
-
bandwidthMeasurements.shift();
|
57 |
-
timeMeasurements.shift();
|
58 |
-
}
|
59 |
-
// update the progress state. It is the max between the byte progress and the time progress
|
60 |
-
let timeProgress = (elapsedMs / (MaxTestDurationSec * 1000)) * 100;
|
61 |
-
let byteProgress = (loadedBytes / totalBytes) * 100;
|
62 |
-
progress = Math.max(timeProgress, byteProgress);
|
63 |
-
if (done) {
|
64 |
-
testStatus = 'Completed';
|
65 |
-
progress = 100;
|
66 |
-
} else {
|
67 |
-
testStatus = 'Running';
|
68 |
-
}
|
69 |
-
return false;
|
70 |
-
};
|
71 |
-
let latencyCallback = (latency: number) => {
|
72 |
-
// update the latency state
|
73 |
-
currentLatency = latency;
|
74 |
-
};
|
75 |
-
let serverLocationCallback = (location: string) => {
|
76 |
-
serverLocation = location;
|
77 |
-
};
|
78 |
-
|
79 |
-
let testTimeoutHandler = 0;
|
80 |
-
let earlyAnalyticsHandler = 0;
|
81 |
|
82 |
-
const startTest = () => {
|
83 |
-
testStatus = 'Running';
|
84 |
progress = 0;
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
currentLatency = 0;
|
89 |
-
bandwidthTest(bandwidthCallback, latencyCallback, serverLocationCallback);
|
90 |
-
testTimeoutHandler = setTimeout(async () => {
|
91 |
-
console.log('Test timed out after', MaxTestDurationSec, 'seconds');
|
92 |
-
// send final analytics data even if the test is not completed (we have enough data for a good estimate)
|
93 |
-
await sendAnalyticsData(currentBandwidth, currentLatency, serverLocation, 1.);
|
94 |
-
testStatus = 'Completed';
|
95 |
-
progress = 100;
|
96 |
-
}, MaxTestDurationSec * 1000);
|
97 |
-
earlyAnalyticsHandler = setTimeout(() => {
|
98 |
-
// send analytics event after 5 seconds (in case user closes the tab before the test completes)
|
99 |
sendAnalyticsData(currentBandwidth, currentLatency, serverLocation, progress / 100);
|
100 |
}, 5000);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
};
|
|
|
102 |
const stopTest = () => {
|
103 |
-
|
104 |
-
clearTimeout(testTimeoutHandler);
|
105 |
-
clearTimeout(earlyAnalyticsHandler);
|
106 |
};
|
107 |
|
108 |
let canvas: HTMLCanvasElement;
|
@@ -188,6 +196,10 @@
|
|
188 |
};
|
189 |
</script>
|
190 |
|
|
|
|
|
|
|
|
|
191 |
<!-- Main Card -->
|
192 |
<div
|
193 |
class="mb-8 overflow-hidden rounded-xl bg-white shadow-lg transition-all duration-300 hover:shadow-xl"
|
|
|
1 |
<script lang="ts">
|
2 |
+
import { getClientInfo, getServerLocation, sendAnalyticsData } from '$lib';
|
3 |
import { Chart, registerables } from 'chart.js';
|
4 |
import type { Action } from 'svelte/action';
|
5 |
import { onMount } from 'svelte';
|
6 |
|
7 |
Chart.register(...registerables);
|
8 |
|
|
|
|
|
9 |
let currentBandwidth = $state(0);
|
|
|
|
|
10 |
let currentLatency = $state(0);
|
11 |
let serverLocation = $state('-');
|
12 |
let clientIp = $state('Detecting...');
|
|
|
14 |
let progress = $state(0);
|
15 |
let bandwidthMeasurements: number[] = $state([]);
|
16 |
let timeMeasurements: string[] = $state([]);
|
17 |
+
let testStatus: 'Running' | 'Stopped' | 'Started' | 'Completed' | 'Idle' | 'Error' = $state('Idle');
|
18 |
+
|
19 |
+
let speedTest = undefined;
|
20 |
+
let fiveSecAnalytics = undefined;
|
21 |
|
22 |
// run ip info to get client IP and location
|
23 |
onMount(async () => {
|
24 |
+
let interval = setInterval(() => {
|
25 |
+
if (window.Speedtest) {
|
26 |
+
speedTest = new Speedtest();
|
27 |
+
clearInterval(interval)
|
28 |
+
}
|
29 |
+
}, 500)
|
30 |
+
|
31 |
+
getClientInfo().then((info) => {
|
32 |
+
clientIp = info.clientIp;
|
33 |
+
clientLocation = info.clientLocation;
|
34 |
+
});
|
35 |
});
|
36 |
|
37 |
+
const startTest = async () => {
|
38 |
+
if (!speedTest) {
|
39 |
+
console.error('Speedtest object is not initialized');
|
40 |
+
return;
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
|
|
|
|
43 |
progress = 0;
|
44 |
+
|
45 |
+
// Send analytics data after 5 seconds
|
46 |
+
fiveSecAnalytics = setTimeout(() => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
sendAnalyticsData(currentBandwidth, currentLatency, serverLocation, progress / 100);
|
48 |
}, 5000);
|
49 |
+
|
50 |
+
speedTest.onupdate = (data) => {
|
51 |
+
if (data.testState === 0) {
|
52 |
+
testStatus = 'Started';
|
53 |
+
}
|
54 |
+
|
55 |
+
if (data.testState === 1) {
|
56 |
+
testStatus = 'Running';
|
57 |
+
}
|
58 |
+
|
59 |
+
if (data.dlStatus === 'Fail') {
|
60 |
+
testStatus = 'Error';
|
61 |
+
}
|
62 |
+
|
63 |
+
const elapsedMs = parseFloat(data.pingStatus == '' ? 0 : data.pingStatus);
|
64 |
+
const mbps = parseFloat(data.dlStatus == '' ? 0 : data.dlStatus);
|
65 |
+
|
66 |
+
currentLatency = elapsedMs;
|
67 |
+
currentBandwidth = mbps;
|
68 |
+
progress = data.dlProgress * 100;
|
69 |
+
|
70 |
+
// update the bandwidth measurements array
|
71 |
+
bandwidthMeasurements.push(mbps); // convert Bps to Mbps
|
72 |
+
timeMeasurements.push((elapsedMs / 1000).toFixed(1)); // convert ms to seconds
|
73 |
+
// only keep the last 20 measurements
|
74 |
+
if (bandwidthMeasurements.length > 20) {
|
75 |
+
bandwidthMeasurements.shift();
|
76 |
+
timeMeasurements.shift();
|
77 |
+
}
|
78 |
+
};
|
79 |
+
|
80 |
+
speedTest.onend = (aborted: boolean) => {
|
81 |
+
clearTimeout(fiveSecAnalytics);
|
82 |
+
|
83 |
+
if (aborted) {
|
84 |
+
testStatus = 'Stopped';
|
85 |
+
return;
|
86 |
+
} else {
|
87 |
+
testStatus = 'Completed';
|
88 |
+
}
|
89 |
+
|
90 |
+
sendAnalyticsData(currentBandwidth, currentLatency, serverLocation, 1);
|
91 |
+
};
|
92 |
+
|
93 |
+
const server = {
|
94 |
+
name:"Huggingface CDN",
|
95 |
+
server:"//cdn-test-cloudfront.hf.co",
|
96 |
+
dlURL:"5gb.safetensors",
|
97 |
+
ulURL:"meta.json",
|
98 |
+
pingURL:"empty.php",
|
99 |
+
getIpURL:"meta.json"
|
100 |
+
};
|
101 |
+
|
102 |
+
speedTest.setParameter("time_dl_max","20");
|
103 |
+
speedTest.setParameter("test_order","IP_D");
|
104 |
+
// s.setParameter("xhr_dlMultistream",15);
|
105 |
+
speedTest.setSelectedServer(server);
|
106 |
+
|
107 |
+
serverLocation = await getServerLocation(`${server.server}${server.dlURL}`)
|
108 |
+
|
109 |
+
speedTest.start();
|
110 |
};
|
111 |
+
|
112 |
const stopTest = () => {
|
113 |
+
speedTest?.abort();
|
|
|
|
|
114 |
};
|
115 |
|
116 |
let canvas: HTMLCanvasElement;
|
|
|
196 |
};
|
197 |
</script>
|
198 |
|
199 |
+
<svelte:head>
|
200 |
+
<script type="text/javascript" src="speedtest.js"></script>
|
201 |
+
</svelte:head>
|
202 |
+
|
203 |
<!-- Main Card -->
|
204 |
<div
|
205 |
class="mb-8 overflow-hidden rounded-xl bg-white shadow-lg transition-all duration-300 hover:shadow-xl"
|
src/routes/analytics/+server.ts
CHANGED
@@ -47,7 +47,7 @@ export async function POST({ request }) {
|
|
47 |
|
48 |
await ddbClient.send(new PutItemCommand(putParams));
|
49 |
|
50 |
-
console.log('Received bandwidth data:', { bandwidth, latency, location, progress });
|
51 |
|
52 |
return json({ success: true });
|
53 |
} catch (error) {
|
|
|
47 |
|
48 |
await ddbClient.send(new PutItemCommand(putParams));
|
49 |
|
50 |
+
//console.log('Received bandwidth data:', { bandwidth, latency, location, progress });
|
51 |
|
52 |
return json({ success: true });
|
53 |
} catch (error) {
|
static/speedtest.js
ADDED
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
LibreSpeed - Main
|
3 |
+
by Federico Dossena
|
4 |
+
https://github.com/librespeed/speedtest/
|
5 |
+
GNU LGPLv3 License
|
6 |
+
*/
|
7 |
+
|
8 |
+
/*
|
9 |
+
This is the main interface between your webpage and the speed test.
|
10 |
+
It hides the speed test web worker to the page, and provides many convenient functions to control the test.
|
11 |
+
|
12 |
+
The best way to learn how to use this is to look at the basic example, but here's some documentation.
|
13 |
+
|
14 |
+
To initialize the test, create a new Speedtest object:
|
15 |
+
let s=new Speedtest();
|
16 |
+
Now you can think of this as a finite state machine. These are the states (use getState() to see them):
|
17 |
+
- 0: here you can change the speed test settings (such as test duration) with the setParameter("parameter",value) method. From here you can either start the test using start() (goes to state 3) or you can add multiple test points using addTestPoint(server) or addTestPoints(serverList) (goes to state 1). Additionally, this is the perfect moment to set up callbacks for the onupdate(data) and onend(aborted) events.
|
18 |
+
- 1: here you can add test points. You only need to do this if you want to use multiple test points.
|
19 |
+
A server is defined as an object like this:
|
20 |
+
{
|
21 |
+
name: "User friendly name",
|
22 |
+
server:"http://yourBackend.com/", <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
|
23 |
+
dlURL:"garbage.php" <----- path to garbage.php or its replacement on the server
|
24 |
+
ulURL:"empty.php" <----- path to empty.php or its replacement on the server
|
25 |
+
pingURL:"empty.php" <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector
|
26 |
+
getIpURL:"getIP.php" <----- path to getIP.php or its replacement on the server
|
27 |
+
}
|
28 |
+
While in state 1, you can only add test points, you cannot change the test settings. When you're done, use selectServer(callback) to select the test point with the lowest ping. This is asynchronous, when it's done, it will call your callback function and move to state 2. Calling setSelectedServer(server) will manually select a server and move to state 2.
|
29 |
+
- 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3
|
30 |
+
- 3: test running. Here, your onupdate event callback will be called periodically, with data coming from the worker about speed and progress. A data object will be passed to your onupdate function, with the following items:
|
31 |
+
- dlStatus: download speed in Mbit/s
|
32 |
+
- ulStatus: upload speed in Mbit/s
|
33 |
+
- pingStatus: ping in ms
|
34 |
+
- jitterStatus: jitter in ms
|
35 |
+
- dlProgress: progress of the download test as a float 0-1
|
36 |
+
- ulProgress: progress of the upload test as a float 0-1
|
37 |
+
- pingProgress: progress of the ping/jitter test as a float 0-1
|
38 |
+
- testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted)
|
39 |
+
- clientIp: IP address of the client performing the test (and optionally ISP and distance)
|
40 |
+
At the end of the test, the onend function will be called, with a boolean specifying whether the test was aborted or if it ended normally.
|
41 |
+
The test can be aborted at any time with abort().
|
42 |
+
At the end of the test, it will move to state 4
|
43 |
+
- 4: test finished. You can run it again by calling start() if you want.
|
44 |
+
*/
|
45 |
+
|
46 |
+
function Speedtest() {
|
47 |
+
this._serverList = []; //when using multiple points of test, this is a list of test points
|
48 |
+
this._selectedServer = null; //when using multiple points of test, this is the selected server
|
49 |
+
this._settings = {}; //settings for the speed test worker
|
50 |
+
this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
|
51 |
+
console.log(
|
52 |
+
"LibreSpeed by Federico Dossena v5.4.1 - https://github.com/librespeed/speedtest"
|
53 |
+
);
|
54 |
+
}
|
55 |
+
|
56 |
+
Speedtest.prototype = {
|
57 |
+
constructor: Speedtest,
|
58 |
+
/**
|
59 |
+
* Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
|
60 |
+
*/
|
61 |
+
getState: function() {
|
62 |
+
return this._state;
|
63 |
+
},
|
64 |
+
/**
|
65 |
+
* Change one of the test settings from their defaults.
|
66 |
+
* - parameter: string with the name of the parameter that you want to set
|
67 |
+
* - value: new value for the parameter
|
68 |
+
*
|
69 |
+
* Invalid values or nonexistant parameters will be ignored by the speed test worker.
|
70 |
+
*/
|
71 |
+
setParameter: function(parameter, value) {
|
72 |
+
if (this._state == 3)
|
73 |
+
throw "You cannot change the test settings while running the test";
|
74 |
+
this._settings[parameter] = value;
|
75 |
+
if(parameter === "telemetry_extra"){
|
76 |
+
this._originalExtra=this._settings.telemetry_extra;
|
77 |
+
}
|
78 |
+
},
|
79 |
+
/**
|
80 |
+
* Used internally to check if a server object contains all the required elements.
|
81 |
+
* Also fixes the server URL if needed.
|
82 |
+
*/
|
83 |
+
_checkServerDefinition: function(server) {
|
84 |
+
try {
|
85 |
+
if (typeof server.name !== "string")
|
86 |
+
throw "Name string missing from server definition (name)";
|
87 |
+
if (typeof server.server !== "string")
|
88 |
+
throw "Server address string missing from server definition (server)";
|
89 |
+
if (server.server.charAt(server.server.length - 1) != "/")
|
90 |
+
server.server += "/";
|
91 |
+
if (server.server.indexOf("//") == 0)
|
92 |
+
server.server = location.protocol + server.server;
|
93 |
+
if (typeof server.dlURL !== "string")
|
94 |
+
throw "Download URL string missing from server definition (dlURL)";
|
95 |
+
if (typeof server.ulURL !== "string")
|
96 |
+
throw "Upload URL string missing from server definition (ulURL)";
|
97 |
+
if (typeof server.pingURL !== "string")
|
98 |
+
throw "Ping URL string missing from server definition (pingURL)";
|
99 |
+
if (typeof server.getIpURL !== "string")
|
100 |
+
throw "GetIP URL string missing from server definition (getIpURL)";
|
101 |
+
} catch (e) {
|
102 |
+
throw "Invalid server definition";
|
103 |
+
}
|
104 |
+
},
|
105 |
+
/**
|
106 |
+
* Add a test point (multiple points of test)
|
107 |
+
* server: the server to be added as an object. Must contain the following elements:
|
108 |
+
* {
|
109 |
+
* name: "User friendly name",
|
110 |
+
* server:"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
|
111 |
+
* dlURL:"garbage.php" path to garbage.php or its replacement on the server
|
112 |
+
* ulURL:"empty.php" path to empty.php or its replacement on the server
|
113 |
+
* pingURL:"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
|
114 |
+
* getIpURL:"getIP.php" path to getIP.php or its replacement on the server
|
115 |
+
* }
|
116 |
+
*/
|
117 |
+
addTestPoint: function(server) {
|
118 |
+
this._checkServerDefinition(server);
|
119 |
+
if (this._state == 0) this._state = 1;
|
120 |
+
if (this._state != 1) throw "You can't add a server after server selection";
|
121 |
+
this._settings.mpot = true;
|
122 |
+
this._serverList.push(server);
|
123 |
+
},
|
124 |
+
/**
|
125 |
+
* Same as addTestPoint, but you can pass an array of servers
|
126 |
+
*/
|
127 |
+
addTestPoints: function(list) {
|
128 |
+
for (let i = 0; i < list.length; i++) this.addTestPoint(list[i]);
|
129 |
+
},
|
130 |
+
/**
|
131 |
+
* Load a JSON server list from URL (multiple points of test)
|
132 |
+
* url: the url where the server list can be fetched. Must be an array with objects containing the following elements:
|
133 |
+
* {
|
134 |
+
* "name": "User friendly name",
|
135 |
+
* "server":"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
|
136 |
+
* "dlURL":"garbage.php" path to garbage.php or its replacement on the server
|
137 |
+
* "ulURL":"empty.php" path to empty.php or its replacement on the server
|
138 |
+
* "pingURL":"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
|
139 |
+
* "getIpURL":"getIP.php" path to getIP.php or its replacement on the server
|
140 |
+
* }
|
141 |
+
* result: callback to be called when the list is loaded correctly. An array with the loaded servers will be passed to this function, or null if it failed
|
142 |
+
*/
|
143 |
+
loadServerList: function(url,result) {
|
144 |
+
if (this._state == 0) this._state = 1;
|
145 |
+
if (this._state != 1) throw "You can't add a server after server selection";
|
146 |
+
this._settings.mpot = true;
|
147 |
+
let xhr = new XMLHttpRequest();
|
148 |
+
xhr.onload = function(){
|
149 |
+
try{
|
150 |
+
const servers=JSON.parse(xhr.responseText);
|
151 |
+
for(let i=0;i<servers.length;i++){
|
152 |
+
this._checkServerDefinition(servers[i]);
|
153 |
+
}
|
154 |
+
this.addTestPoints(servers);
|
155 |
+
result(servers);
|
156 |
+
}catch(e){
|
157 |
+
result(null);
|
158 |
+
}
|
159 |
+
}.bind(this);
|
160 |
+
xhr.onerror = function(){result(null);}
|
161 |
+
xhr.open("GET",url);
|
162 |
+
xhr.send();
|
163 |
+
},
|
164 |
+
/**
|
165 |
+
* Returns the selected server (multiple points of test)
|
166 |
+
*/
|
167 |
+
getSelectedServer: function() {
|
168 |
+
if (this._state < 2 || this._selectedServer == null)
|
169 |
+
throw "No server is selected";
|
170 |
+
return this._selectedServer;
|
171 |
+
},
|
172 |
+
/**
|
173 |
+
* Manually selects one of the test points (multiple points of test)
|
174 |
+
*/
|
175 |
+
setSelectedServer: function(server) {
|
176 |
+
this._checkServerDefinition(server);
|
177 |
+
if (this._state == 3)
|
178 |
+
throw "You can't select a server while the test is running";
|
179 |
+
this._selectedServer = server;
|
180 |
+
this._state = 2;
|
181 |
+
},
|
182 |
+
/**
|
183 |
+
* Automatically selects a server from the list of added test points. The server with the lowest ping will be chosen. (multiple points of test)
|
184 |
+
* The process is asynchronous and the passed result callback function will be called when it's done, then the test can be started.
|
185 |
+
*/
|
186 |
+
selectServer: function(result) {
|
187 |
+
if (this._state != 1) {
|
188 |
+
if (this._state == 0) throw "No test points added";
|
189 |
+
if (this._state == 2) throw "Server already selected";
|
190 |
+
if (this._state >= 3)
|
191 |
+
throw "You can't select a server while the test is running";
|
192 |
+
}
|
193 |
+
if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
|
194 |
+
/*this function goes through a list of servers. For each server, the ping is measured, then the server with the function selected is called with the best server, or null if all the servers were down.
|
195 |
+
*/
|
196 |
+
const select = function(serverList, selected) {
|
197 |
+
//pings the specified URL, then calls the function result. Result will receive a parameter which is either the time it took to ping the URL, or -1 if something went wrong.
|
198 |
+
const PING_TIMEOUT = 2000;
|
199 |
+
let USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers
|
200 |
+
if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
|
201 |
+
//IE11 doesn't support XHR timeout
|
202 |
+
USE_PING_TIMEOUT = false;
|
203 |
+
}
|
204 |
+
const ping = function(url, rtt) {
|
205 |
+
url += (url.match(/\?/) ? "&" : "?") + "cors=true";
|
206 |
+
let xhr = new XMLHttpRequest();
|
207 |
+
let t = new Date().getTime();
|
208 |
+
xhr.onload = function() {
|
209 |
+
if (xhr.responseText.length == 0) {
|
210 |
+
//we expect an empty response
|
211 |
+
let instspd = new Date().getTime() - t; //rough timing estimate
|
212 |
+
try {
|
213 |
+
//try to get more accurate timing using performance API
|
214 |
+
let p = performance.getEntriesByName(url);
|
215 |
+
p = p[p.length - 1];
|
216 |
+
let d = p.responseStart - p.requestStart;
|
217 |
+
if (d <= 0) d = p.duration;
|
218 |
+
if (d > 0 && d < instspd) instspd = d;
|
219 |
+
} catch (e) {}
|
220 |
+
rtt(instspd);
|
221 |
+
} else rtt(-1);
|
222 |
+
}.bind(this);
|
223 |
+
xhr.onerror = function() {
|
224 |
+
rtt(-1);
|
225 |
+
}.bind(this);
|
226 |
+
xhr.open("GET", url);
|
227 |
+
if (USE_PING_TIMEOUT) {
|
228 |
+
try {
|
229 |
+
xhr.timeout = PING_TIMEOUT;
|
230 |
+
xhr.ontimeout = xhr.onerror;
|
231 |
+
} catch (e) {}
|
232 |
+
}
|
233 |
+
xhr.send();
|
234 |
+
}.bind(this);
|
235 |
+
|
236 |
+
//this function repeatedly pings a server to get a good estimate of the ping. When it's done, it calls the done function without parameters. At the end of the execution, the server will have a new parameter called pingT, which is either the best ping we got from the server or -1 if something went wrong.
|
237 |
+
const PINGS = 3, //up to 3 pings are performed, unless the server is down...
|
238 |
+
SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold
|
239 |
+
const checkServer = function(server, done) {
|
240 |
+
let i = 0;
|
241 |
+
server.pingT = -1;
|
242 |
+
if (server.server.indexOf(location.protocol) == -1) done();
|
243 |
+
else {
|
244 |
+
const nextPing = function() {
|
245 |
+
if (i++ == PINGS) {
|
246 |
+
done();
|
247 |
+
return;
|
248 |
+
}
|
249 |
+
ping(
|
250 |
+
server.server + server.pingURL,
|
251 |
+
function(t) {
|
252 |
+
if (t >= 0) {
|
253 |
+
if (t < server.pingT || server.pingT == -1) server.pingT = t;
|
254 |
+
if (t < SLOW_THRESHOLD) nextPing();
|
255 |
+
else done();
|
256 |
+
} else done();
|
257 |
+
}.bind(this)
|
258 |
+
);
|
259 |
+
}.bind(this);
|
260 |
+
nextPing();
|
261 |
+
}
|
262 |
+
}.bind(this);
|
263 |
+
//check servers in list, one by one
|
264 |
+
let i = 0;
|
265 |
+
const done = function() {
|
266 |
+
let bestServer = null;
|
267 |
+
for (let i = 0; i < serverList.length; i++) {
|
268 |
+
if (
|
269 |
+
serverList[i].pingT != -1 &&
|
270 |
+
(bestServer == null || serverList[i].pingT < bestServer.pingT)
|
271 |
+
)
|
272 |
+
bestServer = serverList[i];
|
273 |
+
}
|
274 |
+
selected(bestServer);
|
275 |
+
}.bind(this);
|
276 |
+
const nextServer = function() {
|
277 |
+
if (i == serverList.length) {
|
278 |
+
done();
|
279 |
+
return;
|
280 |
+
}
|
281 |
+
checkServer(serverList[i++], nextServer);
|
282 |
+
}.bind(this);
|
283 |
+
nextServer();
|
284 |
+
}.bind(this);
|
285 |
+
|
286 |
+
//parallel server selection
|
287 |
+
const CONCURRENCY = 6;
|
288 |
+
let serverLists = [];
|
289 |
+
for (let i = 0; i < CONCURRENCY; i++) {
|
290 |
+
serverLists[i] = [];
|
291 |
+
}
|
292 |
+
for (let i = 0; i < this._serverList.length; i++) {
|
293 |
+
serverLists[i % CONCURRENCY].push(this._serverList[i]);
|
294 |
+
}
|
295 |
+
let completed = 0;
|
296 |
+
let bestServer = null;
|
297 |
+
for (let i = 0; i < CONCURRENCY; i++) {
|
298 |
+
select(
|
299 |
+
serverLists[i],
|
300 |
+
function(server) {
|
301 |
+
if (server != null) {
|
302 |
+
if (bestServer == null || server.pingT < bestServer.pingT)
|
303 |
+
bestServer = server;
|
304 |
+
}
|
305 |
+
completed++;
|
306 |
+
if (completed == CONCURRENCY) {
|
307 |
+
this._selectedServer = bestServer;
|
308 |
+
this._state = 2;
|
309 |
+
if (result) result(bestServer);
|
310 |
+
}
|
311 |
+
}.bind(this)
|
312 |
+
);
|
313 |
+
}
|
314 |
+
},
|
315 |
+
/**
|
316 |
+
* Starts the test.
|
317 |
+
* During the test, the onupdate(data) callback function will be called periodically with data from the worker.
|
318 |
+
* At the end of the test, the onend(aborted) function will be called with a boolean telling you if the test was aborted or if it ended normally.
|
319 |
+
*/
|
320 |
+
start: function() {
|
321 |
+
if (this._state == 3) throw "Test already running";
|
322 |
+
this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
|
323 |
+
this.worker.onmessage = function(e) {
|
324 |
+
if (e.data === this._prevData) return;
|
325 |
+
else this._prevData = e.data;
|
326 |
+
const data = JSON.parse(e.data);
|
327 |
+
try {
|
328 |
+
if (this.onupdate) this.onupdate(data);
|
329 |
+
} catch (e) {
|
330 |
+
console.error("Speedtest onupdate event threw exception: " + e);
|
331 |
+
}
|
332 |
+
if (data.testState >= 4) {
|
333 |
+
clearInterval(this.updater);
|
334 |
+
this._state = 4;
|
335 |
+
try {
|
336 |
+
if (this.onend) this.onend(data.testState == 5);
|
337 |
+
} catch (e) {
|
338 |
+
console.error("Speedtest onend event threw exception: " + e);
|
339 |
+
}
|
340 |
+
}
|
341 |
+
}.bind(this);
|
342 |
+
this.updater = setInterval(
|
343 |
+
function() {
|
344 |
+
this.worker.postMessage("status");
|
345 |
+
}.bind(this),
|
346 |
+
200
|
347 |
+
);
|
348 |
+
if (this._state == 1)
|
349 |
+
throw "When using multiple points of test, you must call selectServer before starting the test";
|
350 |
+
if (this._state == 2) {
|
351 |
+
this._settings.url_dl =
|
352 |
+
this._selectedServer.server + this._selectedServer.dlURL;
|
353 |
+
this._settings.url_ul =
|
354 |
+
this._selectedServer.server + this._selectedServer.ulURL;
|
355 |
+
this._settings.url_ping =
|
356 |
+
this._selectedServer.server + this._selectedServer.pingURL;
|
357 |
+
this._settings.url_getIp =
|
358 |
+
this._selectedServer.server + this._selectedServer.getIpURL;
|
359 |
+
if (typeof this._originalExtra !== "undefined") {
|
360 |
+
this._settings.telemetry_extra = JSON.stringify({
|
361 |
+
server: this._selectedServer.name,
|
362 |
+
extra: this._originalExtra
|
363 |
+
});
|
364 |
+
} else
|
365 |
+
this._settings.telemetry_extra = JSON.stringify({
|
366 |
+
server: this._selectedServer.name
|
367 |
+
});
|
368 |
+
}
|
369 |
+
this._state = 3;
|
370 |
+
this.worker.postMessage("start " + JSON.stringify(this._settings));
|
371 |
+
},
|
372 |
+
/**
|
373 |
+
* Aborts the test while it's running.
|
374 |
+
*/
|
375 |
+
abort: function() {
|
376 |
+
if (this._state < 3) throw "You cannot abort a test that's not started yet";
|
377 |
+
if (this._state < 4) this.worker.postMessage("abort");
|
378 |
+
}
|
379 |
+
};
|
static/speedtest_worker.js
ADDED
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
LibreSpeed - Worker
|
3 |
+
by Federico Dossena
|
4 |
+
https://github.com/librespeed/speedtest/
|
5 |
+
GNU LGPLv3 License
|
6 |
+
*/
|
7 |
+
|
8 |
+
// data reported to main thread
|
9 |
+
let testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
|
10 |
+
let dlStatus = ""; // download speed in megabit/s with 2 decimal digits
|
11 |
+
let ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
|
12 |
+
let pingStatus = ""; // ping in milliseconds with 2 decimal digits
|
13 |
+
let jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
|
14 |
+
let clientIp = ""; // client's IP address as reported by getIP.php
|
15 |
+
let dlProgress = 0; //progress of download test 0-1
|
16 |
+
let ulProgress = 0; //progress of upload test 0-1
|
17 |
+
let pingProgress = 0; //progress of ping+jitter test 0-1
|
18 |
+
let testId = null; //test ID (sent back by telemetry if used, null otherwise)
|
19 |
+
|
20 |
+
let log = ""; //telemetry log
|
21 |
+
function tlog(s) {
|
22 |
+
if (settings.telemetry_level >= 2) {
|
23 |
+
log += Date.now() + ": " + s + "\n";
|
24 |
+
}
|
25 |
+
}
|
26 |
+
function tverb(s) {
|
27 |
+
if (settings.telemetry_level >= 3) {
|
28 |
+
log += Date.now() + ": " + s + "\n";
|
29 |
+
}
|
30 |
+
}
|
31 |
+
function twarn(s) {
|
32 |
+
if (settings.telemetry_level >= 2) {
|
33 |
+
log += Date.now() + " WARN: " + s + "\n";
|
34 |
+
}
|
35 |
+
console.warn(s);
|
36 |
+
}
|
37 |
+
|
38 |
+
// test settings. can be overridden by sending specific values with the start command
|
39 |
+
let settings = {
|
40 |
+
mpot: false, //set to true when in MPOT mode
|
41 |
+
test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
|
42 |
+
time_ul_max: 15, // max duration of upload test in seconds
|
43 |
+
time_dl_max: 15, // max duration of download test in seconds
|
44 |
+
time_auto: true, // if set to true, tests will take less time on faster connections
|
45 |
+
time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
|
46 |
+
time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
|
47 |
+
count_ping: 10, // number of pings to perform in ping test
|
48 |
+
url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
|
49 |
+
url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
|
50 |
+
url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
|
51 |
+
url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
|
52 |
+
getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
|
53 |
+
getIp_ispInfo_distance: "km", //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
|
54 |
+
xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
|
55 |
+
xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
|
56 |
+
xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
|
57 |
+
xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
|
58 |
+
xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
|
59 |
+
xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
|
60 |
+
garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
|
61 |
+
enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
|
62 |
+
ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
|
63 |
+
overheadCompensationFactor: 1.06, //can be changed to compensate for transport overhead. (see doc.md for some other values)
|
64 |
+
useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
|
65 |
+
telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
|
66 |
+
url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
|
67 |
+
telemetry_extra: "", //extra data that can be passed to the telemetry through the settings
|
68 |
+
forceIE11Workaround: false //when set to true, it will force the IE11 upload test on all browsers. Debug only
|
69 |
+
};
|
70 |
+
|
71 |
+
let xhr = null; // array of currently active xhr requests
|
72 |
+
let interval = null; // timer used in tests
|
73 |
+
let test_pointer = 0; //pointer to the next test to run inside settings.test_order
|
74 |
+
|
75 |
+
/*
|
76 |
+
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
|
77 |
+
*/
|
78 |
+
function url_sep(url) {
|
79 |
+
return url.match(/\?/) ? "&" : "?";
|
80 |
+
}
|
81 |
+
|
82 |
+
/*
|
83 |
+
listener for commands from main thread to this worker.
|
84 |
+
commands:
|
85 |
+
-status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
|
86 |
+
-abort: aborts the current test
|
87 |
+
-start: starts the test. optionally, settings can be passed as JSON.
|
88 |
+
example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
|
89 |
+
*/
|
90 |
+
this.addEventListener("message", function(e) {
|
91 |
+
const params = e.data.split(" ");
|
92 |
+
if (params[0] === "status") {
|
93 |
+
// return status
|
94 |
+
postMessage(
|
95 |
+
JSON.stringify({
|
96 |
+
testState: testState,
|
97 |
+
dlStatus: dlStatus,
|
98 |
+
ulStatus: ulStatus,
|
99 |
+
pingStatus: pingStatus,
|
100 |
+
clientIp: clientIp,
|
101 |
+
jitterStatus: jitterStatus,
|
102 |
+
dlProgress: dlProgress,
|
103 |
+
ulProgress: ulProgress,
|
104 |
+
pingProgress: pingProgress,
|
105 |
+
testId: testId
|
106 |
+
})
|
107 |
+
);
|
108 |
+
}
|
109 |
+
if (params[0] === "start" && testState === -1) {
|
110 |
+
// start new test
|
111 |
+
testState = 0;
|
112 |
+
try {
|
113 |
+
// parse settings, if present
|
114 |
+
let s = {};
|
115 |
+
try {
|
116 |
+
const ss = e.data.substring(5);
|
117 |
+
if (ss) s = JSON.parse(ss);
|
118 |
+
} catch (e) {
|
119 |
+
twarn("Error parsing custom settings JSON. Please check your syntax");
|
120 |
+
}
|
121 |
+
//copy custom settings
|
122 |
+
for (let key in s) {
|
123 |
+
if (typeof settings[key] !== "undefined") settings[key] = s[key];
|
124 |
+
else twarn("Unknown setting ignored: " + key);
|
125 |
+
}
|
126 |
+
const ua = navigator.userAgent;
|
127 |
+
// quirks for specific browsers. apply only if not overridden. more may be added in future releases
|
128 |
+
if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
|
129 |
+
if (/Firefox.(\d+\.\d+)/i.test(ua)) {
|
130 |
+
if (typeof s.ping_allowPerformanceApi === "undefined") {
|
131 |
+
// ff performance API sucks
|
132 |
+
settings.ping_allowPerformanceApi = false;
|
133 |
+
}
|
134 |
+
}
|
135 |
+
if (/Edge.(\d+\.\d+)/i.test(ua)) {
|
136 |
+
if (typeof s.xhr_dlMultistream === "undefined") {
|
137 |
+
// edge more precise with 3 download streams
|
138 |
+
settings.xhr_dlMultistream = 3;
|
139 |
+
}
|
140 |
+
}
|
141 |
+
if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
|
142 |
+
if (typeof s.xhr_dlMultistream === "undefined") {
|
143 |
+
// chrome more precise with 5 streams
|
144 |
+
settings.xhr_dlMultistream = 5;
|
145 |
+
}
|
146 |
+
}
|
147 |
+
}
|
148 |
+
if (/Edge.(\d+\.\d+)/i.test(ua)) {
|
149 |
+
//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
|
150 |
+
settings.forceIE11Workaround = true;
|
151 |
+
}
|
152 |
+
if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
|
153 |
+
//PS4 browser has the same bug as IE11/Edge
|
154 |
+
settings.forceIE11Workaround = true;
|
155 |
+
}
|
156 |
+
if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
|
157 |
+
//cheap af
|
158 |
+
//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
|
159 |
+
settings.xhr_ul_blob_megabytes = 4;
|
160 |
+
}
|
161 |
+
if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
|
162 |
+
//Safari also needs the IE11 workaround but only for the MPOT version
|
163 |
+
settings.forceIE11Workaround = true;
|
164 |
+
}
|
165 |
+
//telemetry_level has to be parsed and not just copied
|
166 |
+
if (typeof s.telemetry_level !== "undefined") settings.telemetry_level = s.telemetry_level === "basic" ? 1 : s.telemetry_level === "full" ? 2 : s.telemetry_level === "debug" ? 3 : 0; // telemetry level
|
167 |
+
//transform test_order to uppercase, just in case
|
168 |
+
settings.test_order = settings.test_order.toUpperCase();
|
169 |
+
} catch (e) {
|
170 |
+
twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
|
171 |
+
}
|
172 |
+
// run the tests
|
173 |
+
tverb(JSON.stringify(settings));
|
174 |
+
test_pointer = 0;
|
175 |
+
let iRun = false,
|
176 |
+
dRun = false,
|
177 |
+
uRun = false,
|
178 |
+
pRun = false;
|
179 |
+
const runNextTest = function() {
|
180 |
+
if (testState == 5) return;
|
181 |
+
if (test_pointer >= settings.test_order.length) {
|
182 |
+
//test is finished
|
183 |
+
if (settings.telemetry_level > 0)
|
184 |
+
sendTelemetry(function(id) {
|
185 |
+
testState = 4;
|
186 |
+
if (id != null) testId = id;
|
187 |
+
});
|
188 |
+
else testState = 4;
|
189 |
+
return;
|
190 |
+
}
|
191 |
+
switch (settings.test_order.charAt(test_pointer)) {
|
192 |
+
case "I":
|
193 |
+
{
|
194 |
+
test_pointer++;
|
195 |
+
if (iRun) {
|
196 |
+
runNextTest();
|
197 |
+
return;
|
198 |
+
} else iRun = true;
|
199 |
+
getIp(runNextTest);
|
200 |
+
}
|
201 |
+
break;
|
202 |
+
case "D":
|
203 |
+
{
|
204 |
+
test_pointer++;
|
205 |
+
if (dRun) {
|
206 |
+
runNextTest();
|
207 |
+
return;
|
208 |
+
} else dRun = true;
|
209 |
+
testState = 1;
|
210 |
+
dlTest(runNextTest);
|
211 |
+
}
|
212 |
+
break;
|
213 |
+
case "U":
|
214 |
+
{
|
215 |
+
test_pointer++;
|
216 |
+
if (uRun) {
|
217 |
+
runNextTest();
|
218 |
+
return;
|
219 |
+
} else uRun = true;
|
220 |
+
testState = 3;
|
221 |
+
ulTest(runNextTest);
|
222 |
+
}
|
223 |
+
break;
|
224 |
+
case "P":
|
225 |
+
{
|
226 |
+
test_pointer++;
|
227 |
+
if (pRun) {
|
228 |
+
runNextTest();
|
229 |
+
return;
|
230 |
+
} else pRun = true;
|
231 |
+
testState = 2;
|
232 |
+
pingTest(runNextTest);
|
233 |
+
}
|
234 |
+
break;
|
235 |
+
case "_":
|
236 |
+
{
|
237 |
+
test_pointer++;
|
238 |
+
setTimeout(runNextTest, 1000);
|
239 |
+
}
|
240 |
+
break;
|
241 |
+
default:
|
242 |
+
test_pointer++;
|
243 |
+
}
|
244 |
+
};
|
245 |
+
runNextTest();
|
246 |
+
}
|
247 |
+
if (params[0] === "abort") {
|
248 |
+
// abort command
|
249 |
+
if (testState >= 4) return;
|
250 |
+
tlog("manually aborted");
|
251 |
+
clearRequests(); // stop all xhr activity
|
252 |
+
runNextTest = null;
|
253 |
+
if (interval) clearInterval(interval); // clear timer if present
|
254 |
+
if (settings.telemetry_level > 1) sendTelemetry(function() {});
|
255 |
+
testState = 5; //set test as aborted
|
256 |
+
dlStatus = "";
|
257 |
+
ulStatus = "";
|
258 |
+
pingStatus = "";
|
259 |
+
jitterStatus = "";
|
260 |
+
clientIp = "";
|
261 |
+
dlProgress = 0;
|
262 |
+
ulProgress = 0;
|
263 |
+
pingProgress = 0;
|
264 |
+
}
|
265 |
+
});
|
266 |
+
// stops all XHR activity, aggressively
|
267 |
+
function clearRequests() {
|
268 |
+
tverb("stopping pending XHRs");
|
269 |
+
if (xhr) {
|
270 |
+
for (let i = 0; i < xhr.length; i++) {
|
271 |
+
try {
|
272 |
+
xhr[i].onprogress = null;
|
273 |
+
xhr[i].onload = null;
|
274 |
+
xhr[i].onerror = null;
|
275 |
+
} catch (e) {}
|
276 |
+
try {
|
277 |
+
xhr[i].upload.onprogress = null;
|
278 |
+
xhr[i].upload.onload = null;
|
279 |
+
xhr[i].upload.onerror = null;
|
280 |
+
} catch (e) {}
|
281 |
+
try {
|
282 |
+
xhr[i].abort();
|
283 |
+
} catch (e) {}
|
284 |
+
try {
|
285 |
+
delete xhr[i];
|
286 |
+
} catch (e) {}
|
287 |
+
}
|
288 |
+
xhr = null;
|
289 |
+
}
|
290 |
+
}
|
291 |
+
// gets client's IP using url_getIp, then calls the done function
|
292 |
+
let ipCalled = false; // used to prevent multiple accidental calls to getIp
|
293 |
+
let ispInfo = ""; //used for telemetry
|
294 |
+
function getIp(done) {
|
295 |
+
tverb("getIp");
|
296 |
+
if (ipCalled) return;
|
297 |
+
else ipCalled = true; // getIp already called?
|
298 |
+
let startT = new Date().getTime();
|
299 |
+
xhr = new XMLHttpRequest();
|
300 |
+
xhr.onload = function() {
|
301 |
+
tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
|
302 |
+
try {
|
303 |
+
const data = JSON.parse(xhr.responseText);
|
304 |
+
clientIp = data.processedString;
|
305 |
+
ispInfo = data.rawIspInfo;
|
306 |
+
} catch (e) {
|
307 |
+
clientIp = xhr.responseText;
|
308 |
+
ispInfo = "";
|
309 |
+
}
|
310 |
+
done();
|
311 |
+
};
|
312 |
+
xhr.onerror = function() {
|
313 |
+
tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
|
314 |
+
done();
|
315 |
+
};
|
316 |
+
xhr.open("GET", settings.url_getIp + url_sep(settings.url_getIp) + (settings.mpot ? "cors=true&" : "") + (settings.getIp_ispInfo ? "isp=true" + (settings.getIp_ispInfo_distance ? "&distance=" + settings.getIp_ispInfo_distance + "&" : "&") : "&") + "r=" + Math.random(), true);
|
317 |
+
xhr.send();
|
318 |
+
}
|
319 |
+
// download test, calls done function when it's over
|
320 |
+
let dlCalled = false; // used to prevent multiple accidental calls to dlTest
|
321 |
+
function dlTest(done) {
|
322 |
+
tverb("dlTest");
|
323 |
+
if (dlCalled) return;
|
324 |
+
else dlCalled = true; // dlTest already called?
|
325 |
+
let totLoaded = 0.0, // total number of loaded bytes
|
326 |
+
startT = new Date().getTime(), // timestamp when test was started
|
327 |
+
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
|
328 |
+
graceTimeDone = false, //set to true after the grace time is past
|
329 |
+
failed = false; // set to true if a stream fails
|
330 |
+
xhr = [];
|
331 |
+
// function to create a download stream. streams are slightly delayed so that they will not end at the same time
|
332 |
+
const testStream = function(i, delay) {
|
333 |
+
setTimeout(
|
334 |
+
function() {
|
335 |
+
if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
|
336 |
+
tverb("dl test stream started " + i + " " + delay);
|
337 |
+
let prevLoaded = 0; // number of bytes loaded last time onprogress was called
|
338 |
+
let x = new XMLHttpRequest();
|
339 |
+
xhr[i] = x;
|
340 |
+
xhr[i].onprogress = function(event) {
|
341 |
+
tverb("dl stream progress event " + i + " " + event.loaded);
|
342 |
+
if (testState !== 1) {
|
343 |
+
try {
|
344 |
+
x.abort();
|
345 |
+
} catch (e) {}
|
346 |
+
} // just in case this XHR is still running after the download test
|
347 |
+
// progress event, add number of new loaded bytes to totLoaded
|
348 |
+
const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
|
349 |
+
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
|
350 |
+
totLoaded += loadDiff;
|
351 |
+
prevLoaded = event.loaded;
|
352 |
+
}.bind(this);
|
353 |
+
xhr[i].onload = function() {
|
354 |
+
// the large file has been loaded entirely, start again
|
355 |
+
tverb("dl stream finished " + i);
|
356 |
+
try {
|
357 |
+
xhr[i].abort();
|
358 |
+
} catch (e) {} // reset the stream data to empty ram
|
359 |
+
testStream(i, 0);
|
360 |
+
}.bind(this);
|
361 |
+
xhr[i].onerror = function() {
|
362 |
+
// error
|
363 |
+
tverb("dl stream failed " + i);
|
364 |
+
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
|
365 |
+
try {
|
366 |
+
xhr[i].abort();
|
367 |
+
} catch (e) {}
|
368 |
+
delete xhr[i];
|
369 |
+
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
|
370 |
+
}.bind(this);
|
371 |
+
// send xhr
|
372 |
+
try {
|
373 |
+
if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
|
374 |
+
else xhr[i].responseType = "arraybuffer";
|
375 |
+
} catch (e) {}
|
376 |
+
xhr[i].open("GET", settings.url_dl + url_sep(settings.url_dl) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random() + "&ckSize=" + settings.garbagePhp_chunkSize, true); // random string to prevent caching
|
377 |
+
xhr[i].send();
|
378 |
+
}.bind(this),
|
379 |
+
1 + delay
|
380 |
+
);
|
381 |
+
}.bind(this);
|
382 |
+
// open streams
|
383 |
+
for (let i = 0; i < settings.xhr_dlMultistream; i++) {
|
384 |
+
testStream(i, settings.xhr_multistreamDelay * i);
|
385 |
+
}
|
386 |
+
// every 200ms, update dlStatus
|
387 |
+
interval = setInterval(
|
388 |
+
function() {
|
389 |
+
tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
|
390 |
+
const t = new Date().getTime() - startT;
|
391 |
+
if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
|
392 |
+
if (t < 200) return;
|
393 |
+
if (!graceTimeDone) {
|
394 |
+
if (t > 1000 * settings.time_dlGraceTime) {
|
395 |
+
if (totLoaded > 0) {
|
396 |
+
// if the connection is so slow that we didn't get a single chunk yet, do not reset
|
397 |
+
startT = new Date().getTime();
|
398 |
+
bonusT = 0;
|
399 |
+
totLoaded = 0.0;
|
400 |
+
}
|
401 |
+
graceTimeDone = true;
|
402 |
+
}
|
403 |
+
} else {
|
404 |
+
const speed = totLoaded / (t / 1000.0);
|
405 |
+
if (settings.time_auto) {
|
406 |
+
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
|
407 |
+
const bonus = (5.0 * speed) / 100000;
|
408 |
+
bonusT += bonus > 400 ? 400 : bonus;
|
409 |
+
}
|
410 |
+
//update status
|
411 |
+
dlStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
|
412 |
+
if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
|
413 |
+
// test is over, stop streams and timer
|
414 |
+
if (failed || isNaN(dlStatus)) dlStatus = "Fail";
|
415 |
+
clearRequests();
|
416 |
+
clearInterval(interval);
|
417 |
+
dlProgress = 1;
|
418 |
+
tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
|
419 |
+
done();
|
420 |
+
}
|
421 |
+
}
|
422 |
+
}.bind(this),
|
423 |
+
200
|
424 |
+
);
|
425 |
+
}
|
426 |
+
// upload test, calls done function when it's over
|
427 |
+
let ulCalled = false; // used to prevent multiple accidental calls to ulTest
|
428 |
+
function ulTest(done) {
|
429 |
+
tverb("ulTest");
|
430 |
+
if (ulCalled) return;
|
431 |
+
else ulCalled = true; // ulTest already called?
|
432 |
+
// garbage data for upload test
|
433 |
+
let r = new ArrayBuffer(1048576);
|
434 |
+
const maxInt = Math.pow(2, 32) - 1;
|
435 |
+
try {
|
436 |
+
r = new Uint32Array(r);
|
437 |
+
for (let i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
|
438 |
+
} catch (e) {}
|
439 |
+
let req = [];
|
440 |
+
let reqsmall = [];
|
441 |
+
for (let i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
|
442 |
+
req = new Blob(req);
|
443 |
+
r = new ArrayBuffer(262144);
|
444 |
+
try {
|
445 |
+
r = new Uint32Array(r);
|
446 |
+
for (let i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
|
447 |
+
} catch (e) {}
|
448 |
+
reqsmall.push(r);
|
449 |
+
reqsmall = new Blob(reqsmall);
|
450 |
+
const testFunction = function() {
|
451 |
+
let totLoaded = 0.0, // total number of transmitted bytes
|
452 |
+
startT = new Date().getTime(), // timestamp when test was started
|
453 |
+
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
|
454 |
+
graceTimeDone = false, //set to true after the grace time is past
|
455 |
+
failed = false; // set to true if a stream fails
|
456 |
+
xhr = [];
|
457 |
+
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
|
458 |
+
const testStream = function(i, delay) {
|
459 |
+
setTimeout(
|
460 |
+
function() {
|
461 |
+
if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
|
462 |
+
tverb("ul test stream started " + i + " " + delay);
|
463 |
+
let prevLoaded = 0; // number of bytes transmitted last time onprogress was called
|
464 |
+
let x = new XMLHttpRequest();
|
465 |
+
xhr[i] = x;
|
466 |
+
let ie11workaround;
|
467 |
+
if (settings.forceIE11Workaround) ie11workaround = true;
|
468 |
+
else {
|
469 |
+
try {
|
470 |
+
xhr[i].upload.onprogress;
|
471 |
+
ie11workaround = false;
|
472 |
+
} catch (e) {
|
473 |
+
ie11workaround = true;
|
474 |
+
}
|
475 |
+
}
|
476 |
+
if (ie11workaround) {
|
477 |
+
// IE11 workaround: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
|
478 |
+
xhr[i].onload = xhr[i].onerror = function() {
|
479 |
+
tverb("ul stream progress event (ie11wa)");
|
480 |
+
totLoaded += reqsmall.size;
|
481 |
+
testStream(i, 0);
|
482 |
+
};
|
483 |
+
xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
|
484 |
+
try {
|
485 |
+
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
|
486 |
+
} catch (e) {}
|
487 |
+
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
|
488 |
+
xhr[i].send(reqsmall);
|
489 |
+
} else {
|
490 |
+
// REGULAR version, no workaround
|
491 |
+
xhr[i].upload.onprogress = function(event) {
|
492 |
+
tverb("ul stream progress event " + i + " " + event.loaded);
|
493 |
+
if (testState !== 3) {
|
494 |
+
try {
|
495 |
+
x.abort();
|
496 |
+
} catch (e) {}
|
497 |
+
} // just in case this XHR is still running after the upload test
|
498 |
+
// progress event, add number of new loaded bytes to totLoaded
|
499 |
+
const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
|
500 |
+
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
|
501 |
+
totLoaded += loadDiff;
|
502 |
+
prevLoaded = event.loaded;
|
503 |
+
}.bind(this);
|
504 |
+
xhr[i].upload.onload = function() {
|
505 |
+
// this stream sent all the garbage data, start again
|
506 |
+
tverb("ul stream finished " + i);
|
507 |
+
testStream(i, 0);
|
508 |
+
}.bind(this);
|
509 |
+
xhr[i].upload.onerror = function() {
|
510 |
+
tverb("ul stream failed " + i);
|
511 |
+
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
|
512 |
+
try {
|
513 |
+
xhr[i].abort();
|
514 |
+
} catch (e) {}
|
515 |
+
delete xhr[i];
|
516 |
+
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
|
517 |
+
}.bind(this);
|
518 |
+
// send xhr
|
519 |
+
xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
|
520 |
+
try {
|
521 |
+
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
|
522 |
+
} catch (e) {}
|
523 |
+
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
|
524 |
+
xhr[i].send(req);
|
525 |
+
}
|
526 |
+
}.bind(this),
|
527 |
+
delay
|
528 |
+
);
|
529 |
+
}.bind(this);
|
530 |
+
// open streams
|
531 |
+
for (let i = 0; i < settings.xhr_ulMultistream; i++) {
|
532 |
+
testStream(i, settings.xhr_multistreamDelay * i);
|
533 |
+
}
|
534 |
+
// every 200ms, update ulStatus
|
535 |
+
interval = setInterval(
|
536 |
+
function() {
|
537 |
+
tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
|
538 |
+
const t = new Date().getTime() - startT;
|
539 |
+
if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
|
540 |
+
if (t < 200) return;
|
541 |
+
if (!graceTimeDone) {
|
542 |
+
if (t > 1000 * settings.time_ulGraceTime) {
|
543 |
+
if (totLoaded > 0) {
|
544 |
+
// if the connection is so slow that we didn't get a single chunk yet, do not reset
|
545 |
+
startT = new Date().getTime();
|
546 |
+
bonusT = 0;
|
547 |
+
totLoaded = 0.0;
|
548 |
+
}
|
549 |
+
graceTimeDone = true;
|
550 |
+
}
|
551 |
+
} else {
|
552 |
+
const speed = totLoaded / (t / 1000.0);
|
553 |
+
if (settings.time_auto) {
|
554 |
+
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
|
555 |
+
const bonus = (5.0 * speed) / 100000;
|
556 |
+
bonusT += bonus > 400 ? 400 : bonus;
|
557 |
+
}
|
558 |
+
//update status
|
559 |
+
ulStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
|
560 |
+
if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
|
561 |
+
// test is over, stop streams and timer
|
562 |
+
if (failed || isNaN(ulStatus)) ulStatus = "Fail";
|
563 |
+
clearRequests();
|
564 |
+
clearInterval(interval);
|
565 |
+
ulProgress = 1;
|
566 |
+
tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
|
567 |
+
done();
|
568 |
+
}
|
569 |
+
}
|
570 |
+
}.bind(this),
|
571 |
+
200
|
572 |
+
);
|
573 |
+
}.bind(this);
|
574 |
+
if (settings.mpot) {
|
575 |
+
tverb("Sending POST request before performing upload test");
|
576 |
+
xhr = [];
|
577 |
+
xhr[0] = new XMLHttpRequest();
|
578 |
+
xhr[0].onload = xhr[0].onerror = function() {
|
579 |
+
tverb("POST request sent, starting upload test");
|
580 |
+
testFunction();
|
581 |
+
}.bind(this);
|
582 |
+
xhr[0].open("POST", settings.url_ul);
|
583 |
+
xhr[0].send();
|
584 |
+
} else testFunction();
|
585 |
+
}
|
586 |
+
// ping+jitter test, function done is called when it's over
|
587 |
+
let ptCalled = false; // used to prevent multiple accidental calls to pingTest
|
588 |
+
function pingTest(done) {
|
589 |
+
tverb("pingTest");
|
590 |
+
if (ptCalled) return;
|
591 |
+
else ptCalled = true; // pingTest already called?
|
592 |
+
const startT = new Date().getTime(); //when the test was started
|
593 |
+
let prevT = null; // last time a pong was received
|
594 |
+
let ping = 0.0; // current ping value
|
595 |
+
let jitter = 0.0; // current jitter value
|
596 |
+
let i = 0; // counter of pongs received
|
597 |
+
let prevInstspd = 0; // last ping time, used for jitter calculation
|
598 |
+
xhr = [];
|
599 |
+
// ping function
|
600 |
+
const doPing = function() {
|
601 |
+
tverb("ping");
|
602 |
+
pingProgress = i / settings.count_ping;
|
603 |
+
prevT = new Date().getTime();
|
604 |
+
xhr[0] = new XMLHttpRequest();
|
605 |
+
xhr[0].onload = function() {
|
606 |
+
// pong
|
607 |
+
tverb("pong");
|
608 |
+
if (i === 0) {
|
609 |
+
prevT = new Date().getTime(); // first pong
|
610 |
+
} else {
|
611 |
+
let instspd = new Date().getTime() - prevT;
|
612 |
+
if (settings.ping_allowPerformanceApi) {
|
613 |
+
try {
|
614 |
+
//try to get accurate performance timing using performance api
|
615 |
+
let p = performance.getEntries();
|
616 |
+
p = p[p.length - 1];
|
617 |
+
let d = p.responseStart - p.requestStart;
|
618 |
+
if (d <= 0) d = p.duration;
|
619 |
+
if (d > 0 && d < instspd) instspd = d;
|
620 |
+
} catch (e) {
|
621 |
+
//if not possible, keep the estimate
|
622 |
+
tverb("Performance API not supported, using estimate");
|
623 |
+
}
|
624 |
+
}
|
625 |
+
//noticed that some browsers randomly have 0ms ping
|
626 |
+
if (instspd < 1) instspd = prevInstspd;
|
627 |
+
if (instspd < 1) instspd = 1;
|
628 |
+
const instjitter = Math.abs(instspd - prevInstspd);
|
629 |
+
if (i === 1) ping = instspd;
|
630 |
+
/* first ping, can't tell jitter yet*/ else {
|
631 |
+
if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
|
632 |
+
if (i === 2) jitter = instjitter;
|
633 |
+
//discard the first jitter measurement because it might be much higher than it should be
|
634 |
+
else jitter = instjitter > jitter ? jitter * 0.3 + instjitter * 0.7 : jitter * 0.8 + instjitter * 0.2; // update jitter, weighted average. spikes in ping values are given more weight.
|
635 |
+
}
|
636 |
+
prevInstspd = instspd;
|
637 |
+
}
|
638 |
+
pingStatus = ping.toFixed(2);
|
639 |
+
jitterStatus = jitter.toFixed(2);
|
640 |
+
i++;
|
641 |
+
tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
|
642 |
+
if (i < settings.count_ping) doPing();
|
643 |
+
else {
|
644 |
+
// more pings to do?
|
645 |
+
pingProgress = 1;
|
646 |
+
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
|
647 |
+
done();
|
648 |
+
}
|
649 |
+
}.bind(this);
|
650 |
+
xhr[0].onerror = function() {
|
651 |
+
// a ping failed, cancel test
|
652 |
+
tverb("ping failed");
|
653 |
+
if (settings.xhr_ignoreErrors === 0) {
|
654 |
+
//abort
|
655 |
+
pingStatus = "Fail";
|
656 |
+
jitterStatus = "Fail";
|
657 |
+
clearRequests();
|
658 |
+
tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
|
659 |
+
pingProgress = 1;
|
660 |
+
done();
|
661 |
+
}
|
662 |
+
if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
|
663 |
+
if (settings.xhr_ignoreErrors === 2) {
|
664 |
+
//ignore failed ping
|
665 |
+
i++;
|
666 |
+
if (i < settings.count_ping) doPing();
|
667 |
+
else {
|
668 |
+
// more pings to do?
|
669 |
+
pingProgress = 1;
|
670 |
+
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
|
671 |
+
done();
|
672 |
+
}
|
673 |
+
}
|
674 |
+
}.bind(this);
|
675 |
+
// send xhr
|
676 |
+
xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
|
677 |
+
xhr[0].send();
|
678 |
+
}.bind(this);
|
679 |
+
doPing(); // start first ping
|
680 |
+
}
|
681 |
+
// telemetry
|
682 |
+
function sendTelemetry(done) {
|
683 |
+
if (settings.telemetry_level < 1) return;
|
684 |
+
xhr = new XMLHttpRequest();
|
685 |
+
xhr.onload = function() {
|
686 |
+
try {
|
687 |
+
const parts = xhr.responseText.split(" ");
|
688 |
+
if (parts[0] == "id") {
|
689 |
+
try {
|
690 |
+
let id = parts[1];
|
691 |
+
done(id);
|
692 |
+
} catch (e) {
|
693 |
+
done(null);
|
694 |
+
}
|
695 |
+
} else done(null);
|
696 |
+
} catch (e) {
|
697 |
+
done(null);
|
698 |
+
}
|
699 |
+
};
|
700 |
+
xhr.onerror = function() {
|
701 |
+
console.log("TELEMETRY ERROR " + xhr.status);
|
702 |
+
done(null);
|
703 |
+
};
|
704 |
+
xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
|
705 |
+
const telemetryIspInfo = {
|
706 |
+
processedString: clientIp,
|
707 |
+
rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
|
708 |
+
};
|
709 |
+
try {
|
710 |
+
const fd = new FormData();
|
711 |
+
fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
|
712 |
+
fd.append("dl", dlStatus);
|
713 |
+
fd.append("ul", ulStatus);
|
714 |
+
fd.append("ping", pingStatus);
|
715 |
+
fd.append("jitter", jitterStatus);
|
716 |
+
fd.append("log", settings.telemetry_level > 1 ? log : "");
|
717 |
+
fd.append("extra", settings.telemetry_extra);
|
718 |
+
xhr.send(fd);
|
719 |
+
} catch (ex) {
|
720 |
+
const postData = "extra=" + encodeURIComponent(settings.telemetry_extra) + "&ispinfo=" + encodeURIComponent(JSON.stringify(telemetryIspInfo)) + "&dl=" + encodeURIComponent(dlStatus) + "&ul=" + encodeURIComponent(ulStatus) + "&ping=" + encodeURIComponent(pingStatus) + "&jitter=" + encodeURIComponent(jitterStatus) + "&log=" + encodeURIComponent(settings.telemetry_level > 1 ? log : "");
|
721 |
+
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
|
722 |
+
xhr.send(postData);
|
723 |
+
}
|
724 |
+
}
|