Convert speedtest.js, speedtest_worker.js to ES6

This commit is contained in:
SCG82 2020-09-18 14:33:45 -07:00
parent 5cef820749
commit de7011b7b4
2 changed files with 635 additions and 574 deletions

View file

@ -1,154 +1,178 @@
/* /**
LibreSpeed - Main * @file LibreSpeed - Main
by Federico Dossena * @author Federico Dossena
https://github.com/librespeed/speedtest/ * @license LGPL-3.0-only
GNU LGPLv3 License * https://github.com/librespeed/speedtest/
*/ */
/* /**
This is the main interface between your webpage and the speedtest. * This is the main interface between your webpage and the speedtest.
It hides the speedtest web worker to the page, and provides many convenient functions to control the test. * It hides the speedtest web worker to the page, and provides many convenient functions to control the test.
*
The best way to learn how to use this is to look at the basic example, but here's some documentation. * The best way to learn how to use this is to look at the basic example, but here's some documentation.
*
To initialize the test, create a new Speedtest object: * - To initialize the test, create a new Speedtest object: `const s = new Speedtest();`.
var s=new Speedtest(); *
Now you can think of this as a finite state machine. These are the states (use getState() to see them): * You can think of this as a finite state machine. These are the states (use getState() to see them):
- 0: here you can change the speedtest 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. * - __0__: here you can change the speedtest settings (such as test duration) with the setParameter("parameter",value)
- 1: here you can add test points. You only need to do this if you want to use multiple test points. * method. From here you can either start the test using start() (goes to state 3) or you can add multiple test
A server is defined as an object like this: * 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.
name: "User friendly name", * - __1__: here you can add test points. You only need to do this if you want to use multiple test points.
server:"http://yourBackend.com/", <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol * A server is defined as an object like this:
dlURL:"garbage.php" <----- path to garbage.php or its replacement on the server * ```
ulURL:"empty.php" <----- path to empty.php or its replacement on the server * {
pingURL:"empty.php" <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector * name: "User friendly name",
getIpURL:"getIP.php" <----- path to getIP.php or its replacement on the server * server: "http://yourBackend.com/", // server URL. If both http & https are supported, just use // without protocol
} * dlURL: "garbage.php", // path to garbage.php or its replacement on the server
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. * ulURL: "empty.php", // path to empty.php or its replacement on the server
- 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3 * pingURL: "empty.php", // path to empty.php or its replacement on the server
- 3: test running. Here, your onupdate event calback 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: * getIpURL: "getIP.php", // path to getIP.php or its replacement on the server
- dlStatus: download speed in mbps * }
- ulStatus: upload speed in mbps * ```
- pingStatus: ping in ms * While in state 1, you can only add test points, you cannot change the test settings. When you're done, use
- jitterStatus: jitter in ms * selectServer(callback) to select the test point with the lowest ping. This is asynchronous, when it's done,
- dlProgress: progress of the download test as a float 0-1 * it will call your callback function and move to state 2. Calling setSelectedServer(server) will manually
- ulProgress: progress of the upload test as a float 0-1 * select a server and move to state 2.
- pingProgress: progress of the ping/jitter test as a float 0-1 * - __2__: test point selected, ready to start the test. Use start() to begin, this will move to state 3.
- testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted) * - __3__: test running. Here, your onupdate event calback will be called periodically, with data coming
- clientIp: IP address of the client performing the test (and optionally ISP and distance) * from the worker about speed and progress. A data object will be passed to your onupdate function,
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. * with the following items:
The test can be aborted at any time with abort(). * ```
At the end of the test, it will move to state 4 * {
- 4: test finished. You can run it again by calling start() if you want. * dlStatus: number, // download speed in mbps
* ulStatus: number, // upload speed in mbps
* pingStatus: number, // ping in ms
* jitterStatus: number, // jitter in ms
* dlProgress: number, // progress of the download test as a float 0-1
* ulProgress: number, // progress of the upload test as a float 0-1
* pingProgress: number, // progress of the ping/jitter test as a float 0-1
* testState: number, // -1: not started, 0: starting, 1: download, 2: ping+jitter, 3: upload, 4: finished, 5: aborted
* clientIp: string, // IP address of the client performing the test (and optionally ISP and distance)
* }
* ```
* 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. The test can be aborted at any time with abort().
* At the end of the test, it will move to state 4.
* - __4__: test finished. You can run it again by calling start() if you want.
*/ */
class Speedtest {
function Speedtest() { constructor() {
this._serverList = []; //when using multiple points of test, this is a list of test points this._serverList = []; //when using multiple points of test, this is a list of test points
this._selectedServer = null; //when using multiple points of test, this is the selected server this._selectedServer = null; //when using multiple points of test, this is the selected server
this._settings = {}; //settings for the speedtest worker this._settings = {}; //settings for the speedtest worker
this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
console.log( this.onupdate = undefined;
"LibreSpeed by Federico Dossena v5.2.1 - https://github.com/librespeed/speedtest" this.onend = undefined;
); console.log("LibreSpeed by Federico Dossena v5.2 - https://github.com/librespeed/speedtest");
} }
Speedtest.prototype = {
constructor: Speedtest,
/** /**
* Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done * Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
* @returns {number} 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
*/ */
getState: function() { getState() {
return this._state; return this._state;
}, }
/** /**
* Change one of the test settings from their defaults. * Change one of the test settings from their defaults.
* - parameter: string with the name of the parameter that you want to set
* - value: new value for the parameter
*
* Invalid values or nonexistant parameters will be ignored by the speedtest worker. * Invalid values or nonexistant parameters will be ignored by the speedtest worker.
* @param {string} parameter - string with the name of the parameter that you want to set
* @param value - new value for the parameter
*/ */
setParameter: function(parameter, value) { setParameter(parameter, value) {
if (this._state != 0) if (this._state !== 0)
throw "You cannot change the test settings after adding server or starting the test"; throw new Error("You cannot change the test settings after adding server or starting the test");
this._settings[parameter] = value; this._settings[parameter] = value;
if (parameter === "telemetry_extra") { if (parameter === "telemetry_extra") {
this._originalExtra = this._settings.telemetry_extra; this._originalExtra = this._settings.telemetry_extra;
} }
}, }
/** /**
* Used internally to check if a server object contains all the required elements. * Used internally to check if a server object contains all the required elements.
* Also fixes the server URL if needed. * Also fixes the server URL if needed.
* @param {Server} server
*/ */
_checkServerDefinition: function(server) { _checkServerDefinition(server) {
try { try {
if (typeof server.name !== "string") if (typeof server.name !== "string")
throw "Name string missing from server definition (name)"; throw new Error("Name string missing from server definition (name)");
if (typeof server.server !== "string") if (typeof server.server !== "string")
throw "Server address string missing from server definition (server)"; throw new Error("Server address string missing from server definition (server)");
if (server.server.charAt(server.server.length - 1) != "/") if (server.server.charAt(server.server.length - 1) !== "/")
server.server += "/"; server.server += "/";
if (server.server.indexOf("//") == 0) if (server.server.indexOf("//") === 0)
server.server = location.protocol + server.server; server.server = location.protocol + server.server;
if (typeof server.dlURL !== "string") if (typeof server.dlURL !== "string")
throw "Download URL string missing from server definition (dlURL)"; throw new Error("Download URL string missing from server definition (dlURL)");
if (typeof server.ulURL !== "string") if (typeof server.ulURL !== "string")
throw "Upload URL string missing from server definition (ulURL)"; throw new Error("Upload URL string missing from server definition (ulURL)");
if (typeof server.pingURL !== "string") if (typeof server.pingURL !== "string")
throw "Ping URL string missing from server definition (pingURL)"; throw new Error("Ping URL string missing from server definition (pingURL)");
if (typeof server.getIpURL !== "string") if (typeof server.getIpURL !== "string")
throw "GetIP URL string missing from server definition (getIpURL)"; throw new Error("GetIP URL string missing from server definition (getIpURL)");
} catch (e) { } catch (e) {
throw "Invalid server definition"; throw new Error(`Invalid server definition: ${e.message}`);
} }
}, }
/** /**
* Add a test point (multiple points of test) * Add a test point (multiple points of test)
* server: the server to be added as an object. Must contain the following elements: * @param {Server} server - the server to be added as an object. Must contain the following elements:
* { * ```
* name: "User friendly name", * name: "User friendly name"
* server:"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol * server: "http://yourBackend.com/" // server URL. If both http & https are supported, just use // without protocol
* dlURL:"garbage.php" path to garbage.php or its replacement on the server * dlURL: "garbage.php" // path to garbage.php or its replacement on the server
* ulURL:"empty.php" path to empty.php or its replacement on the server * ulURL: "empty.php" // path to empty.php or its replacement on the server
* pingURL:"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector * pingURL: "empty.php" // path to empty.php or its replacement on the server
* getIpURL:"getIP.php" path to getIP.php or its replacement on the server * getIpURL: "getIP.php" // path to getIP.php or its replacement on the server
* } * ```
*/ */
addTestPoint: function(server) { addTestPoint(server) {
this._checkServerDefinition(server); this._checkServerDefinition(server);
if (this._state == 0) this._state = 1; if (this._state === 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection"; if (this._state !== 1) throw new Error("You can't add a server after server selection");
this._settings.mpot = true; this._settings.mpot = true;
this._serverList.push(server); this._serverList.push(server);
}, }
/** /**
* Same as addTestPoint, but you can pass an array of servers * Same as `addTestPoint`, but you can pass an array of servers
* @param {Server[]} list - array of server objects
*/ */
addTestPoints: function(list) { addTestPoints(list) {
for (var i = 0; i < list.length; i++) this.addTestPoint(list[i]); for (let i = 0; i < list.length; i++) {
}, this.addTestPoint(list[i]);
}
}
/** /**
* Load a JSON server list from URL (multiple points of test) * Load a JSON server list from URL (multiple points of test)
* url: the url where the server list can be fetched. Must be an array with objects containing the following elements: * @param {string} url - the url where the server list can be fetched.
* { * Must be an array with objects containing the following elements:
* "name": "User friendly name", * ```
* "server":"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol * name: "User friendly name",
* "dlURL":"garbage.php" path to garbage.php or its replacement on the server * server: "http://yourBackend.com/", // server URL. If both http & https are supported, just use // without protocol
* "ulURL":"empty.php" path to empty.php or its replacement on the server * dlURL: "garbage.php", // path to garbage.php or its replacement on the server
* "pingURL":"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector * ulURL: "empty.php", // path to empty.php or its replacement on the server
* "getIpURL":"getIP.php" path to getIP.php or its replacement on the server * pingURL: "empty.php", // path to empty.php or its replacement on the server
* } * getIpURL: "getIP.php", // path to getIP.php or its replacement on the server
* 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 * ```
* @param {(x: Server[] | null) => void} 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.
*/ */
loadServerList: function(url,result) { loadServerList(url, result) {
if (this._state == 0) this._state = 1; if (this._state === 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection"; if (this._state !== 1) throw new Error("You can't add a server after server selection");
this._settings.mpot = true; this._settings.mpot = true;
var xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.onload = function(){ xhr.onload = () => {
try { try {
var servers=JSON.parse(xhr.responseText); /** @type {Server[]} */
for(var i=0;i<servers.length;i++){ const servers = JSON.parse(xhr.responseText);
for (let i = 0; i < servers.length; i++){
this._checkServerDefinition(servers[i]); this._checkServerDefinition(servers[i]);
} }
this.addTestPoints(servers); this.addTestPoints(servers);
@ -156,73 +180,100 @@ Speedtest.prototype = {
} catch (e) { } catch (e) {
result(null); result(null);
} }
}.bind(this); };
xhr.onerror = function(){result(null);} xhr.onerror = () => { result(null); };
xhr.open("GET", url); xhr.open("GET", url);
xhr.send(); xhr.send();
}, }
/** /**
* Returns the selected server (multiple points of test) * Returns the selected server (multiple points of test)
*/ */
getSelectedServer: function() { getSelectedServer() {
if (this._state < 2 || this._selectedServer == null) if (this._state < 2 || this._selectedServer == null) throw new Error("No server is selected");
throw "No server is selected";
return this._selectedServer; return this._selectedServer;
}, }
/**
* @typedef {Object} Server
* @property {string} name user friendly name
* @property {string} server URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
* @property {string} dlURL path to __garbage.php__ or its replacement on the server
* @property {string} ulURL path to __empty.php__ or its replacement on the server
* @property {string} pingURL path to __empty.php__ or its replacement on the server. This is used to ping the server by this selector
* @property {string} getIpURL path to __getIP.php__ or its replacement on the server
* @property {number} pingT calculated (do not set). either the best ping we got from the server or -1 if something went wrong.
*/
/** /**
* Manually selects one of the test points (multiple points of test) * Manually selects one of the test points (multiple points of test)
* @param {Server} server
*/ */
setSelectedServer: function(server) { setSelectedServer(server) {
this._checkServerDefinition(server); this._checkServerDefinition(server);
if (this._state == 3) if (this._state === 3) throw new Error("You can't select a server while the test is running");
throw "You can't select a server while the test is running";
this._selectedServer = server; this._selectedServer = server;
this._state = 2; this._state = 2;
},
/**
* Automatically selects a server from the list of added test points. The server with the lowest ping will be chosen. (multiple points of test)
* The process is asynchronous and the passed result callback function will be called when it's done, then the test can be started.
*/
selectServer: function(result) {
if (this._state != 1) {
if (this._state == 0) throw "No test points added";
if (this._state == 2) throw "Server already selected";
if (this._state >= 3)
throw "You can't select a server while the test is running";
} }
if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
/*this function goes through a list of servers. For each server, the ping is measured, then the server with the function result is called with the best server, or null if all the servers were down. /**
* Automatically selects a server from the list of added test points.
* The server with the lowest ping will be chosen (multiple points of test).
* The process is asynchronous and the passed result callback function will
* be called when it's done, then the test can be started.
* @param {(x: Server) => void} result
*/ */
var select = function(serverList, result) { selectServer(result) {
//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. if (this._state !== 1) {
var PING_TIMEOUT = 2000; if (this._state === 0) throw new Error("No test points added");
var USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers if (this._state === 2) throw new Error("Server already selected");
if (this._state >= 3) throw new Error("You can't select a server while the test is running");
}
if (this._selectServerCalled) throw new Error("selectServer already called");
else this._selectServerCalled = true;
/**
* This function goes through a list of servers. For each server, the ping is measured,
* then the server with the function result is called with the best server,
* or null if all the servers were down.
* @param {Server[]} serverList
* @param {(x: Server | null) => void} result parameter is either the best server or null if all servers were down
*/
const select = (serverList, result) => {
const PING_TIMEOUT = 2000;
// will be disabled on unsupported browsers
let USE_PING_TIMEOUT = true;
if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) { if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
// IE11 doesn't support XHR timeout // IE11 doesn't support XHR timeout
USE_PING_TIMEOUT = false; USE_PING_TIMEOUT = false;
} }
var ping = function(url, result) { /**
* 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.
* @param {string} url
* @param {(pingMs: number) => void} result parameter is either the time it took to ping the URL, or -1 if something went wrong
*/
const ping = (url, result) => {
url += (url.match(/\?/) ? "&" : "?") + "cors=true"; url += (url.match(/\?/) ? "&" : "?") + "cors=true";
var xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
var t = new Date().getTime(); const t = new Date().getTime();
xhr.onload = function() { xhr.onload = () => {
if (xhr.responseText.length == 0) { // We expect an empty response
//we expect an empty response if (xhr.responseText.length === 0) {
var instspd = new Date().getTime() - t; //rough timing estimate // Rough timing estimate
let instspd = new Date().getTime() - t;
try { try {
//try to get more accurate timing using performance API // Try to get more accurate timing using Performance API
var p = performance.getEntriesByName(url); const pArr = performance.getEntriesByName(url);
p = p[p.length - 1]; const p = pArr[pArr.length - 1];
var d = p.responseStart - p.requestStart; let d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration; if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d; if (d > 0 && d < instspd) instspd = d;
} catch (e) {} } catch (e) {}
result(instspd); result(instspd);
} else result(-1); } else {
}.bind(this);
xhr.onerror = function() {
result(-1); result(-1);
}.bind(this); }
};
xhr.onerror = () => { result(-1); };
xhr.open("GET", url); xhr.open("GET", url);
if (USE_PING_TIMEOUT) { if (USE_PING_TIMEOUT) {
try { try {
@ -231,149 +282,139 @@ Speedtest.prototype = {
} catch (e) {} } catch (e) {}
} }
xhr.send(); xhr.send();
}.bind(this); };
const PINGS = 3; // up to 3 pings are performed, unless the server is down...
//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. const SLOW_THRESHOLD = 500; // ...or one of the pings is above this threshold
var PINGS = 3, //up to 3 pings are performed, unless the server is down... /**
SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold * This function repeatedly pings a server to get a good estimate of the ping.
var checkServer = function(server, done) { * When it's done, it calls the done function without parameters.
var i = 0; * 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.
* @param {Server} server
* @param {() => void} done
*/
const checkServer = (server, done) => {
let i = 0;
server.pingT = -1; server.pingT = -1;
if (server.server.indexOf(location.protocol) == -1) done(); if (server.server.indexOf(location.protocol) === -1) return void done();
else { const nextPing = () => {
var nextPing = function() { if (i++ === PINGS) return void done();
if (i++ == PINGS) {
done();
return;
}
ping( ping(
server.server + server.pingURL, server.server + server.pingURL,
function(t) { (t) => {
if (t >= 0) { if (t >= 0) {
if (t < server.pingT || server.pingT == -1) server.pingT = t; if (t < server.pingT || server.pingT === -1) server.pingT = t;
if (t < SLOW_THRESHOLD) nextPing(); if (t < SLOW_THRESHOLD) nextPing();
else done(); else done();
} else done(); } else {
}.bind(this) done();
);
}.bind(this);
nextPing();
} }
}.bind(this); }
//check servers in list, one by one );
var i = 0; };
var done = function() { nextPing();
var bestServer = null; };
for (var i = 0; i < serverList.length; i++) { let index = 0;
if ( /**
serverList[i].pingT != -1 && * Check servers in list, one by one
(bestServer == null || serverList[i].pingT < bestServer.pingT) */
) const done = () => {
let bestServer = null;
for (let i = 0; i < serverList.length; i++) {
if (serverList[i].pingT !== -1 && (!bestServer || serverList[i].pingT < bestServer.pingT)) {
bestServer = serverList[i]; bestServer = serverList[i];
} }
result(bestServer); index++;
}.bind(this);
var nextServer = function() {
if (i == serverList.length) {
done();
return;
} }
checkServer(serverList[i++], nextServer); result(bestServer);
}.bind(this); };
const nextServer = () => {
if (index === serverList.length) return void done();
checkServer(serverList[index++], nextServer);
};
nextServer(); nextServer();
}.bind(this); };
// Parallel server selection
//parallel server selection const CONCURRENCY = 6;
var CONCURRENCY = 6; const serverLists = [];
var serverLists = []; for (let i = 0; i < CONCURRENCY; i++) {
for (var i = 0; i < CONCURRENCY; i++) {
serverLists[i] = []; serverLists[i] = [];
} }
for (var i = 0; i < this._serverList.length; i++) { for (let i = 0; i < this._serverList.length; i++) {
serverLists[i % CONCURRENCY].push(this._serverList[i]); serverLists[i % CONCURRENCY].push(this._serverList[i]);
} }
var completed = 0; let completed = 0;
var bestServer = null; /** @type {Server} */
for (var i = 0; i < CONCURRENCY; i++) { let bestServer = null;
for (let i = 0; i < CONCURRENCY; i++) {
select( select(
serverLists[i], serverLists[i],
function(server) { (server) => {
if (server != null) { if (server && (!bestServer || server.pingT < bestServer.pingT)) {
if (bestServer == null || server.pingT < bestServer.pingT)
bestServer = server; bestServer = server;
} }
completed++; completed++;
if (completed == CONCURRENCY) { if (completed === CONCURRENCY) {
this._selectedServer = bestServer; this._selectedServer = bestServer;
this._state = 2; this._state = 2;
if (result) result(bestServer); if (result) result(bestServer);
} }
}.bind(this) }
); );
} }
}, }
/** /**
* Starts the test. * Starts the test.
* During the test, the onupdate(data) callback function will be called periodically with data from the worker. * During the test, the onupdate(data) callback function will be called periodically
* 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. * with data from the worker. 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.
*/ */
start: function() { start() {
if (this._state == 3) throw "Test already running"; if (this._state === 3) throw new Error("Test already running");
this.worker = new Worker("speedtest_worker.js?r=" + Math.random()); this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
this.worker.onmessage = function(e) { this.worker.onmessage = (e) => {
if (e.data === this._prevData) return; if (e.data === this._prevData) return;
else this._prevData = e.data; this._prevData = e.data;
var data = JSON.parse(e.data); const data = JSON.parse(e.data);
try { try {
if (this.onupdate) this.onupdate(data); if (this.onupdate) this.onupdate(data);
} catch (e) { } catch (e) {
console.error("Speedtest onupdate event threw exception: " + e); console.error("Speedtest onupdate event threw exception: " + e);
} }
if (data.testState >= 4) { if (data.testState >= 4) {
clearInterval(this.updater);
this._state = 4;
try { try {
if (this.onend) this.onend(data.testState == 5); if (this.onend) this.onend(data.testState === 5);
} catch (e) { } catch (e) {
console.error("Speedtest onend event threw exception: " + e); console.error("Speedtest onend event threw exception: " + e);
} }
clearInterval(this.updater);
this._state = 4;
} }
}.bind(this); };
this.updater = setInterval( this.updater = setInterval(() => { this.worker.postMessage("status"); }, 200);
function() { if (this._state === 1) {
this.worker.postMessage("status"); throw new Error("When using multiple points of test, you must call selectServer before starting the test");
}.bind(this), }
200 if (this._state === 2) {
); this._settings.url_dl = this._selectedServer.server + this._selectedServer.dlURL;
if (this._state == 1) this._settings.url_ul = this._selectedServer.server + this._selectedServer.ulURL;
throw "When using multiple points of test, you must call selectServer before starting the test"; this._settings.url_ping = this._selectedServer.server + this._selectedServer.pingURL;
if (this._state == 2) { this._settings.url_getIp = this._selectedServer.server + this._selectedServer.getIpURL;
this._settings.url_dl =
this._selectedServer.server + this._selectedServer.dlURL;
this._settings.url_ul =
this._selectedServer.server + this._selectedServer.ulURL;
this._settings.url_ping =
this._selectedServer.server + this._selectedServer.pingURL;
this._settings.url_getIp =
this._selectedServer.server + this._selectedServer.getIpURL;
if (typeof this._originalExtra !== "undefined") {
this._settings.telemetry_extra = JSON.stringify({ this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name, server: this._selectedServer.name,
extra: this._originalExtra extra: this._originalExtra ? this._originalExtra : undefined
});
} else
this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name
}); });
} }
this._state = 3; this._state = 3;
this.worker.postMessage("start " + JSON.stringify(this._settings)); this.worker.postMessage("start " + JSON.stringify(this._settings));
}, }
/** /**
* Aborts the test while it's running. * Aborts the test while it's running.
*/ */
abort: function() { abort() {
if (this._state < 3) throw "You cannot abort a test that's not started yet"; if (this._state < 3) throw new Error("You cannot abort a test that's not started yet");
if (this._state < 4) this.worker.postMessage("abort"); if (this._state < 4) this.worker.postMessage("abort");
} }
}; }

View file

@ -1,33 +1,42 @@
/* /**
LibreSpeed - Worker * @file LibreSpeed - Worker
by Federico Dossena * @author Federico Dossena
https://github.com/librespeed/speedtest/ * @license LGPL-3.0-only
GNU LGPLv3 License * @see https://github.com/librespeed/speedtest/
*/ */
// data reported to main thread // data reported to main thread
var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort let testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
var dlStatus = ""; // download speed in megabit/s with 2 decimal digits let dlStatus = 0; // download speed in megabit/s with 2 decimal digits
var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits let ulStatus = 0; // upload speed in megabit/s with 2 decimal digits
var pingStatus = ""; // ping in milliseconds with 2 decimal digits let pingStatus = 0; // ping in milliseconds with 2 decimal digits
var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits let jitterStatus = 0; // jitter in milliseconds with 2 decimal digits
var clientIp = ""; // client's IP address as reported by getIP.php let clientIp = ""; // client's IP address as reported by getIP.php
var dlProgress = 0; //progress of download test 0-1 let dlProgress = 0; // progress of download test 0-1
var ulProgress = 0; //progress of upload test 0-1 let ulProgress = 0; // progress of upload test 0-1
var pingProgress = 0; //progress of ping+jitter test 0-1 let pingProgress = 0; // progress of ping+jitter test 0-1
var testId = null; //test ID (sent back by telemetry if used, null otherwise) let testId = null; // test ID (sent back by telemetry if used, null otherwise)
var log = ""; //telemetry log let log = ""; // telemetry log
/**
* @param {string} s
*/
function tlog(s) { function tlog(s) {
if (settings.telemetry_level >= 2) { if (settings.telemetry_level >= 2) {
log += Date.now() + ": " + s + "\n"; log += Date.now() + ": " + s + "\n";
} }
} }
/**
* @param {string} s
*/
function tverb(s) { function tverb(s) {
if (settings.telemetry_level >= 3) { if (settings.telemetry_level >= 3) {
log += Date.now() + ": " + s + "\n"; log += Date.now() + ": " + s + "\n";
} }
} }
/**
* @param {string} s
*/
function twarn(s) { function twarn(s) {
if (settings.telemetry_level >= 2) { if (settings.telemetry_level >= 2) {
log += Date.now() + " WARN: " + s + "\n"; log += Date.now() + " WARN: " + s + "\n";
@ -35,8 +44,10 @@ function twarn(s) {
console.warn(s); console.warn(s);
} }
// test settings. can be overridden by sending specific values with the start command /**
var settings = { * Test settings - can be overridden by sending specific values with the start command
*/
const settings = {
mpot: false, // set to true when in MPOT mode mpot: false, // set to true when in MPOT mode
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 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
time_ul_max: 15, // max duration of upload test in seconds time_ul_max: 15, // max duration of upload test in seconds
@ -67,27 +78,23 @@ var settings = {
telemetry_extra: "" // extra data that can be passed to the telemetry through the settings telemetry_extra: "" // extra data that can be passed to the telemetry through the settings
}; };
var xhr = null; // array of currently active xhr requests /** @type {XMLHttpRequest[]} */
var interval = null; // timer used in tests let xhr = null; // array of currently active xhr requests
var test_pointer = 0; //pointer to the next test to run inside settings.test_order /** @type {number} */
let interval = null; // timer used in tests
let test_pointer = 0; // pointer to the next test to run inside settings.test_order
/* /**
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator * listener for commands from main thread to this worker.
* commands:
* - status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
* - abort: aborts the current test
* - start: starts the test. optionally, settings can be passed as JSON.
* @example
* start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
*/ */
function url_sep(url) { self.addEventListener("message", (e) => {
return url.match(/\?/) ? "&" : "?"; const params = e.data.split(" ");
}
/*
listener for commands from main thread to this worker.
commands:
-status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
-abort: aborts the current test
-start: starts the test. optionally, settings can be passed as JSON.
example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
*/
this.addEventListener("message", function(e) {
var params = e.data.split(" ");
if (params[0] === "status") { if (params[0] === "status") {
// return status // return status
postMessage( postMessage(
@ -110,21 +117,21 @@ this.addEventListener("message", function(e) {
testState = 0; testState = 0;
try { try {
// parse settings, if present // parse settings, if present
var s = {}; let s = {};
try { try {
var ss = e.data.substring(5); const ss = e.data.substring(5);
if (ss) s = JSON.parse(ss); if (ss) s = JSON.parse(ss);
} catch (e) { } catch (e) {
twarn("Error parsing custom settings JSON. Please check your syntax"); twarn("Error parsing custom settings JSON. Please check your syntax");
} }
// copy custom settings // copy custom settings
for (var key in s) { for (const key in s) {
if (typeof settings[key] !== "undefined") settings[key] = s[key]; if (typeof settings[key] !== "undefined") settings[key] = s[key];
else twarn("Unknown setting ignored: " + key); else twarn("Unknown setting ignored: " + key);
} }
var ua = navigator.userAgent; const ua = navigator.userAgent;
// quirks for specific browsers. apply only if not overridden. more may be added in future releases // quirks for specific browsers. apply only if not overridden. more may be added in future releases
if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) { if (settings.enable_quirks || typeof s.enable_quirks !== "undefined" && s.enable_quirks) {
if (/Firefox.(\d+\.\d+)/i.test(ua)) { if (/Firefox.(\d+\.\d+)/i.test(ua)) {
if (typeof s.ping_allowPerformanceApi === "undefined") { if (typeof s.ping_allowPerformanceApi === "undefined") {
// ff performance API sucks // ff performance API sucks
@ -161,8 +168,10 @@ this.addEventListener("message", function(e) {
// Safari also needs the IE11 workaround but only for the MPOT version // Safari also needs the IE11 workaround but only for the MPOT version
settings.forceIE11Workaround = true; settings.forceIE11Workaround = true;
} }
if (typeof s.telemetry_level !== "undefined") {
// telemetry_level has to be parsed and not just copied // telemetry_level has to be parsed and not just copied
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 settings.telemetry_level = s.telemetry_level === "basic" ? 1 : s.telemetry_level === "full" ? 2 : s.telemetry_level === "debug" ? 3 : 0;
}
// transform test_order to uppercase, just in case // transform test_order to uppercase, just in case
settings.test_order = settings.test_order.toUpperCase(); settings.test_order = settings.test_order.toUpperCase();
} catch (e) { } catch (e) {
@ -171,71 +180,55 @@ this.addEventListener("message", function(e) {
// run the tests // run the tests
tverb(JSON.stringify(settings)); tverb(JSON.stringify(settings));
test_pointer = 0; test_pointer = 0;
var iRun = false, let iRun = false;
dRun = false, let dRun = false;
uRun = false, let uRun = false;
pRun = false; let pRun = false;
var runNextTest = function() { const runNextTest = () => {
if (testState == 5) return; if (testState === 5) return;
if (test_pointer >= settings.test_order.length) { if (test_pointer >= settings.test_order.length) {
// test is finished // test is finished
if (settings.telemetry_level > 0) if (settings.telemetry_level > 0) {
sendTelemetry(function(id) { sendTelemetry((id) => {
testState = 4; testState = 4;
if (id != null) testId = id; if (id != null) testId = id;
}); });
else testState = 4; } else {
testState = 4;
}
return; return;
} }
switch (settings.test_order.charAt(test_pointer)) { switch (settings.test_order.charAt(test_pointer)) {
case "I": case "I":
{
test_pointer++; test_pointer++;
if (iRun) { if (iRun) return void runNextTest();
runNextTest(); iRun = true;
return;
} else iRun = true;
getIp(runNextTest); getIp(runNextTest);
}
break; break;
case "D": case "D":
{
test_pointer++; test_pointer++;
if (dRun) { if (dRun) return void runNextTest();
runNextTest(); dRun = true;
return;
} else dRun = true;
testState = 1; testState = 1;
dlTest(runNextTest); dlTest(runNextTest);
}
break; break;
case "U": case "U":
{
test_pointer++; test_pointer++;
if (uRun) { if (uRun) return void runNextTest();
runNextTest(); uRun = true;
return;
} else uRun = true;
testState = 3; testState = 3;
ulTest(runNextTest); ulTest(runNextTest);
}
break; break;
case "P": case "P":
{
test_pointer++; test_pointer++;
if (pRun) { if (pRun) return void runNextTest();
runNextTest(); pRun = true;
return;
} else pRun = true;
testState = 2; testState = 2;
pingTest(runNextTest); pingTest(runNextTest);
}
break; break;
case "_": case "_":
{
test_pointer++; test_pointer++;
setTimeout(runNextTest, 1000); setTimeout(runNextTest, 1000);
}
break; break;
default: default:
test_pointer++; test_pointer++;
@ -245,28 +238,30 @@ this.addEventListener("message", function(e) {
} }
if (params[0] === "abort") { if (params[0] === "abort") {
// abort command // abort command
if (testState >= 4) return; if (testState >= 4) return; // test finished
tlog("manually aborted"); tlog("manually aborted");
clearRequests(); // stop all xhr activity clearRequests(); // stop all xhr activity
runNextTest = null;
if (interval) clearInterval(interval); // clear timer if present if (interval) clearInterval(interval); // clear timer if present
if (settings.telemetry_level > 1) sendTelemetry(function() {}); if (settings.telemetry_level > 1) sendTelemetry(() => {});
testState = 5; // set test as aborted testState = 5; // set test as aborted
dlStatus = ""; dlStatus = 0;
ulStatus = ""; ulStatus = 0;
pingStatus = ""; pingStatus = 0;
jitterStatus = ""; jitterStatus = 0;
clientIp = ""; clientIp = "";
dlProgress = 0; dlProgress = 0;
ulProgress = 0; ulProgress = 0;
pingProgress = 0; pingProgress = 0;
} }
}); });
// stops all XHR activity, aggressively
/**
* stops all XHR activity, aggressively
*/
function clearRequests() { function clearRequests() {
tverb("stopping pending XHRs"); tverb("stopping pending XHRs");
if (xhr) { if (xhr) {
for (var i = 0; i < xhr.length; i++) { for (let i = 0; i < xhr.length; i++) {
try { try {
xhr[i].onprogress = null; xhr[i].onprogress = null;
xhr[i].onload = null; xhr[i].onload = null;
@ -277,29 +272,29 @@ function clearRequests() {
xhr[i].upload.onload = null; xhr[i].upload.onload = null;
xhr[i].upload.onerror = null; xhr[i].upload.onerror = null;
} catch (e) {} } catch (e) {}
try { try { xhr[i].abort(); } catch (e) {}
xhr[i].abort(); try { delete xhr[i]; } catch (e) {}
} catch (e) {}
try {
delete xhr[i];
} catch (e) {}
} }
xhr = null; xhr = null;
} }
} }
// gets client's IP using url_getIp, then calls the done function
var ipCalled = false; // used to prevent multiple accidental calls to getIp let ipCalled = false; // used to prevent multiple accidental calls to getIp
var ispInfo = ""; //used for telemetry let ispInfo = ""; // used for telemetry
/**
* gets client's IP using `url_getIp`, then calls the `done()` function
* @param {() => void} done
*/
function getIp(done) { function getIp(done) {
tverb("getIp"); tverb("getIp");
if (ipCalled) return; if (ipCalled) return;
else ipCalled = true; // getIp already called? ipCalled = true; // getIp already called?
var startT = new Date().getTime(); const startT = new Date().getTime();
xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.onload = function() { xhr.onload = () => {
tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms"); tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
try { try {
var data = JSON.parse(xhr.responseText); const data = JSON.parse(xhr.responseText);
clientIp = data.processedString; clientIp = data.processedString;
ispInfo = data.rawIspInfo; ispInfo = data.rawIspInfo;
} catch (e) { } catch (e) {
@ -308,65 +303,66 @@ function getIp(done) {
} }
done(); done();
}; };
xhr.onerror = function() { xhr.onerror = () => {
tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms"); tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
done(); done();
}; };
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); 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);
xhr.send(); xhr.send();
} }
// download test, calls done function when it's over
var dlCalled = false; // used to prevent multiple accidental calls to dlTest let dlCalled = false; // used to prevent multiple accidental calls to dlTest
/**
* download test, calls done function when it's over
* @param {() => void} done
*/
function dlTest(done) { function dlTest(done) {
tverb("dlTest"); tverb("dlTest");
if (dlCalled) return; if (dlCalled) return;
else dlCalled = true; // dlTest already called? dlCalled = true; // dlTest already called?
var totLoaded = 0.0, // total number of loaded bytes let totLoaded = 0.0; // total number of loaded bytes
startT = new Date().getTime(), // timestamp when test was started let startT = new Date().getTime(); // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections) let bonusT = 0; // how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past let graceTimeDone = false; // set to true after the grace time is past
failed = false; // set to true if a stream fails let failed = false; // set to true if a stream fails
xhr = []; xhr = [];
// function to create a download stream. streams are slightly delayed so that they will not end at the same time /**
var testStream = function(i, delay) { * function to create a download stream. streams are slightly delayed so that they will not end at the same time
* @param {number} i
* @param {number} delay
*/
const testStream = (i, delay) => {
setTimeout( setTimeout(
function() { () => {
if (testState !== 1) return; // delayed stream ended up starting after the end of the download test if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
tverb("dl test stream started " + i + " " + delay); tverb("dl test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes loaded last time onprogress was called let prevLoaded = 0; // number of bytes loaded last time onprogress was called
var x = new XMLHttpRequest(); const x = new XMLHttpRequest();
xhr[i] = x; xhr[i] = x;
xhr[i].onprogress = function(event) { xhr[i].onprogress = (event) => {
tverb("dl stream progress event " + i + " " + event.loaded); tverb("dl stream progress event " + i + " " + event.loaded);
if (testState !== 1) { // just in case this XHR is still running after the download test
try { if (testState !== 1) try { x.abort(); } catch (e) {}
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the download test
// progress event, add number of new loaded bytes to totLoaded // progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded; const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff; totLoaded += loadDiff;
prevLoaded = event.loaded; prevLoaded = event.loaded;
}.bind(this); };
xhr[i].onload = function() { xhr[i].onload = () => {
// the large file has been loaded entirely, start again // the large file has been loaded entirely, start again
tverb("dl stream finished " + i); tverb("dl stream finished " + i);
try { try { xhr[i].abort(); } catch (e) {} // reset the stream data to empty ram
xhr[i].abort();
} catch (e) {} // reset the stream data to empty ram
testStream(i, 0); testStream(i, 0);
}.bind(this); };
xhr[i].onerror = function() { xhr[i].onerror = () => {
// error // error
tverb("dl stream failed " + i); tverb("dl stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; // abort if (settings.xhr_ignoreErrors === 0) failed = true; // abort
try { try { xhr[i].abort(); } catch (e) {}
xhr[i].abort();
} catch (e) {}
delete xhr[i]; delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); // restart stream if (settings.xhr_ignoreErrors === 1) testStream(i, 0); // restart stream
}.bind(this); };
// send xhr // send xhr
try { try {
if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob"; if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
@ -374,19 +370,19 @@ function dlTest(done) {
} catch (e) {} } catch (e) {}
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 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
xhr[i].send(); xhr[i].send();
}.bind(this), },
1 + delay 1 + delay
); );
}.bind(this); };
// open streams // open streams
for (var i = 0; i < settings.xhr_dlMultistream; i++) { for (let i = 0; i < settings.xhr_dlMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i); testStream(i, settings.xhr_multistreamDelay * i);
} }
// every 200ms, update dlStatus // every 200ms, update dlStatus
interval = setInterval( interval = setInterval(
function() { () => {
tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)")); tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT; const t = new Date().getTime() - startT;
if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000); if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
if (t < 200) return; if (t < 200) return;
if (!graceTimeDone) { if (!graceTimeDone) {
@ -400,71 +396,86 @@ function dlTest(done) {
graceTimeDone = true; graceTimeDone = true;
} }
} else { } else {
var speed = totLoaded / (t / 1000.0); const speed = totLoaded / (t / 1000.0);
if (settings.time_auto) { if (settings.time_auto) {
// decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here // decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (6.4 * speed) / 100000; const bonus = 6.4 * speed / 100000;
bonusT += bonus > 800 ? 800 : bonus; bonusT += bonus > 800 ? 800 : bonus;
} }
// update status // update status
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 dlStatus = Number((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
if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) { if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
// test is over, stop streams and timer // test is over, stop streams and timer
if (failed || isNaN(dlStatus)) dlStatus = "Fail"; if (failed || isNaN(dlStatus)) dlStatus = -1;
clearRequests(); clearRequests();
clearInterval(interval); clearInterval(interval);
dlProgress = 1; dlProgress = 1;
tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms"); tlog(`dlTest: ${dlStatus < 0 ? "Fail" : dlStatus}, took ${new Date().getTime() - startT}ms`);
done(); done();
} }
} }
}.bind(this), },
200 200
); );
} }
// upload test, calls done function whent it's over
var ulCalled = false; // used to prevent multiple accidental calls to ulTest let ulCalled = false; // used to prevent multiple accidental calls to ulTest
/**
* upload test, calls done function when it's over
* @param {() => void} done
*/
function ulTest(done) { function ulTest(done) {
tverb("ulTest"); tverb("ulTest");
if (ulCalled) return; if (ulCalled) return;
else ulCalled = true; // ulTest already called? ulCalled = true; // ulTest already called?
// garbage data for upload test // garbage data for upload test
var r = new ArrayBuffer(1048576); let r = new ArrayBuffer(1048576);
var maxInt = Math.pow(2, 32) - 1; const maxInt = Math.pow(2, 32) - 1;
try { try {
r = new Uint32Array(r); r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt; for (let i = 0; i < r.length; i++) {
r[i] = Math.random() * maxInt;
}
} catch (e) {} } catch (e) {}
var req = []; const req = [];
var reqsmall = []; const reqsmall = [];
for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r); for (let i = 0; i < settings.xhr_ul_blob_megabytes; i++) {
req = new Blob(req); req.push(r);
}
const request = new Blob(req);
r = new ArrayBuffer(262144); r = new ArrayBuffer(262144);
try { try {
r = new Uint32Array(r); r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt; for (let i = 0; i < r.length; i++) {
r[i] = Math.random() * maxInt;
}
} catch (e) {} } catch (e) {}
reqsmall.push(r); reqsmall.push(r);
reqsmall = new Blob(reqsmall); const requestS = new Blob(reqsmall);
var testFunction = function() { const testFunction = () => {
var totLoaded = 0.0, // total number of transmitted bytes let totLoaded = 0.0; // total number of transmitted bytes
startT = new Date().getTime(), // timestamp when test was started let startT = new Date().getTime(); // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections) let bonusT = 0; // how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past let graceTimeDone = false; // set to true after the grace time is past
failed = false; // set to true if a stream fails let failed = false; // set to true if a stream fails
xhr = []; xhr = [];
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time /**
var testStream = function(i, delay) { * function to create an upload stream. streams are slightly delayed so that they will not end at the same time
* @param {number} i
* @param {number} delay
*/
const testStream = (i, delay) => {
setTimeout( setTimeout(
function() { () => {
if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
tverb("ul test stream started " + i + " " + delay); tverb("ul test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes transmitted last time onprogress was called let prevLoaded = 0; // number of bytes transmitted last time onprogress was called
var x = new XMLHttpRequest(); const x = new XMLHttpRequest();
xhr[i] = x; xhr[i] = x;
var ie11workaround; let ie11workaround;
if (settings.forceIE11Workaround) ie11workaround = true; if (settings.forceIE11Workaround) {
else { ie11workaround = true;
} else {
try { try {
xhr[i].upload.onprogress; xhr[i].upload.onprogress;
ie11workaround = false; ie11workaround = false;
@ -474,9 +485,9 @@ function ulTest(done) {
} }
if (ie11workaround) { if (ie11workaround) {
// IE11 workarond: 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 // IE11 workarond: 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
xhr[i].onload = xhr[i].onerror = function() { xhr[i].onload = xhr[i].onerror = () => {
tverb("ul stream progress event (ie11wa)"); tverb("ul stream progress event (ie11wa)");
totLoaded += reqsmall.size; totLoaded += requestS.size;
testStream(i, 0); testStream(i, 0);
}; };
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 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,57 +495,52 @@ function ulTest(done) {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway) xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {} } catch (e) {}
// No Content-Type header in MPOT branch because it triggers bugs in some browsers // No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(reqsmall); xhr[i].send(requestS);
} else { } else {
// REGULAR version, no workaround // REGULAR version, no workaround
xhr[i].upload.onprogress = function(event) { xhr[i].upload.onprogress = (event) => {
tverb("ul stream progress event " + i + " " + event.loaded); tverb("ul stream progress event " + i + " " + event.loaded);
if (testState !== 3) { // just in case this XHR is still running after the upload test
try { if (testState !== 3) try { x.abort(); } catch (e) {}
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the upload test
// progress event, add number of new loaded bytes to totLoaded // progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded; const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff; totLoaded += loadDiff;
prevLoaded = event.loaded; prevLoaded = event.loaded;
}.bind(this); };
xhr[i].upload.onload = function() { xhr[i].upload.onload = () => {
// this stream sent all the garbage data, start again // this stream sent all the garbage data, start again
tverb("ul stream finished " + i); tverb("ul stream finished " + i);
testStream(i, 0); testStream(i, 0);
}.bind(this); };
xhr[i].upload.onerror = function() { xhr[i].upload.onerror = () => {
tverb("ul stream failed " + i); tverb("ul stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; // abort if (settings.xhr_ignoreErrors === 0) failed = true; // abort
try { try { xhr[i].abort(); } catch (e) {}
xhr[i].abort();
} catch (e) {}
delete xhr[i]; delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); // restart stream if (settings.xhr_ignoreErrors === 1) testStream(i, 0); // restart stream
}.bind(this); };
// send xhr // send xhr
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 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
try { try {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway) xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {} } catch (e) {}
// No Content-Type header in MPOT branch because it triggers bugs in some browsers // No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(req); xhr[i].send(request);
} }
}.bind(this), },
delay delay
); );
}.bind(this); };
// open streams // open streams
for (var i = 0; i < settings.xhr_ulMultistream; i++) { for (let i = 0; i < settings.xhr_ulMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i); testStream(i, settings.xhr_multistreamDelay * i);
} }
// every 200ms, update ulStatus // every 200ms, update ulStatus
interval = setInterval( interval = setInterval(
function() { () => {
tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)")); tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT; const t = new Date().getTime() - startT;
if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000); if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
if (t < 200) return; if (t < 200) return;
if (!graceTimeDone) { if (!graceTimeDone) {
@ -548,72 +554,79 @@ function ulTest(done) {
graceTimeDone = true; graceTimeDone = true;
} }
} else { } else {
var speed = totLoaded / (t / 1000.0); const speed = totLoaded / (t / 1000.0);
if (settings.time_auto) { if (settings.time_auto) {
// decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here // decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (6.4 * speed) / 100000; const bonus = 6.4 * speed / 100000;
bonusT += bonus > 800 ? 800 : bonus; bonusT += bonus > 800 ? 800 : bonus;
} }
// update status // update status
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 ulStatus = Number((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
if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) { if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
// test is over, stop streams and timer // test is over, stop streams and timer
if (failed || isNaN(ulStatus)) ulStatus = "Fail"; if (failed || isNaN(ulStatus)) ulStatus = -1;
clearRequests(); clearRequests();
clearInterval(interval); clearInterval(interval);
ulProgress = 1; ulProgress = 1;
tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms"); tlog(`ulTest: ${ulStatus < 0 ? "Fail" : ulStatus}, took ${new Date().getTime() - startT}ms`);
done(); done();
} }
} }
}.bind(this), },
200 200
); );
}.bind(this); };
if (settings.mpot) { if (settings.mpot) {
tverb("Sending POST request before performing upload test"); tverb("Sending POST request before performing upload test");
xhr = []; xhr = [];
xhr[0] = new XMLHttpRequest(); xhr[0] = new XMLHttpRequest();
xhr[0].onload = xhr[0].onerror = function() { xhr[0].onload = xhr[0].onerror = () => {
tverb("POST request sent, starting upload test"); tverb("POST request sent, starting upload test");
testFunction(); testFunction();
}.bind(this); };
xhr[0].open("POST", settings.url_ul); xhr[0].open("POST", settings.url_ul);
xhr[0].send(); xhr[0].send();
} else testFunction(); } else {
testFunction();
} }
// ping+jitter test, function done is called when it's over }
var ptCalled = false; // used to prevent multiple accidental calls to pingTest
let ptCalled = false; // used to prevent multiple accidental calls to pingTest
/**
* ping+jitter test, function done is called when it's over
* @param {() => void} done
*/
function pingTest(done) { function pingTest(done) {
tverb("pingTest"); tverb("pingTest");
if (ptCalled) return; if (ptCalled) return;
else ptCalled = true; // pingTest already called? ptCalled = true; // pingTest already called?
var startT = new Date().getTime(); //when the test was started const startT = new Date().getTime(); // when the test was started
var prevT = null; // last time a pong was received let prevT = null; // last time a pong was received
var ping = 0.0; // current ping value let ping = 0.0; // current ping value
var jitter = 0.0; // current jitter value let jitter = 0.0; // current jitter value
var i = 0; // counter of pongs received let i = 0; // counter of pongs received
var prevInstspd = 0; // last ping time, used for jitter calculation let prevInstspd = 0; // last ping time, used for jitter calculation
xhr = []; xhr = [];
// ping function // ping function
var doPing = function() { const doPing = () => {
tverb("ping"); tverb("ping");
pingProgress = i / settings.count_ping; pingProgress = i / settings.count_ping;
prevT = new Date().getTime(); prevT = new Date().getTime();
xhr[0] = new XMLHttpRequest(); xhr[0] = new XMLHttpRequest();
xhr[0].onload = function() { xhr[0].onload = () => {
// pong // pong
tverb("pong"); tverb("pong");
if (i === 0) { if (i === 0) {
prevT = new Date().getTime(); // first pong prevT = new Date().getTime(); // first pong
} else { } else {
var instspd = new Date().getTime() - prevT; let instspd = new Date().getTime() - prevT;
if (settings.ping_allowPerformanceApi) { if (settings.ping_allowPerformanceApi) {
try { try {
// try to get accurate performance timing using performance api // try to get accurate performance timing using performance api
var p = performance.getEntries(); const pl = performance.getEntries();
p = p[p.length - 1]; /** @type {PerformanceResourceTiming} */
var d = p.responseStart - p.requestStart; const p = pl[pl.length - 1];
let d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration; if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d; if (d > 0 && d < instspd) instspd = d;
} catch (e) { } catch (e) {
@ -624,100 +637,107 @@ function pingTest(done) {
// noticed that some browsers randomly have 0ms ping // noticed that some browsers randomly have 0ms ping
if (instspd < 1) instspd = prevInstspd; if (instspd < 1) instspd = prevInstspd;
if (instspd < 1) instspd = 1; if (instspd < 1) instspd = 1;
var instjitter = Math.abs(instspd - prevInstspd); const instjitter = Math.abs(instspd - prevInstspd);
if (i === 1) ping = instspd; if (i === 1) {
/* first ping, can't tell jitter yet*/ else { ping = instspd; // first ping, can't tell jitter yet
} else {
if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
if (i === 2) jitter = instjitter; if (i === 2) jitter = instjitter; // discard the first jitter measurement because it might be much higher than it should be
//discard the first jitter measurement because it might be much higher than it should be
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. 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.
} }
prevInstspd = instspd; prevInstspd = instspd;
} }
pingStatus = ping.toFixed(2); pingStatus = Number(ping.toFixed(2));
jitterStatus = jitter.toFixed(2); jitterStatus = Number(jitter.toFixed(2));
i++; i++;
tverb("ping: " + pingStatus + " jitter: " + jitterStatus); tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
if (i < settings.count_ping) doPing(); if (i < settings.count_ping) {
else { doPing();
} else {
// more pings to do? // more pings to do?
pingProgress = 1; pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms"); tlog(`ping: ${pingStatus < 0 ? "Fail" : pingStatus} jitter: ${jitterStatus < 0 ? "Fail" : jitterStatus}, took ${new Date().getTime() - startT}ms`);
done(); done();
} }
}.bind(this); };
xhr[0].onerror = function() { xhr[0].onerror = () => {
// a ping failed, cancel test // a ping failed, cancel test
tverb("ping failed"); tverb("ping failed");
if (settings.xhr_ignoreErrors === 0) { if (settings.xhr_ignoreErrors === 0) {
// abort // abort
pingStatus = "Fail"; pingStatus = -1;
jitterStatus = "Fail"; jitterStatus = -1;
clearRequests(); clearRequests();
tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms"); tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
pingProgress = 1; pingProgress = 1;
done(); done();
} } else if (settings.xhr_ignoreErrors === 1) {
if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping doPing(); // retry ping
if (settings.xhr_ignoreErrors === 2) { } else if (settings.xhr_ignoreErrors === 2) {
// ignore failed ping // ignore failed ping
i++; i++;
if (i < settings.count_ping) doPing(); if (i < settings.count_ping) {
else { doPing();
} else {
// more pings to do? // more pings to do?
pingProgress = 1; pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms"); tlog(`ping: ${pingStatus < 0 ? "Fail" : pingStatus} jitter: ${jitterStatus < 0 ? "Fail" : jitterStatus}, took ${new Date().getTime() - startT}ms`);
done(); done();
} }
} }
}.bind(this); };
// send xhr // send xhr
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 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
xhr[0].send(); xhr[0].send();
}.bind(this); };
doPing(); // start first ping doPing(); // start first ping
} }
// telemetry
/**
* @param {(id?: string) => void} done
*/
function sendTelemetry(done) { function sendTelemetry(done) {
if (settings.telemetry_level < 1) return; if (settings.telemetry_level < 1) return;
xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.onload = function() { xhr.onload = () => {
try { try {
var parts = xhr.responseText.split(" "); const parts = xhr.responseText.split(" ");
if (parts[0] == "id") { if (parts[0] === "id")
try { try {
var id = parts[1]; const id = parts[1];
done(id); done(id);
} catch (e) { } catch (e) { done(null); }
else
done(null); done(null);
} } catch (e) { done(null); }
} else done(null);
} catch (e) {
done(null);
}
}; };
xhr.onerror = function() { xhr.onerror = () => {
console.log("TELEMETRY ERROR " + xhr.status); console.log("TELEMETRY ERROR " + xhr.status);
done(null); done(null);
}; };
xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
var telemetryIspInfo = { const telemetryIspInfo = { processedString: clientIp, rawIspInfo: typeof ispInfo === "object" ? ispInfo : "" };
processedString: clientIp,
rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
};
try { try {
var fd = new FormData(); const fd = new FormData();
fd.append("ispinfo", JSON.stringify(telemetryIspInfo)); fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
fd.append("dl", dlStatus); fd.append("dl", dlStatus.toString());
fd.append("ul", ulStatus); fd.append("ul", ulStatus.toString());
fd.append("ping", pingStatus); fd.append("ping", pingStatus.toString());
fd.append("jitter", jitterStatus); fd.append("jitter", jitterStatus.toString());
fd.append("log", settings.telemetry_level > 1 ? log : ""); fd.append("log", settings.telemetry_level > 1 ? log : "");
fd.append("extra", settings.telemetry_extra); fd.append("extra", settings.telemetry_extra);
xhr.send(fd); xhr.send(fd);
} catch (ex) { } catch (ex) {
var 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 : ""); 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 : "");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postData); xhr.send(postData);
} }
} }
/**
* this function is used on URLs passed in the settings to determine whether we need a '?' or an '&' as a separator
* @param {string} url
*/
function url_sep(url) {
return url.match(/\?/) ? "&" : "?";
}