2017-03-02 16:58:40 +00:00
/ *
2019-09-25 06:23:53 +00:00
LibreSpeed - Worker
2017-03-02 16:58:40 +00:00
by Federico Dossena
2019-09-25 06:23:53 +00:00
https : //github.com/librespeed/speedtest/
2017-03-02 16:58:40 +00:00
GNU LGPLv3 License
* /
2017-05-15 10:02:32 +00:00
// data reported to main thread
2023-01-25 10:22:43 +00:00
const NOT _STARTED _STATE = - 1 , // not started
STARTING _STATE = 0 , // starting
DOWNLOAD _TEST _STATE = 1 , // download test
PING _JITTER _TEST _STATE = 2 , // ping + jitter
UPLOAD _TEST _STATE = 3 , // upload test
RPM _UPLOAD _TEST _STATE = 4 , // RPM upload
RPM _DOWNLOAD _TEST _STATE = 5 , // RPM download
FINISHED _STATE = 6 , // finished
ABORT _STATE = 7 ; // abort
var testState = NOT _STARTED _STATE ;
2019-01-25 08:17:32 +00:00
var dlStatus = "" ; // download speed in megabit/s with 2 decimal digits
var ulStatus = "" ; // upload speed in megabit/s with 2 decimal digits
var pingStatus = "" ; // ping in milliseconds with 2 decimal digits
var jitterStatus = "" ; // jitter in milliseconds with 2 decimal digits
var clientIp = "" ; // client's IP address as reported by getIP.php
2023-01-25 10:22:43 +00:00
var rpmUlStatus = "" ; // number of RPM in upload way
var rpmUlRatioStatus = "" ; // number of RPM lost in upload way
var rpmDlStatus = "" ; // number of RPM in download way
var rpmDlRatioStatus = "" ; // number of RPM lost in download way
2019-01-25 08:17:32 +00:00
var dlProgress = 0 ; //progress of download test 0-1
var ulProgress = 0 ; //progress of upload test 0-1
var pingProgress = 0 ; //progress of ping+jitter test 0-1
2023-01-25 10:22:43 +00:00
var rpmUlProgress = 0 ; // progress of RPM Upload test 0-1
var rpmDlProgress = 0 ; // progress of RPM Download test 0-1
2019-01-30 11:30:59 +00:00
var testId = null ; //test ID (sent back by telemetry if used, null otherwise)
2018-08-06 16:15:32 +00:00
2019-01-25 08:17:32 +00:00
var log = "" ; //telemetry log
function tlog ( s ) {
if ( settings . telemetry _level >= 2 ) {
log += Date . now ( ) + ": " + s + "\n" ;
}
}
function tverb ( s ) {
if ( settings . telemetry _level >= 3 ) {
log += Date . now ( ) + ": " + s + "\n" ;
}
}
function twarn ( s ) {
if ( settings . telemetry _level >= 2 ) {
log += Date . now ( ) + " WARN: " + s + "\n" ;
}
console . warn ( s ) ;
}
2017-08-24 13:28:28 +00:00
2017-05-15 10:02:32 +00:00
// test settings. can be overridden by sending specific values with the start command
var settings = {
2023-01-25 10:22:43 +00:00
mpot : true , //set to true when in MPOT mode
test _order : "IP_S_R" , //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
2019-01-25 08:17:32 +00:00
time _ul _max : 15 , // max duration of upload test in seconds
time _dl _max : 15 , // max duration of download test in seconds
time _auto : true , // if set to true, tests will take less time on faster connections
time _ulGraceTime : 3 , //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
time _dlGraceTime : 1.5 , //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
count _ping : 10 , // number of pings to perform in ping test
2019-06-30 05:03:06 +00:00
url _dl : "backend/garbage.php" , // path to a large file or garbage.php, used for download test. must be relative to this js file
url _ul : "backend/empty.php" , // path to an empty file, used for upload test. must be relative to this js file
url _ping : "backend/empty.php" , // path to an empty file, used for ping test. must be relative to this js file
url _getIp : "backend/getIP.php" , // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
2019-01-25 08:17:32 +00:00
getIp _ispInfo : true , //if set to true, the server will include ISP info with the IP address
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
2019-04-10 05:22:41 +00:00
xhr _dlMultistream : 6 , // number of download streams to use (can be different if enable_quirks is active)
2019-01-25 08:17:32 +00:00
xhr _ulMultistream : 3 , // number of upload streams to use (can be different if enable_quirks is active)
xhr _multistreamDelay : 300 , //how much concurrent requests should be delayed
xhr _ignoreErrors : 1 , // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
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)
xhr _ul _blob _megabytes : 20 , //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
2019-04-10 05:22:41 +00:00
garbagePhp _chunkSize : 100 , // size of chunks sent by garbage.php (can be different if enable_quirks is active)
2019-01-25 08:17:32 +00:00
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
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.
overheadCompensationFactor : 1.06 , //can be changed to compensatie for transport overhead. (see doc.md for some other values)
useMebibits : false , //if set to true, speed will be reported in mebibits/s instead of megabits/s
telemetry _level : 0 , // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
2019-06-30 05:03:06 +00:00
url _telemetry : "results/telemetry.php" , // path to the script that adds telemetry data to the database
2020-10-24 07:32:39 +00:00
telemetry _extra : "" , //extra data that can be passed to the telemetry through the settings
2023-01-25 10:22:43 +00:00
forceIE11Workaround : false , //when set to true, it will foce the IE11 upload test on all browsers. Debug only
rpm : { // RPM parameters
MAD : 4 , // Moving Average Distance (number of intervals to take into account for the moving average)
ID : 1 , // Interval duration at which the algorithm reevaluates stability
TMP : 0.95 , // Trimmed Mean Percentage to be trimmed
SDT : 0.05 , // Standard Deviation Tolerance for stability detection
MNP : 16 , // Maximum number of parallel transport-layer connections
MPS : 20 , // Maximum responsiveness probes per second
PTC : 0.05 , // Percentage of Total Capacity the probes are allowed to consume
MaxTime : 20 , // Maximum Time in second
} ,
useWildcard : false // Use wildcard link for connexions
2019-01-25 08:17:32 +00:00
} ;
2017-05-15 10:02:32 +00:00
2019-01-25 08:17:32 +00:00
var xhr = null ; // array of currently active xhr requests
var interval = null ; // timer used in tests
var test _pointer = 0 ; //pointer to the next test to run inside settings.test_order
2017-03-02 16:58:40 +00:00
2017-06-16 04:59:11 +00:00
/ *
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
* /
2019-01-25 08:17:32 +00:00
function url _sep ( url ) {
return url . match ( /\?/ ) ? "&" : "?" ;
}
2017-06-16 04:59:11 +00:00
2023-01-25 10:22:43 +00:00
function useWildcard ( url , subdomain ) {
let domain = ""
try {
domain = new URL ( url ) . hostname ;
} catch {
// url is a route e.g. "/empty.php"
// returns default route
twarn ( ` Couldn't create wildcard subdomain for ${ url } ` ) ;
return url ;
}
let parts = domain . split ( '.' ) ;
parts . splice ( 0 , 0 , subdomain ) ;
let newDomain = parts . join ( '.' ) ;
return url . replace ( domain , newDomain )
}
2017-03-02 16:58:40 +00:00
/ *
listener for commands from main thread to this worker .
commands :
2019-06-30 05:03:06 +00:00
- status : returns the current status as a JSON string containing testState , dlStatus , ulStatus , pingStatus , clientIp , jitterStatus , dlProgress , ulProgress , pingProgress
2017-03-02 16:58:40 +00:00
- abort : aborts the current test
2017-05-15 10:02:32 +00:00
- start : starts the test . optionally , settings can be passed as JSON .
2018-12-07 15:29:12 +00:00
example : start { "time_ul_max" : "10" , "time_dl_max" : "10" , "count_ping" : "50" }
2017-03-02 16:58:40 +00:00
* /
2019-01-25 08:17:32 +00:00
this . addEventListener ( "message" , function ( e ) {
var params = e . data . split ( " " ) ;
if ( params [ 0 ] === "status" ) {
// return status
postMessage (
JSON . stringify ( {
2019-06-30 05:03:06 +00:00
testState : testState ,
2019-01-25 08:17:32 +00:00
dlStatus : dlStatus ,
ulStatus : ulStatus ,
pingStatus : pingStatus ,
clientIp : clientIp ,
jitterStatus : jitterStatus ,
dlProgress : dlProgress ,
ulProgress : ulProgress ,
pingProgress : pingProgress ,
2023-01-25 10:22:43 +00:00
testId : testId ,
rpmDlProgress : rpmDlProgress ,
rpmDlStatus : rpmDlStatus ,
rpmDlRatioStatus : rpmDlRatioStatus ,
rpmUlProgress : rpmUlProgress ,
rpmUlStatus : rpmUlStatus ,
rpmUlRatioStatus : rpmUlRatioStatus ,
2019-01-25 08:17:32 +00:00
} )
) ;
}
2023-01-25 10:22:43 +00:00
if ( params [ 0 ] === "start" && testState === NOT _STARTED _STATE ) {
2019-01-25 08:17:32 +00:00
// start new test
2023-01-25 10:22:43 +00:00
testState = STARTING _STATE ;
2019-01-25 08:17:32 +00:00
try {
// parse settings, if present
var s = { } ;
try {
var ss = e . data . substring ( 5 ) ;
if ( ss ) s = JSON . parse ( ss ) ;
} catch ( e ) {
twarn ( "Error parsing custom settings JSON. Please check your syntax" ) ;
}
//copy custom settings
for ( var key in s ) {
if ( typeof settings [ key ] !== "undefined" ) settings [ key ] = s [ key ] ;
else twarn ( "Unknown setting ignored: " + key ) ;
}
2020-02-17 17:49:09 +00:00
var ua = navigator . userAgent ;
2019-01-25 08:17:32 +00:00
// 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 ( /Firefox.(\d+\.\d+)/i . test ( ua ) ) {
2019-10-07 05:56:44 +00:00
if ( typeof s . ping _allowPerformanceApi === "undefined" ) {
2019-04-13 19:29:30 +00:00
// ff performance API sucks
settings . ping _allowPerformanceApi = false ;
}
2019-01-25 08:17:32 +00:00
}
if ( /Edge.(\d+\.\d+)/i . test ( ua ) ) {
if ( typeof s . xhr _dlMultistream === "undefined" ) {
// edge more precise with 3 download streams
settings . xhr _dlMultistream = 3 ;
}
}
if ( /Chrome.(\d+)/i . test ( ua ) && ! ! self . fetch ) {
if ( typeof s . xhr _dlMultistream === "undefined" ) {
// chrome more precise with 5 streams
settings . xhr _dlMultistream = 5 ;
}
}
}
if ( /Edge.(\d+\.\d+)/i . test ( ua ) ) {
//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
settings . forceIE11Workaround = true ;
}
2019-02-03 11:31:59 +00:00
if ( /PlayStation 4.(\d+\.\d+)/i . test ( ua ) ) {
//PS4 browser has the same bug as IE11/Edge
settings . forceIE11Workaround = true ;
}
2019-01-25 08:17:32 +00:00
if ( /Chrome.(\d+)/i . test ( ua ) && /Android|iPhone|iPad|iPod|Windows Phone/i . test ( ua ) ) {
//cheap af
//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
settings . xhr _ul _blob _megabytes = 4 ;
}
2019-06-30 05:03:06 +00:00
if ( /^((?!chrome|android|crios|fxios).)*safari/i . test ( ua ) ) {
//Safari also needs the IE11 workaround but only for the MPOT version
settings . forceIE11Workaround = true ;
}
2019-01-25 08:17:32 +00:00
//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
//transform test_order to uppercase, just in case
settings . test _order = settings . test _order . toUpperCase ( ) ;
} catch ( e ) {
2019-06-30 05:03:06 +00:00
twarn ( "Possible error in custom test settings. Some settings might not have been applied. Exception: " + e ) ;
2019-01-25 08:17:32 +00:00
}
// run the tests
tverb ( JSON . stringify ( settings ) ) ;
test _pointer = 0 ;
var iRun = false ,
dRun = false ,
uRun = false ,
pRun = false ;
2023-01-25 10:22:43 +00:00
rRun = false ;
sRun = false ;
2019-01-25 08:17:32 +00:00
var runNextTest = function ( ) {
2023-01-25 10:22:43 +00:00
if ( testState == ABORT _STATE ) return ;
2019-01-25 08:17:32 +00:00
if ( test _pointer >= settings . test _order . length ) {
//test is finished
if ( settings . telemetry _level > 0 )
sendTelemetry ( function ( id ) {
2023-01-25 10:22:43 +00:00
testState = FINISHED _STATE ;
2019-01-30 09:16:28 +00:00
if ( id != null ) testId = id ;
2019-01-25 08:17:32 +00:00
} ) ;
2023-01-25 10:22:43 +00:00
else { testState = FINISHED _STATE ; }
2019-01-25 08:17:32 +00:00
return ;
}
switch ( settings . test _order . charAt ( test _pointer ) ) {
case "I" :
{
test _pointer ++ ;
if ( iRun ) {
runNextTest ( ) ;
return ;
} else iRun = true ;
getIp ( runNextTest ) ;
}
break ;
case "D" :
{
test _pointer ++ ;
if ( dRun ) {
runNextTest ( ) ;
return ;
} else dRun = true ;
2023-01-25 10:22:43 +00:00
testState = DOWNLOAD _TEST _STATE ;
2019-01-25 08:17:32 +00:00
dlTest ( runNextTest ) ;
}
break ;
case "U" :
{
test _pointer ++ ;
if ( uRun ) {
runNextTest ( ) ;
return ;
} else uRun = true ;
2023-01-25 10:22:43 +00:00
testState = UPLOAD _TEST _STATE ;
2019-01-25 08:17:32 +00:00
ulTest ( runNextTest ) ;
}
break ;
case "P" :
{
test _pointer ++ ;
if ( pRun ) {
runNextTest ( ) ;
return ;
} else pRun = true ;
2023-01-25 10:22:43 +00:00
testState = PING _JITTER _TEST _STATE ;
2019-01-25 08:17:32 +00:00
pingTest ( runNextTest ) ;
}
break ;
2023-01-25 10:22:43 +00:00
case "R" :
{
test _pointer ++ ;
if ( rRun ) {
runNextTest ( ) ;
return ;
} else rRun = true ;
testState = RPM _UPLOAD _TEST _STATE ;
rpmUlTest ( runNextTest ) ;
}
break ;
case "S" :
{
test _pointer ++ ;
if ( sRun ) {
runNextTest ( ) ;
return ;
} else sRun = true ;
testState = RPM _DOWNLOAD _TEST _STATE ;
rpmDlTest ( runNextTest )
}
break ;
2019-01-25 08:17:32 +00:00
case "_" :
{
test _pointer ++ ;
setTimeout ( runNextTest , 1000 ) ;
}
break ;
default :
test _pointer ++ ;
}
} ;
runNextTest ( ) ;
}
if ( params [ 0 ] === "abort" ) {
// abort command
2023-01-25 10:22:43 +00:00
if ( testState >= FINISHED _STATE ) return ;
2019-01-25 08:17:32 +00:00
tlog ( "manually aborted" ) ;
clearRequests ( ) ; // stop all xhr activity
runNextTest = null ;
if ( interval ) clearInterval ( interval ) ; // clear timer if present
if ( settings . telemetry _level > 1 ) sendTelemetry ( function ( ) { } ) ;
2023-01-25 10:22:43 +00:00
testState = ABORT _STATE ; //set test as aborted
2019-01-25 08:17:32 +00:00
dlStatus = "" ;
ulStatus = "" ;
pingStatus = "" ;
2019-06-30 05:03:06 +00:00
jitterStatus = "" ;
clientIp = "" ;
dlProgress = 0 ;
ulProgress = 0 ;
pingProgress = 0 ;
2023-01-25 10:22:43 +00:00
rpmUlProgress = 0 ;
rpmDlProgress = 0 ;
2019-01-25 08:17:32 +00:00
}
} ) ;
2017-05-15 10:02:32 +00:00
// stops all XHR activity, aggressively
2019-01-25 08:17:32 +00:00
function clearRequests ( ) {
tverb ( "stopping pending XHRs" ) ;
if ( xhr ) {
for ( var i = 0 ; i < xhr . length ; i ++ ) {
try {
xhr [ i ] . onprogress = null ;
xhr [ i ] . onload = null ;
xhr [ i ] . onerror = null ;
} catch ( e ) { }
try {
xhr [ i ] . upload . onprogress = null ;
xhr [ i ] . upload . onload = null ;
xhr [ i ] . upload . onerror = null ;
} catch ( e ) { }
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { }
try {
delete xhr [ i ] ;
} catch ( e ) { }
}
xhr = null ;
}
2017-03-02 16:58:40 +00:00
}
2017-05-15 10:02:32 +00:00
// gets client's IP using url_getIp, then calls the done function
2019-01-25 08:17:32 +00:00
var ipCalled = false ; // used to prevent multiple accidental calls to getIp
var ispInfo = "" ; //used for telemetry
function getIp ( done ) {
tverb ( "getIp" ) ;
if ( ipCalled ) return ;
else ipCalled = true ; // getIp already called?
var startT = new Date ( ) . getTime ( ) ;
xhr = new XMLHttpRequest ( ) ;
xhr . onload = function ( ) {
tlog ( "IP: " + xhr . responseText + ", took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
try {
var data = JSON . parse ( xhr . responseText ) ;
clientIp = data . processedString ;
ispInfo = data . rawIspInfo ;
} catch ( e ) {
clientIp = xhr . responseText ;
ispInfo = "" ;
}
done ( ) ;
} ;
xhr . onerror = function ( ) {
tlog ( "getIp failed, took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
done ( ) ;
} ;
2019-06-30 05:03:06 +00:00
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 ) ;
2019-01-25 08:17:32 +00:00
xhr . send ( ) ;
2017-02-26 11:15:51 +00:00
}
2017-05-15 10:02:32 +00:00
// download test, calls done function when it's over
2019-01-25 08:17:32 +00:00
var dlCalled = false ; // used to prevent multiple accidental calls to dlTest
function dlTest ( done ) {
tverb ( "dlTest" ) ;
if ( dlCalled ) return ;
else dlCalled = true ; // dlTest already called?
var totLoaded = 0.0 , // total number of loaded bytes
startT = new Date ( ) . getTime ( ) , // timestamp when test was started
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
failed = false ; // set to true if a stream fails
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 ) {
setTimeout (
function ( ) {
2023-01-25 10:22:43 +00:00
if ( testState !== DOWNLOAD _TEST _STATE ) return ; // delayed stream ended up starting after the end of the download test
2019-01-25 08:17:32 +00:00
tverb ( "dl test stream started " + i + " " + delay ) ;
var prevLoaded = 0 ; // number of bytes loaded last time onprogress was called
var x = new XMLHttpRequest ( ) ;
xhr [ i ] = x ;
xhr [ i ] . onprogress = function ( event ) {
tverb ( "dl stream progress event " + i + " " + event . loaded ) ;
2023-01-25 10:22:43 +00:00
if ( testState !== DOWNLOAD _TEST _STATE ) {
2019-01-25 08:17:32 +00:00
try {
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
var loadDiff = event . loaded <= 0 ? 0 : event . loaded - prevLoaded ;
if ( isNaN ( loadDiff ) || ! isFinite ( loadDiff ) || loadDiff < 0 ) return ; // just in case
totLoaded += loadDiff ;
prevLoaded = event . loaded ;
} . bind ( this ) ;
xhr [ i ] . onload = function ( ) {
// the large file has been loaded entirely, start again
tverb ( "dl stream finished " + i ) ;
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { } // reset the stream data to empty ram
testStream ( i , 0 ) ;
} . bind ( this ) ;
xhr [ i ] . onerror = function ( ) {
// error
tverb ( "dl stream failed " + i ) ;
if ( settings . xhr _ignoreErrors === 0 ) failed = true ; //abort
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { }
delete xhr [ i ] ;
if ( settings . xhr _ignoreErrors === 1 ) testStream ( i , 0 ) ; //restart stream
} . bind ( this ) ;
// send xhr
try {
if ( settings . xhr _dlUseBlob ) xhr [ i ] . responseType = "blob" ;
else xhr [ i ] . responseType = "arraybuffer" ;
} catch ( e ) { }
2019-06-30 05:03:06 +00:00
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
2019-01-25 08:17:32 +00:00
xhr [ i ] . send ( ) ;
} . bind ( this ) ,
1 + delay
) ;
} . bind ( this ) ;
// open streams
for ( var i = 0 ; i < settings . xhr _dlMultistream ; i ++ ) {
testStream ( i , settings . xhr _multistreamDelay * i ) ;
}
// every 200ms, update dlStatus
interval = setInterval (
function ( ) {
tverb ( "DL: " + dlStatus + ( graceTimeDone ? "" : " (in grace time)" ) ) ;
var t = new Date ( ) . getTime ( ) - startT ;
if ( graceTimeDone ) dlProgress = ( t + bonusT ) / ( settings . time _dl _max * 1000 ) ;
if ( t < 200 ) return ;
if ( ! graceTimeDone ) {
if ( t > 1000 * settings . time _dlGraceTime ) {
if ( totLoaded > 0 ) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date ( ) . getTime ( ) ;
bonusT = 0 ;
totLoaded = 0.0 ;
}
graceTimeDone = true ;
}
} else {
var speed = totLoaded / ( t / 1000.0 ) ;
if ( settings . time _auto ) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
2020-09-27 18:18:01 +00:00
var bonus = ( 5.0 * speed ) / 100000 ;
bonusT += bonus > 400 ? 400 : bonus ;
2019-01-25 08:17:32 +00:00
}
//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
if ( ( t + bonusT ) / 1000.0 > settings . time _dl _max || failed ) {
// test is over, stop streams and timer
if ( failed || isNaN ( dlStatus ) ) dlStatus = "Fail" ;
clearRequests ( ) ;
clearInterval ( interval ) ;
dlProgress = 1 ;
tlog ( "dlTest: " + dlStatus + ", took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
done ( ) ;
}
}
} . bind ( this ) ,
200
) ;
2016-10-09 07:13:36 +00:00
}
2018-12-15 07:18:17 +00:00
// upload test, calls done function whent it's over
2019-01-25 08:17:32 +00:00
var ulCalled = false ; // used to prevent multiple accidental calls to ulTest
function ulTest ( done ) {
tverb ( "ulTest" ) ;
if ( ulCalled ) return ;
else ulCalled = true ; // ulTest already called?
// garbage data for upload test
var r = new ArrayBuffer ( 1048576 ) ;
var maxInt = Math . pow ( 2 , 32 ) - 1 ;
try {
r = new Uint32Array ( r ) ;
for ( var i = 0 ; i < r . length ; i ++ ) r [ i ] = Math . random ( ) * maxInt ;
} catch ( e ) { }
var req = [ ] ;
var reqsmall = [ ] ;
for ( var i = 0 ; i < settings . xhr _ul _blob _megabytes ; i ++ ) req . push ( r ) ;
req = new Blob ( req ) ;
r = new ArrayBuffer ( 262144 ) ;
try {
r = new Uint32Array ( r ) ;
for ( var i = 0 ; i < r . length ; i ++ ) r [ i ] = Math . random ( ) * maxInt ;
} catch ( e ) { }
reqsmall . push ( r ) ;
reqsmall = new Blob ( reqsmall ) ;
2019-06-30 05:03:06 +00:00
var testFunction = function ( ) {
var totLoaded = 0.0 , // total number of transmitted bytes
startT = new Date ( ) . getTime ( ) , // timestamp when test was started
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
failed = false ; // set to true if a stream fails
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 ) {
setTimeout (
function ( ) {
2023-01-25 10:22:43 +00:00
if ( testState !== UPLOAD _TEST _STATE ) return ; // delayed stream ended up starting after the end of the upload test
2019-06-30 05:03:06 +00:00
tverb ( "ul test stream started " + i + " " + delay ) ;
var prevLoaded = 0 ; // number of bytes transmitted last time onprogress was called
var x = new XMLHttpRequest ( ) ;
xhr [ i ] = x ;
var ie11workaround ;
if ( settings . forceIE11Workaround ) ie11workaround = true ;
else {
try {
xhr [ i ] . upload . onprogress ;
ie11workaround = false ;
} catch ( e ) {
ie11workaround = true ;
}
2019-01-25 08:17:32 +00:00
}
2019-06-30 05:03:06 +00:00
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
xhr [ i ] . onload = xhr [ i ] . onerror = function ( ) {
tverb ( "ul stream progress event (ie11wa)" ) ;
totLoaded += reqsmall . size ;
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
try {
xhr [ i ] . setRequestHeader ( "Content-Encoding" , "identity" ) ; // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch ( e ) { }
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr [ i ] . send ( reqsmall ) ;
} else {
// REGULAR version, no workaround
xhr [ i ] . upload . onprogress = function ( event ) {
tverb ( "ul stream progress event " + i + " " + event . loaded ) ;
2023-01-25 10:22:43 +00:00
if ( testState !== UPLOAD _TEST _STATE ) {
2019-06-30 05:03:06 +00:00
try {
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
var loadDiff = event . loaded <= 0 ? 0 : event . loaded - prevLoaded ;
if ( isNaN ( loadDiff ) || ! isFinite ( loadDiff ) || loadDiff < 0 ) return ; // just in case
totLoaded += loadDiff ;
prevLoaded = event . loaded ;
} . bind ( this ) ;
xhr [ i ] . upload . onload = function ( ) {
// this stream sent all the garbage data, start again
tverb ( "ul stream finished " + i ) ;
testStream ( i , 0 ) ;
} . bind ( this ) ;
xhr [ i ] . upload . onerror = function ( ) {
tverb ( "ul stream failed " + i ) ;
if ( settings . xhr _ignoreErrors === 0 ) failed = true ; //abort
2019-01-25 08:17:32 +00:00
try {
2019-06-30 05:03:06 +00:00
xhr [ i ] . abort ( ) ;
2019-01-25 08:17:32 +00:00
} catch ( e ) { }
2019-06-30 05:03:06 +00:00
delete xhr [ i ] ;
if ( settings . xhr _ignoreErrors === 1 ) testStream ( i , 0 ) ; //restart stream
} . bind ( this ) ;
// 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
2019-01-25 08:17:32 +00:00
try {
2019-06-30 05:03:06 +00:00
xhr [ i ] . setRequestHeader ( "Content-Encoding" , "identity" ) ; // disable compression (some browsers may refuse it, but data is incompressible anyway)
2019-01-25 08:17:32 +00:00
} catch ( e ) { }
2019-06-30 05:03:06 +00:00
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr [ i ] . send ( req ) ;
}
} . bind ( this ) ,
2020-05-04 11:38:29 +00:00
delay
2019-06-30 05:03:06 +00:00
) ;
} . bind ( this ) ;
// open streams
for ( var i = 0 ; i < settings . xhr _ulMultistream ; i ++ ) {
testStream ( i , settings . xhr _multistreamDelay * i ) ;
}
// every 200ms, update ulStatus
interval = setInterval (
function ( ) {
tverb ( "UL: " + ulStatus + ( graceTimeDone ? "" : " (in grace time)" ) ) ;
var t = new Date ( ) . getTime ( ) - startT ;
if ( graceTimeDone ) ulProgress = ( t + bonusT ) / ( settings . time _ul _max * 1000 ) ;
if ( t < 200 ) return ;
if ( ! graceTimeDone ) {
if ( t > 1000 * settings . time _ulGraceTime ) {
if ( totLoaded > 0 ) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date ( ) . getTime ( ) ;
bonusT = 0 ;
totLoaded = 0.0 ;
}
graceTimeDone = true ;
}
} else {
var speed = totLoaded / ( t / 1000.0 ) ;
if ( settings . time _auto ) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
2020-09-27 18:18:01 +00:00
var bonus = ( 5.0 * speed ) / 100000 ;
bonusT += bonus > 400 ? 400 : bonus ;
2019-06-30 05:03:06 +00:00
}
//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
if ( ( t + bonusT ) / 1000.0 > settings . time _ul _max || failed ) {
// test is over, stop streams and timer
if ( failed || isNaN ( ulStatus ) ) ulStatus = "Fail" ;
clearRequests ( ) ;
clearInterval ( interval ) ;
ulProgress = 1 ;
tlog ( "ulTest: " + ulStatus + ", took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
done ( ) ;
}
2019-01-25 08:17:32 +00:00
}
} . bind ( this ) ,
2019-06-30 05:03:06 +00:00
200
2019-01-25 08:17:32 +00:00
) ;
} . bind ( this ) ;
2019-06-30 05:03:06 +00:00
if ( settings . mpot ) {
tverb ( "Sending POST request before performing upload test" ) ;
xhr = [ ] ;
xhr [ 0 ] = new XMLHttpRequest ( ) ;
xhr [ 0 ] . onload = xhr [ 0 ] . onerror = function ( ) {
tverb ( "POST request sent, starting upload test" ) ;
testFunction ( ) ;
} . bind ( this ) ;
xhr [ 0 ] . open ( "POST" , settings . url _ul ) ;
xhr [ 0 ] . send ( ) ;
} else testFunction ( ) ;
2016-10-09 07:13:36 +00:00
}
2017-05-15 10:02:32 +00:00
// ping+jitter test, function done is called when it's over
2019-01-25 08:17:32 +00:00
var ptCalled = false ; // used to prevent multiple accidental calls to pingTest
function pingTest ( done ) {
tverb ( "pingTest" ) ;
if ( ptCalled ) return ;
else ptCalled = true ; // pingTest already called?
var startT = new Date ( ) . getTime ( ) ; //when the test was started
var prevT = null ; // last time a pong was received
var ping = 0.0 ; // current ping value
var jitter = 0.0 ; // current jitter value
var i = 0 ; // counter of pongs received
var prevInstspd = 0 ; // last ping time, used for jitter calculation
xhr = [ ] ;
// ping function
var doPing = function ( ) {
tverb ( "ping" ) ;
pingProgress = i / settings . count _ping ;
prevT = new Date ( ) . getTime ( ) ;
xhr [ 0 ] = new XMLHttpRequest ( ) ;
xhr [ 0 ] . onload = function ( ) {
// pong
tverb ( "pong" ) ;
if ( i === 0 ) {
prevT = new Date ( ) . getTime ( ) ; // first pong
} else {
var instspd = new Date ( ) . getTime ( ) - prevT ;
if ( settings . ping _allowPerformanceApi ) {
try {
//try to get accurate performance timing using performance api
var p = performance . getEntries ( ) ;
p = p [ p . length - 1 ] ;
2019-04-13 19:29:30 +00:00
var d = p . responseStart - p . requestStart ;
if ( d <= 0 ) d = p . duration ;
2019-01-25 08:17:32 +00:00
if ( d > 0 && d < instspd ) instspd = d ;
} catch ( e ) {
//if not possible, keep the estimate
tverb ( "Performance API not supported, using estimate" ) ;
}
}
2019-04-13 19:29:30 +00:00
//noticed that some browsers randomly have 0ms ping
2019-06-30 05:03:06 +00:00
if ( instspd < 1 ) instspd = prevInstspd ;
if ( instspd < 1 ) instspd = 1 ;
2019-01-25 08:17:32 +00:00
var instjitter = Math . abs ( instspd - prevInstspd ) ;
if ( i === 1 ) ping = instspd ;
/* first ping, can't tell jitter yet*/ else {
2019-09-24 07:38:17 +00:00
if ( instspd < ping ) ping = instspd ; // update ping, if the instant ping is lower
2019-01-25 08:17:32 +00:00
if ( i === 2 ) jitter = instjitter ;
//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.
}
prevInstspd = instspd ;
2017-10-30 11:35:49 +00:00
}
2019-01-25 08:17:32 +00:00
pingStatus = ping . toFixed ( 2 ) ;
jitterStatus = jitter . toFixed ( 2 ) ;
i ++ ;
tverb ( "ping: " + pingStatus + " jitter: " + jitterStatus ) ;
if ( i < settings . count _ping ) doPing ( ) ;
else {
// more pings to do?
pingProgress = 1 ;
tlog ( "ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
done ( ) ;
}
} . bind ( this ) ;
xhr [ 0 ] . onerror = function ( ) {
// a ping failed, cancel test
tverb ( "ping failed" ) ;
if ( settings . xhr _ignoreErrors === 0 ) {
//abort
pingStatus = "Fail" ;
jitterStatus = "Fail" ;
clearRequests ( ) ;
tlog ( "ping test failed, took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
pingProgress = 1 ;
done ( ) ;
}
if ( settings . xhr _ignoreErrors === 1 ) doPing ( ) ; //retry ping
if ( settings . xhr _ignoreErrors === 2 ) {
//ignore failed ping
i ++ ;
if ( i < settings . count _ping ) doPing ( ) ;
else {
// more pings to do?
pingProgress = 1 ;
tlog ( "ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + ( new Date ( ) . getTime ( ) - startT ) + "ms" ) ;
done ( ) ;
}
}
} . bind ( this ) ;
// send xhr
2019-06-30 05:03:06 +00:00
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
2019-01-25 08:17:32 +00:00
xhr [ 0 ] . send ( ) ;
} . bind ( this ) ;
doPing ( ) ; // start first ping
2017-03-02 16:58:40 +00:00
}
2023-01-25 10:22:43 +00:00
// RPM function
function rpm ( way , createLoadGeneratingConnexions , doPing , done , updateTotalLoaded , updateIsFailed ) {
let pings = [ ]
let totLoaded = updateTotalLoaded ( ) ;
let failed = updateIsFailed ( ) ;
var currentConnexionsNumber = 0 ;
let i = 0 ;
let rpm = 0 ;
// data transfered at interval i
let checkpoints = [ ] ;
let checkpointTimes = [ ]
let instantGoodputs = [ ]
let movigAvgGoodputs = [ ]
let responsivenesses = [ ]
let loadGenerationAdded = [ ]
function instantaneousAgreegateGoodput ( i ) {
return Math . max ( ( checkpoints [ i ] - checkpoints [ i - 1 ] ) / ( ( checkpointTimes [ i ] - checkpointTimes [ i - 1 ] ) / 1000 ) , 0 ) ;
}
// Util functions for the loop
function hasGoodputSaturate ( ) {
let MADinstantGoodputs = instantGoodputs . slice ( - settings . rpm . MAD ) ;
const n = MADinstantGoodputs . length ;
const mean = MADinstantGoodputs . reduce ( ( acc , val ) => acc + val , 0 ) / n ;
const stdDev = Math . sqrt ( MADinstantGoodputs . reduce ( ( acc , val ) => acc + ( val - mean ) * * 2 , 0 ) / n ) ;
const stdDevPercentage = ( stdDev / mean ) * 100 ;
return stdDevPercentage <= settings . rpm . SDT ;
}
function getStdDev ( list ) {
list = list . slice ( - settings . rpm . MAD ) ;
const n = list . length ;
const mean = list . reduce ( ( acc , val ) => acc + val , 0 ) / n ;
const stdDev = Math . sqrt ( list . reduce ( ( acc , val ) => acc + ( val - mean ) * * 2 , 0 ) / n ) ;
return stdDev ;
}
function movingAverageAgreegateGoodput ( i ) {
let nPrev = Math . min ( settings . rpm . MAD , i ) ; // if i < 4
let totalData = checkpoints [ i ] - checkpoints [ i - nPrev ] ;
let totalTime = ( checkpointTimes [ i ] - checkpointTimes [ i - nPrev ] ) / 1000 ;
return totalData / totalTime ;
}
const startTime = new Date ( ) . getTime ( ) ;
let onLoadedConnection = true ;
// Pings
let pingInterval = setInterval ( function ( ) {
doPing ( ( ping ) => {
if ( ( testState !== RPM _DOWNLOAD _TEST _STATE && way === "download" ) || ( testState !== RPM _UPLOAD _TEST _STATE && way === "upload" ) ) { return }
pings . push ( ping ) ;
} , onLoadedConnection ) ;
onLoadedConnection = ! onLoadedConnection
} . bind ( this ) , Math . round ( 1000 / settings . rpm . MPS ) )
// Init connections
createLoadGeneratingConnexions ( currentConnexionsNumber ) ;
currentConnexionsNumber ++ ;
loadGenerationAdded [ i ] = currentConnexionsNumber ;
checkpoints [ 0 ] = 0
checkpointTimes [ 0 ] = 0 ;
i = 1
let interval = setInterval ( function ( ) {
if ( ( testState !== RPM _DOWNLOAD _TEST _STATE && way === "download" ) || ( testState !== RPM _UPLOAD _TEST _STATE && way === "upload" ) ) {
// test change
clearRequests ( ) ;
clearInterval ( pingInterval )
clearInterval ( interval )
}
totLoaded = updateTotalLoaded ( ) ;
// elapsedTime in ms
let elapsedTime = new Date ( ) . getTime ( ) - startTime ;
if ( i > settings . rpm . MaxTime ) {
// Timeout ending
tlog ( ` Rpm ${ way } timeout end ` ) ;
let status = failed ? "failed" : rpm ;
clearInterval ( pingInterval )
clearInterval ( interval )
clearRequests ( ) ;
rpmDlProgress = 1 ;
tlog ( "rpmTest: " + status + ", took " + ( elapsedTime ) + "ms" ) ;
done ( ) ;
} else {
// Updates
checkpoints [ i ] = totLoaded ;
checkpointTimes [ i ] = elapsedTime ;
instantGoodputs [ i ] = instantaneousAgreegateGoodput ( i ) ;
movigAvgGoodputs [ i ] = movingAverageAgreegateGoodput ( i ) ;
// Compute trimmed mean for responsiveness
let sortedValues = pings . sort ( ) ;
let trimCount = Math . floor ( sortedValues . length * ( ( 1 - settings . rpm . TMP ) / 2 ) ) ;
let trimmedValues = sortedValues . slice ( trimCount , sortedValues . length - trimCount ) ;
if ( trimmedValues . length > 0 ) {
let mean = trimmedValues . reduce ( ( a , v ) => a + v , 0 ) / trimmedValues . length
rpm = 60_000 / mean ;
// Update results
let pingAsRPM = parseFloat ( pingStatus ) ;
let ratioRPM = "" ;
if ( pingAsRPM ) {
pingAsRPM = Math . round ( 60_000 / pingAsRPM ) ;
2023-05-04 13:39:04 +00:00
ratioRPM = pingAsRPM / rpm ;
2023-01-25 10:22:43 +00:00
ratioRPM = ratioRPM . toFixed ( 2 ) ;
} ;
if ( way === "upload" ) {
rpmUlStatus = rpm . toFixed ( 0 ) ;
rpmUlRatioStatus = ratioRPM ;
rpmUlProgress = 1 ;
} else if ( way === "download" ) {
rpmDlStatus = rpm . toFixed ( 0 ) ;
rpmDlRatioStatus = ratioRPM ;
rpmDlProgress = 1 ;
}
}
responsivenesses [ i ] = rpm ;
let bandwidth = ( ( movingAverageAgreegateGoodput ( i ) * 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 ( way == "download" ) {
dlStatus = bandwidth ;
} else if ( way == "upload" ) {
ulStatus = bandwidth ;
}
// Following pseudo code
// Create an additional load-generating connection
if ( currentConnexionsNumber < settings . rpm . MNP ) {
createLoadGeneratingConnexions ( currentConnexionsNumber ) ;
currentConnexionsNumber ++ ;
loadGenerationAdded [ i ] = currentConnexionsNumber ;
}
// Check if goodput has saturated
let currentAvg = movigAvgGoodputs [ i ]
let stdDevAvgGoodput = getStdDev ( movigAvgGoodputs )
if ( hasGoodputSaturate ( ) || ( stdDevAvgGoodput < settings . rpm . SDT * currentAvg ) ) {
// Goodput has staturated
let currentResponsiveness = responsivenesses [ i ] ;
if ( getStdDev ( responsivenesses ) < settings . rpm . SDT * currentResponsiveness ) {
tlog ( ` Rpm ${ way } gracefull end ` ) ;
let status = failed ? "failed" : rpm ;
clearInterval ( pingInterval )
clearInterval ( interval )
clearRequests ( ) ;
if ( way === "upload" ) {
rpmUlStatus = currentResponsiveness . toFixed ( 0 ) ;
rpmUlProgress = 1 ;
} else if ( way === "download" ) {
rpmDlStatus = currentResponsiveness . toFixed ( 0 ) ;
rpmDlProgress = 1 ;
}
rpmDlProgress = 1 ;
tlog ( "rpmTest: " + status + ", took " + ( elapsedTime ) + "ms" ) ;
done ( ) ;
}
}
}
tlog ( ` RPM ${ way } round ${ i } , ${ movingAverageAgreegateGoodput ( i ) * 8 } bps, ${ rpm } RPM ` )
i ++ ;
} . bind ( this ) , settings . rpm . ID * 1000 )
}
// RPM Upload test
var rpmUlCalled = false ;
function rpmUlTest ( done ) {
tverb ( "rpmUlTest" ) ;
if ( rpmUlCalled ) return ;
else rpmUlCalled = true ;
xhr = [ ] ;
// Buffer for upload tasks
var r = new ArrayBuffer ( 1048576 ) ;
var maxInt = Math . pow ( 2 , 32 ) - 1 ;
try {
r = new Uint32Array ( r ) ;
for ( var i = 0 ; i < r . length ; i ++ ) r [ i ] = Math . random ( ) * maxInt ;
} catch ( e ) { }
var req = [ ] ;
var reqsmall = [ ] ;
for ( var i = 0 ; i < settings . xhr _ul _blob _megabytes ; i ++ ) req . push ( r ) ;
req = new Blob ( req ) ;
r = new ArrayBuffer ( 262144 ) ;
try {
r = new Uint32Array ( r ) ;
for ( var i = 0 ; i < r . length ; i ++ ) r [ i ] = Math . random ( ) * maxInt ;
} catch ( e ) { }
reqsmall . push ( r ) ;
reqsmall = new Blob ( reqsmall ) ;
var testFunction = function ( ) {
var totLoaded = 0 ;
var failed = false ; // set to true if a stream fails
createLoadGeneratingConnexions = function ( i ) {
if ( testState !== RPM _UPLOAD _TEST _STATE || xhr === null ) { return }
i += 2 ; // xhr[0 and 1] for pings
var prevUlLoaded = 0 ;
var ul = new XMLHttpRequest ( ) ;
xhr [ i ] = ul ;
var ie11workaround = false ;
if ( settings . forceIE11Workaround ) ie11workaround = true ;
else {
try {
xhr [ i ] . upload . onprogress ;
ie11workaround = false ;
} catch ( e ) {
ie11workaround = true ;
}
}
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
xhr [ i ] . onload = xhr [ i ] . onerror = function ( ) {
tverb ( "RPM ul stream progress event (ie11wa)" ) ;
totLoaded += reqsmall . size ;
createLoadGeneratingConnexions ( i , { download : false } ) ;
} ;
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 {
xhr [ i ] . setRequestHeader ( "Content-Encoding" , "identity" ) ; // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch ( e ) { }
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr [ i ] . send ( reqsmall ) ;
} else {
// REGULAR version, no workaround
xhr [ i ] . upload . onprogress = function ( event ) {
tverb ( "RPM ul stream progress event " + ( i ) + " " + event . loaded ) ;
if ( testState !== RPM _UPLOAD _TEST _STATE ) {
try {
xhr [ i ] . 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
var loadDiff = event . loaded <= 0 ? 0 : event . loaded - prevUlLoaded ;
if ( isNaN ( loadDiff ) || ! isFinite ( loadDiff ) || loadDiff < 0 ) return ; // just in case
totLoaded += loadDiff ;
prevUlLoaded = event . loaded ;
} . bind ( this ) ;
xhr [ i ] . upload . onload = function ( ) {
// this stream sent all the garbage data, start again
tverb ( "RPM ul stream finished " + ( i ) ) ;
createLoadGeneratingConnexions ( i ) ;
} . bind ( this ) ;
xhr [ i ] . upload . onerror = function ( ) {
tverb ( "RPM ul stream failed " + ( i ) ) ;
if ( settings . xhr _ignoreErrors === 0 ) failed = true ; //abort
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { }
delete xhr [ i ] ;
if ( settings . xhr _ignoreErrors === 1 ) createLoadGeneratingConnexions ( i ) ; //restart stream
} . bind ( this ) ;
if ( settings . useWildcard ) {
// WILDCARD
xhr [ i ] . open ( "POST" , useWildcard ( settings . url _ul , ` con ${ i } ` ) + url _sep ( settings . url _ul ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
} else {
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 {
xhr [ i ] . setRequestHeader ( "Content-Encoding" , "identity" ) ; // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch ( e ) { }
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr [ i ] . send ( req ) ;
}
} . bind ( this )
var doPing = function ( callback , onLoadedConnection ) {
if ( testState !== RPM _UPLOAD _TEST _STATE ) {
return
}
tverb ( "RPM dl ping" ) ;
let idx = onLoadedConnection ? 1 : 0 ;
let prevT = new Date ( ) . getTime ( ) ;
xhr [ idx ] = new XMLHttpRequest ( ) ;
xhr [ idx ] . onload = function ( ) {
// pong
var instspd = new Date ( ) . getTime ( ) - prevT ;
if ( settings . ping _allowPerformanceApi ) {
try {
//try to get accurate performance timing using performance api
var p = performance . getEntries ( ) ;
p = p [ p . length - 1 ] ;
var d = p . responseStart - p . requestStart ;
if ( d <= 0 ) d = p . duration ;
if ( d > 0 && d < instspd ) instspd = d ;
} catch ( e ) {
//if not possible, keep the estimate
tverb ( "Performance API not supported, using estimate" ) ;
}
}
callback ( instspd )
} . bind ( this ) ;
xhr [ idx ] . onerror = function ( ) {
// a ping failed, cancel test
tverb ( "RPM dl ping failed" ) ;
callback ( undefined )
} . bind ( this ) ;
// send xhr
if ( settings . useWildcard ) {
// WILDCARD
if ( onLoadedConnection ) {
xhr [ idx ] . open ( "POST" , useWildcard ( settings . url _ping , "con2" ) + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
} else {
xhr [ idx ] . open ( "POST" , useWildcard ( settings . url _ping , ` ping ${ Math . floor ( Math . random ( ) * 1000 ) } ` ) + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
}
} else {
xhr [ idx ] . open ( "POST" , settings . url _ping + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
}
xhr [ idx ] . send ( ) ;
} . bind ( this ) ;
rpm (
"upload" ,
createLoadGeneratingConnexions ,
doPing ,
done ,
( ) => { return totLoaded } ,
( ) => { return failed }
)
} . bind ( this ) ;
testFunction ( ) ;
}
// RPM Download test
var rpmDlCalled = false ;
function rpmDlTest ( done ) {
tverb ( "rpmDlTest" ) ;
if ( rpmDlCalled ) return ;
else rpmDlCalled = true ;
xhr = [ ] ;
var testFunction = function ( ) {
var totLoaded = 0 ;
var failed = false ; // set to true if a stream fails
createLoadGeneratingConnexions = function ( i ) {
if ( testState !== RPM _DOWNLOAD _TEST _STATE || xhr === null ) { return }
i += 2 ; // xhr[0 and 1] for pings
var prevDlLoaded = 0 ;
var dl = new XMLHttpRequest ( ) ;
xhr [ i ] = dl ;
xhr [ i ] . onprogress = function ( event ) {
tverb ( "RPM dl stream progress event " + i + " " + event . loaded ) ;
if ( testState !== RPM _DOWNLOAD _TEST _STATE ) {
try {
dl . 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
var loadDiff = event . loaded <= 0 ? 0 : event . loaded - prevDlLoaded ;
if ( isNaN ( loadDiff ) || ! isFinite ( loadDiff ) || loadDiff < 0 ) return ; // just in case
totLoaded += loadDiff ;
prevDlLoaded = event . loaded ;
} . bind ( this )
xhr [ i ] . onload = function ( ) {
// the large file has been loaded entirely, start again
tverb ( "RPM dl stream finished " + i ) ;
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { } // reset the stream data to empty ram
createLoadGeneratingConnexions ( i ) ;
} . bind ( this )
xhr [ i ] . onerror = function ( ) {
// error
tverb ( "RPM dl stream failed " + i ) ;
if ( settings . xhr _ignoreErrors === 0 ) failed = true ; //abort
try {
xhr [ i ] . abort ( ) ;
} catch ( e ) { }
delete xhr [ i ] ;
if ( settings . xhr _ignoreErrors === 1 ) createLoadGeneratingConnexions ( i , 0 ) ; //restart stream
} . bind ( this )
// LAUNCH STREAMS
try {
if ( settings . xhr _dlUseBlob ) xhr [ i ] . responseType = "blob" ;
else xhr [ i ] . responseType = "arraybuffer" ;
} catch ( e ) { }
if ( settings . useWildcard ) {
// Wildcard
xhr [ i ] . open ( "GET" , useWildcard ( settings . url _dl , ` con ${ i } ` ) + url _sep ( settings . url _dl ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) + "&ckSize=" + settings . garbagePhp _chunkSize , true ) ; // random string to prevent caching
} else {
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 ( ) ;
} . bind ( this )
var doPing = function ( callback , onLoadedConnection ) {
if ( testState !== RPM _DOWNLOAD _TEST _STATE ) {
return
}
tverb ( "RPM ul ping" ) ;
let idx = onLoadedConnection ? 1 : 0 ;
let prevT = new Date ( ) . getTime ( ) ;
xhr [ idx ] = new XMLHttpRequest ( ) ;
xhr [ idx ] . onload = function ( ) {
// pong
var instspd = new Date ( ) . getTime ( ) - prevT ;
if ( settings . ping _allowPerformanceApi ) {
try {
//try to get accurate performance timing using performance api
var p = performance . getEntries ( ) ;
p = p [ p . length - 1 ] ;
var d = p . responseStart - p . requestStart ;
if ( d <= 0 ) d = p . duration ;
if ( d > 0 && d < instspd ) instspd = d ;
} catch ( e ) {
//if not possible, keep the estimate
tverb ( "Performance API not supported, using estimate" ) ;
}
}
callback ( instspd )
} . bind ( this ) ;
xhr [ idx ] . onerror = function ( ) {
// a ping failed, cancel test
tverb ( "RPM ul ping failed" ) ;
callback ( undefined )
} . bind ( this ) ;
// send xhr
if ( settings . useWildcard ) {
// WILDCARD
if ( onLoadedConnection ) {
xhr [ idx ] . open ( "GET" , useWildcard ( settings . url _ping , "con2" ) + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
} else {
xhr [ idx ] . open ( "GET" , useWildcard ( settings . url _ping , ` ping ${ Math . floor ( Math . random ( ) * 1000 ) } ` ) + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
}
} else {
xhr [ idx ] . open ( "GET" , settings . url _ping + url _sep ( settings . url _ping ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ; // random string to prevent caching
}
xhr [ idx ] . send ( ) ;
} . bind ( this ) ;
rpm (
"download" ,
createLoadGeneratingConnexions ,
doPing ,
done ,
( ) => { return totLoaded } ,
( ) => { return failed }
)
} . bind ( this ) ;
testFunction ( ) ;
}
2017-08-24 13:28:28 +00:00
// telemetry
2019-01-25 08:17:32 +00:00
function sendTelemetry ( done ) {
if ( settings . telemetry _level < 1 ) return ;
xhr = new XMLHttpRequest ( ) ;
xhr . onload = function ( ) {
try {
var parts = xhr . responseText . split ( " " ) ;
if ( parts [ 0 ] == "id" ) {
try {
2019-01-30 09:16:28 +00:00
var id = parts [ 1 ] ;
done ( id ) ;
2019-01-25 08:17:32 +00:00
} catch ( e ) {
2019-01-30 09:16:28 +00:00
done ( null ) ;
2019-01-25 08:17:32 +00:00
}
2019-01-30 09:16:28 +00:00
} else done ( null ) ;
2019-01-25 08:17:32 +00:00
} catch ( e ) {
2019-01-30 09:16:28 +00:00
done ( null ) ;
2019-01-25 08:17:32 +00:00
}
} ;
xhr . onerror = function ( ) {
console . log ( "TELEMETRY ERROR " + xhr . status ) ;
2019-01-31 11:43:45 +00:00
done ( null ) ;
2019-01-25 08:17:32 +00:00
} ;
2019-06-30 05:03:06 +00:00
xhr . open ( "POST" , settings . url _telemetry + url _sep ( settings . url _telemetry ) + ( settings . mpot ? "cors=true&" : "" ) + "r=" + Math . random ( ) , true ) ;
2019-01-25 08:17:32 +00:00
var telemetryIspInfo = {
processedString : clientIp ,
rawIspInfo : typeof ispInfo === "object" ? ispInfo : ""
} ;
try {
var fd = new FormData ( ) ;
fd . append ( "ispinfo" , JSON . stringify ( telemetryIspInfo ) ) ;
fd . append ( "dl" , dlStatus ) ;
fd . append ( "ul" , ulStatus ) ;
fd . append ( "ping" , pingStatus ) ;
fd . append ( "jitter" , jitterStatus ) ;
fd . append ( "log" , settings . telemetry _level > 1 ? log : "" ) ;
fd . append ( "extra" , settings . telemetry _extra ) ;
xhr . send ( fd ) ;
} 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 : "" ) ;
xhr . setRequestHeader ( "Content-Type" , "application/x-www-form-urlencoded" ) ;
xhr . send ( postData ) ;
2018-08-06 16:15:32 +00:00
}
2019-01-25 08:17:32 +00:00
}