stability.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <link rel="shortcut icon" href="favicon.ico" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
  6. <meta charset="UTF-8" />
  7. <title>LibreSpeed - Stability Test</title>
  8. <style type="text/css">
  9. html,
  10. body {
  11. border: none;
  12. padding: 0;
  13. margin: 0;
  14. background: #ffffff;
  15. color: #202020;
  16. }
  17. body {
  18. text-align: center;
  19. font-family: "Roboto", sans-serif;
  20. }
  21. h1 {
  22. color: #404040;
  23. }
  24. nav {
  25. margin-bottom: 1em;
  26. }
  27. nav a {
  28. color: #6060aa;
  29. text-decoration: none;
  30. font-size: 0.95em;
  31. }
  32. nav a:hover {
  33. text-decoration: underline;
  34. }
  35. #controls {
  36. margin: 1em auto;
  37. }
  38. #durationSelect,
  39. #targetSelect {
  40. font-size: 1em;
  41. padding: 0.3em 0.5em;
  42. margin-right: 1em;
  43. }
  44. #startBtn {
  45. display: inline-block;
  46. margin: 0 auto;
  47. color: #6060aa;
  48. background-color: rgba(0, 0, 0, 0);
  49. border: 0.15em solid #6060ff;
  50. border-radius: 0.3em;
  51. transition: all 0.3s;
  52. box-sizing: border-box;
  53. width: 8em;
  54. height: 3em;
  55. line-height: 2.7em;
  56. cursor: pointer;
  57. box-shadow:
  58. 0 0 0 rgba(0, 0, 0, 0.1),
  59. inset 0 0 0 rgba(0, 0, 0, 0.1);
  60. }
  61. #startBtn:hover {
  62. box-shadow:
  63. 0 0 2em rgba(0, 0, 0, 0.1),
  64. inset 0 0 1em rgba(0, 0, 0, 0.1);
  65. }
  66. #startBtn:before {
  67. content: "Start";
  68. }
  69. #startBtn.running {
  70. background-color: #ff3030;
  71. border-color: #ff6060;
  72. color: #ffffff;
  73. }
  74. #startBtn.running:before {
  75. content: "Abort";
  76. }
  77. #resetBtn {
  78. display: inline-block;
  79. color: #808080;
  80. background-color: rgba(0, 0, 0, 0);
  81. border: 0.15em solid #a0a0a0;
  82. border-radius: 0.3em;
  83. transition: all 0.3s;
  84. box-sizing: border-box;
  85. width: 6em;
  86. height: 3em;
  87. line-height: 2.7em;
  88. cursor: pointer;
  89. margin-left: 0.5em;
  90. box-shadow:
  91. 0 0 0 rgba(0, 0, 0, 0.1),
  92. inset 0 0 0 rgba(0, 0, 0, 0.1);
  93. }
  94. #resetBtn:hover {
  95. box-shadow:
  96. 0 0 2em rgba(0, 0, 0, 0.1),
  97. inset 0 0 1em rgba(0, 0, 0, 0.1);
  98. }
  99. #serverArea {
  100. margin: 0.8em 0;
  101. }
  102. #server {
  103. font-size: 1em;
  104. padding: 0.2em;
  105. }
  106. #test {
  107. margin-top: 2em;
  108. margin-bottom: 2em;
  109. }
  110. div.testGroup {
  111. display: block;
  112. margin: 0 auto;
  113. }
  114. div.testArea2 {
  115. display: inline-block;
  116. width: 10em;
  117. height: 7em;
  118. position: relative;
  119. box-sizing: border-box;
  120. text-align: center;
  121. }
  122. div.testArea2 div.testName {
  123. display: block;
  124. text-align: center;
  125. font-size: 1.4em;
  126. }
  127. div.testArea2 div.meterText {
  128. display: inline-block;
  129. font-size: 2.5em;
  130. }
  131. div.meterText:empty:before {
  132. content: "0.00";
  133. }
  134. div.testArea2 div.unit {
  135. display: inline-block;
  136. }
  137. #rating {
  138. font-size: 1.3em;
  139. font-weight: bold;
  140. margin: 0.5em 0;
  141. }
  142. #rating.great {
  143. color: #2ecc71;
  144. }
  145. #rating.good {
  146. color: #27ae60;
  147. }
  148. #rating.poor {
  149. color: #e67e22;
  150. }
  151. #rating.bad {
  152. color: #e74c3c;
  153. }
  154. #rating.none {
  155. color: #808080;
  156. }
  157. #chartContainer {
  158. margin: 1em auto;
  159. width: 95%;
  160. max-width: 60em;
  161. position: relative;
  162. }
  163. #pingChart {
  164. width: 100%;
  165. height: 280px;
  166. border: 1px solid #e0e0e0;
  167. border-radius: 4px;
  168. background: #fafafa;
  169. }
  170. #optionalControls {
  171. margin: 1.5em auto;
  172. max-width: 40em;
  173. }
  174. #optionalControls label {
  175. display: block;
  176. margin: 0.5em 0;
  177. }
  178. #alertThreshold {
  179. vertical-align: middle;
  180. width: 200px;
  181. }
  182. #downloadCsvBtn {
  183. margin-top: 0.8em;
  184. font-size: 0.9em;
  185. padding: 0.4em 1em;
  186. cursor: pointer;
  187. border: 1px solid #6060aa;
  188. background: none;
  189. color: #6060aa;
  190. border-radius: 0.3em;
  191. }
  192. #downloadCsvBtn:hover {
  193. background: #6060aa;
  194. color: #ffffff;
  195. }
  196. .footer {
  197. margin: 2em 0 1em;
  198. }
  199. .footer a {
  200. color: #808080;
  201. font-size: 0.85em;
  202. }
  203. @media all and (max-width: 40em) {
  204. body {
  205. font-size: 0.8em;
  206. }
  207. #pingChart {
  208. height: 200px;
  209. }
  210. }
  211. @media all and (prefers-color-scheme: dark) {
  212. html,
  213. body {
  214. background: #202020;
  215. color: #f4f4f4;
  216. color-scheme: dark;
  217. }
  218. h1 {
  219. color: #e0e0e0;
  220. }
  221. nav a {
  222. color: #9090ff;
  223. }
  224. #pingChart {
  225. border-color: #404040;
  226. background: #1a1a1a;
  227. }
  228. a {
  229. color: #9090ff;
  230. }
  231. #startBtn {
  232. color: #9090ff;
  233. border-color: #7070ff;
  234. }
  235. #startBtn.running {
  236. background-color: #ff3030;
  237. border-color: #ff6060;
  238. color: #ffffff;
  239. }
  240. #resetBtn {
  241. color: #a0a0a0;
  242. border-color: #606060;
  243. }
  244. #downloadCsvBtn {
  245. color: #9090ff;
  246. border-color: #9090ff;
  247. }
  248. #downloadCsvBtn:hover {
  249. background: #9090ff;
  250. color: #202020;
  251. }
  252. .footer a {
  253. color: #a0a0a0;
  254. }
  255. }
  256. </style>
  257. </head>
  258. <body>
  259. <h1>LibreSpeed - Stability Test</h1>
  260. <nav><a href="./">&larr; Speed Test</a></nav>
  261. <div id="controls">
  262. <select id="durationSelect">
  263. <option value="60">60 Seconds</option>
  264. <option value="90">90 Seconds</option>
  265. <option value="120">2 Minutes</option>
  266. <option value="180">3 Minutes</option>
  267. <option value="300">5 Minutes</option>
  268. </select>
  269. <select id="targetSelect">
  270. <option value="">Local Server</option>
  271. <option value="https://www.google.com/generate_204">Google</option>
  272. <option value="https://www.cloudflare.com/cdn-cgi/trace">Cloudflare</option>
  273. <option value="https://www.apple.com/library/test/success.html">Apple</option>
  274. </select>
  275. <div id="startBtn" onclick="startStop()"></div>
  276. <div id="resetBtn" onclick="resetTest()">Reset</div>
  277. </div>
  278. <div id="serverArea" style="display: none">
  279. Server:
  280. <select id="server" onchange="onServerChange(this.value)"></select>
  281. </div>
  282. <div id="rating" class="none">--</div>
  283. <div id="test">
  284. <div class="testGroup">
  285. <div class="testArea2">
  286. <div class="testName">Current</div>
  287. <div id="statCurrent" class="meterText" style="color: #aa6060"></div>
  288. <div class="unit">ms</div>
  289. </div>
  290. <div class="testArea2">
  291. <div class="testName">Average</div>
  292. <div id="statAvg" class="meterText" style="color: #aa6060"></div>
  293. <div class="unit">ms</div>
  294. </div>
  295. <div class="testArea2">
  296. <div class="testName">Jitter</div>
  297. <div id="statJitter" class="meterText" style="color: #aa6060"></div>
  298. <div class="unit">ms</div>
  299. </div>
  300. </div>
  301. <div class="testGroup">
  302. <div class="testArea2">
  303. <div class="testName">Min</div>
  304. <div id="statMin" class="meterText"></div>
  305. <div class="unit">ms</div>
  306. </div>
  307. <div class="testArea2">
  308. <div class="testName">Max</div>
  309. <div id="statMax" class="meterText"></div>
  310. <div class="unit">ms</div>
  311. </div>
  312. <div class="testArea2">
  313. <div class="testName">Failed Requests</div>
  314. <div id="statLoss" class="meterText"></div>
  315. <div class="unit">%</div>
  316. </div>
  317. <div class="testArea2">
  318. <div class="testName">Elapsed</div>
  319. <div id="statElapsed" class="meterText">00:00</div>
  320. <div class="unit"></div>
  321. </div>
  322. </div>
  323. </div>
  324. <div id="chartContainer">
  325. <canvas id="pingChart"></canvas>
  326. </div>
  327. <div id="optionalControls">
  328. <label>
  329. Alert threshold:
  330. <input
  331. type="range"
  332. id="alertThreshold"
  333. min="0"
  334. max="500"
  335. step="10"
  336. value="0"
  337. oninput="updateThreshold(this.value)"
  338. />
  339. <span id="thresholdValue">Off</span>
  340. </label>
  341. <button id="downloadCsvBtn" onclick="downloadCsv()">Download CSV</button>
  342. </div>
  343. <div class="footer">
  344. <a href="https://github.com/librespeed/speedtest">Source code</a>
  345. </div>
  346. <script type="text/javascript">
  347. function I(i) {
  348. return document.getElementById(i);
  349. }
  350. // Server configuration (same pattern as index.html)
  351. // Set this to a different URL to load the server list from another location.
  352. var SPEEDTEST_SERVERS = "server-list.json";
  353. // State
  354. var worker = null;
  355. var updater = null;
  356. var running = false;
  357. var allPingData = []; // full dataset for chart and CSV
  358. var latestData = null;
  359. var alertThresholdMs = 0;
  360. var lastBeepTime = 0;
  361. var audioCtx = null;
  362. var selectedServer = null;
  363. // Dark mode detection for canvas colors
  364. var isDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  365. try {
  366. window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function (e) {
  367. isDark = e.matches;
  368. });
  369. } catch (e) {}
  370. // Chart constants
  371. var VISIBLE_SECONDS = 60;
  372. var CHART_PADDING_LEFT = 50;
  373. var CHART_PADDING_RIGHT = 15;
  374. var CHART_PADDING_TOP = 15;
  375. var CHART_PADDING_BOTTOM = 30;
  376. function joinServerUrl(server, path) {
  377. if (!server) return path;
  378. if (!path) return server;
  379. if (server.charAt(server.length - 1) === "/" || path.charAt(0) === "/") return server + path;
  380. return server + "/" + path;
  381. }
  382. // Load server list dynamically (Docker exposes server-list.json; older setups may expose servers.json)
  383. function loadServers(callback) {
  384. if (Array.isArray(SPEEDTEST_SERVERS)) {
  385. callback();
  386. return;
  387. }
  388. var serverListUrl = typeof SPEEDTEST_SERVERS === "string" ? SPEEDTEST_SERVERS : "";
  389. if (!serverListUrl) {
  390. SPEEDTEST_SERVERS = [];
  391. callback();
  392. return;
  393. }
  394. var xhr = new XMLHttpRequest();
  395. xhr.onload = function () {
  396. var loadedServers = null;
  397. try {
  398. var servers = JSON.parse(xhr.responseText);
  399. if (Array.isArray(servers)) {
  400. loadedServers = servers;
  401. }
  402. } catch (e) {}
  403. if (loadedServers !== null) {
  404. SPEEDTEST_SERVERS = loadedServers;
  405. callback();
  406. } else if (!xhr._fallbackTried) {
  407. xhr._fallbackTried = true;
  408. xhr.open("GET", "servers.json?r=" + Math.random());
  409. xhr.send();
  410. } else {
  411. SPEEDTEST_SERVERS = [];
  412. callback();
  413. }
  414. };
  415. xhr.onerror = function () {
  416. if (xhr._fallbackTried) {
  417. SPEEDTEST_SERVERS = [];
  418. callback();
  419. } else {
  420. xhr._fallbackTried = true;
  421. xhr.open("GET", "servers.json?r=" + Math.random());
  422. xhr.send();
  423. }
  424. };
  425. xhr.open("GET", serverListUrl + (serverListUrl.match(/\?/) ? "&" : "?") + "r=" + Math.random());
  426. try {
  427. xhr.timeout = 2000;
  428. xhr.ontimeout = xhr.onerror;
  429. } catch (e) {}
  430. xhr.send();
  431. }
  432. // Server initialization
  433. function initServers() {
  434. if (SPEEDTEST_SERVERS.length === 0) {
  435. I("serverArea").style.display = "none";
  436. } else {
  437. I("serverArea").style.display = "";
  438. // ping servers to find best one
  439. var completed = 0;
  440. var best = null;
  441. for (var i = 0; i < SPEEDTEST_SERVERS.length; i++) {
  442. (function (idx) {
  443. pingServer(SPEEDTEST_SERVERS[idx], function (server, rtt) {
  444. SPEEDTEST_SERVERS[idx].pingT = rtt;
  445. if (rtt > 0 && (best === null || rtt < best.pingT)) best = SPEEDTEST_SERVERS[idx];
  446. completed++;
  447. if (completed === SPEEDTEST_SERVERS.length) {
  448. // populate dropdown
  449. for (var j = 0; j < SPEEDTEST_SERVERS.length; j++) {
  450. if (SPEEDTEST_SERVERS[j].pingT <= 0) continue;
  451. var opt = document.createElement("option");
  452. opt.value = j;
  453. opt.textContent = SPEEDTEST_SERVERS[j].name;
  454. if (SPEEDTEST_SERVERS[j] === best) opt.selected = true;
  455. I("server").appendChild(opt);
  456. }
  457. selectedServer = best;
  458. }
  459. });
  460. })(i);
  461. }
  462. }
  463. }
  464. function pingServer(server, callback) {
  465. var baseUrl = joinServerUrl(server.server, server.pingURL);
  466. var url = baseUrl + (baseUrl.match(/\?/) ? "&" : "?") + "cors=true&r=" + Math.random();
  467. var xhr = new XMLHttpRequest();
  468. var t = new Date().getTime();
  469. xhr.onload = function () {
  470. callback(server, new Date().getTime() - t);
  471. };
  472. xhr.onerror = function () {
  473. callback(server, -1);
  474. };
  475. xhr.open("GET", url);
  476. try {
  477. xhr.timeout = 2000;
  478. xhr.ontimeout = xhr.onerror;
  479. } catch (e) {}
  480. xhr.send();
  481. }
  482. function onServerChange(idx) {
  483. selectedServer = SPEEDTEST_SERVERS[idx];
  484. }
  485. // Start/Stop
  486. function startStop() {
  487. if (running) {
  488. // abort
  489. if (worker) worker.postMessage("abort");
  490. stopTest();
  491. } else {
  492. startTest();
  493. }
  494. }
  495. function startTest() {
  496. allPingData = [];
  497. latestData = null;
  498. resetUI();
  499. running = true;
  500. I("startBtn").className = "running";
  501. I("durationSelect").disabled = true;
  502. I("targetSelect").disabled = true;
  503. I("server").disabled = true;
  504. var externalTarget = I("targetSelect").value;
  505. var workerSettings = {
  506. duration: parseInt(I("durationSelect").value),
  507. ping_allowPerformanceApi: true,
  508. url_ping_external: externalTarget
  509. };
  510. if (!externalTarget && selectedServer) {
  511. workerSettings.url_ping = joinServerUrl(selectedServer.server, selectedServer.pingURL);
  512. workerSettings.mpot = true;
  513. }
  514. var currentWorker = new Worker("stability_worker.js?r=" + Math.random());
  515. worker = currentWorker;
  516. worker.onmessage = function (e) {
  517. if (worker !== currentWorker) return;
  518. var data = JSON.parse(e.data);
  519. latestData = data;
  520. // accumulate ping data
  521. if (data.pingData && data.pingData.length > 0) {
  522. for (var i = 0; i < data.pingData.length; i++) {
  523. allPingData.push(data.pingData[i]);
  524. }
  525. }
  526. // check alert threshold
  527. if (alertThresholdMs > 0 && data.currentPing > alertThresholdMs) {
  528. playBeep();
  529. }
  530. if (data.testState >= 4) {
  531. stopTest();
  532. }
  533. };
  534. updater = setInterval(function () {
  535. if (worker) worker.postMessage("status");
  536. }, 200);
  537. worker.postMessage("start " + JSON.stringify(workerSettings));
  538. }
  539. function stopTest() {
  540. running = false;
  541. I("startBtn").className = "";
  542. I("durationSelect").disabled = false;
  543. I("targetSelect").disabled = false;
  544. I("server").disabled = false;
  545. if (updater) {
  546. clearInterval(updater);
  547. updater = null;
  548. }
  549. // request final status
  550. if (worker) {
  551. var stoppedWorker = worker;
  552. stoppedWorker.postMessage("status");
  553. setTimeout(function () {
  554. try {
  555. stoppedWorker.terminate();
  556. } catch (e) {}
  557. if (worker === stoppedWorker) {
  558. worker = null;
  559. }
  560. }, 500);
  561. }
  562. }
  563. function resetTest() {
  564. if (running) {
  565. if (worker) worker.postMessage("abort");
  566. stopTest();
  567. }
  568. allPingData = [];
  569. latestData = null;
  570. resetUI();
  571. drawChart();
  572. }
  573. function resetUI() {
  574. I("statCurrent").textContent = "";
  575. I("statAvg").textContent = "";
  576. I("statMin").textContent = "";
  577. I("statMax").textContent = "";
  578. I("statJitter").textContent = "";
  579. I("statLoss").textContent = "";
  580. I("statElapsed").textContent = "";
  581. I("rating").textContent = "--";
  582. I("rating").className = "none";
  583. }
  584. // Format helpers
  585. function fmt(v) {
  586. v = Number(v);
  587. if (isNaN(v) || v <= 0) return "--";
  588. if (v < 10) return v.toFixed(2);
  589. if (v < 100) return v.toFixed(1);
  590. return v.toFixed(0);
  591. }
  592. function fmtTime(sec) {
  593. var m = Math.floor(sec / 60);
  594. var s = Math.floor(sec % 60);
  595. return (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
  596. }
  597. // Rating calculation
  598. function getRating(avg, jit, loss) {
  599. if (avg <= 0) return { text: "--", cls: "none" };
  600. if (avg < 30 && jit < 5 && loss < 0.5) return { text: "Great", cls: "great" };
  601. if (avg < 60 && jit < 15 && loss < 2) return { text: "Good", cls: "good" };
  602. if (avg < 100 && jit < 30 && loss < 5) return { text: "Poor", cls: "poor" };
  603. return { text: "Bad", cls: "bad" };
  604. }
  605. // UI update loop
  606. function updateUI() {
  607. if (!latestData) return;
  608. var d = latestData;
  609. I("statCurrent").textContent = fmt(d.currentPing);
  610. I("statAvg").textContent = fmt(d.avgPing);
  611. I("statMin").textContent = d.minPing > 0 ? fmt(d.minPing) : "--";
  612. I("statMax").textContent = fmt(d.maxPing);
  613. I("statJitter").textContent = fmt(d.jitter);
  614. I("statLoss").textContent = d.totalSamples > 0 ? d.packetLoss.toFixed(1) : "--";
  615. I("statElapsed").textContent = fmtTime(d.elapsed);
  616. var r = getRating(d.avgPing, d.jitter, d.packetLoss);
  617. I("rating").textContent = r.text;
  618. I("rating").className = r.cls;
  619. }
  620. // Canvas chart rendering
  621. function drawChart() {
  622. var canvas = I("pingChart");
  623. var ctx = canvas.getContext("2d");
  624. var dp = window.devicePixelRatio || 1;
  625. var cw = canvas.clientWidth * dp;
  626. var ch = canvas.clientHeight * dp;
  627. if (canvas.width !== cw || canvas.height !== ch) {
  628. canvas.width = cw;
  629. canvas.height = ch;
  630. }
  631. ctx.clearRect(0, 0, cw, ch);
  632. var padL = CHART_PADDING_LEFT * dp;
  633. var padR = CHART_PADDING_RIGHT * dp;
  634. var padT = CHART_PADDING_TOP * dp;
  635. var padB = CHART_PADDING_BOTTOM * dp;
  636. var plotW = cw - padL - padR;
  637. var plotH = ch - padT - padB;
  638. // colors based on theme
  639. var lineColor = isDark ? "#9090FF" : "#6060AA";
  640. var fillColor = isDark ? "rgba(144,144,255,0.15)" : "rgba(96,96,170,0.15)";
  641. var gridColor = isDark ? "#404040" : "#E0E0E0";
  642. var textColor = isDark ? "#A0A0A0" : "#808080";
  643. var lostColor = "#e74c3c";
  644. var thresholdColor = "rgba(231,76,60,0.6)";
  645. // determine visible time window
  646. var data = allPingData;
  647. var maxTime = 0;
  648. if (data.length > 0) maxTime = data[data.length - 1].t;
  649. var timeStart, timeEnd;
  650. if (maxTime <= VISIBLE_SECONDS) {
  651. timeStart = 0;
  652. timeEnd = Math.max(VISIBLE_SECONDS, maxTime);
  653. } else {
  654. timeEnd = maxTime;
  655. timeStart = maxTime - VISIBLE_SECONDS;
  656. }
  657. // binary search to find first visible data point
  658. var visStart = 0;
  659. var lo = 0,
  660. hi = data.length - 1;
  661. while (lo <= hi) {
  662. var mid = (lo + hi) >> 1;
  663. if (data[mid].t < timeStart) lo = mid + 1;
  664. else hi = mid - 1;
  665. }
  666. visStart = lo;
  667. // determine Y-axis scale from visible data only
  668. var yMax = 50; // minimum 50ms scale
  669. for (var i = visStart; i < data.length && data[i].t <= timeEnd; i++) {
  670. if (!data[i].lost && data[i].ping > yMax) yMax = data[i].ping;
  671. }
  672. yMax = Math.ceil((yMax * 1.2) / 10) * 10; // round up to nearest 10 with 20% headroom
  673. var fontSize = 11 * dp;
  674. ctx.font = fontSize + "px sans-serif";
  675. ctx.textBaseline = "middle";
  676. // grid lines - horizontal
  677. var ySteps = getYSteps(yMax);
  678. ctx.strokeStyle = gridColor;
  679. ctx.lineWidth = dp;
  680. ctx.fillStyle = textColor;
  681. ctx.textAlign = "right";
  682. for (var s = 0; s < ySteps.length; s++) {
  683. var yVal = ySteps[s];
  684. if (yVal > yMax) continue;
  685. var y = padT + plotH - (yVal / yMax) * plotH;
  686. ctx.beginPath();
  687. ctx.moveTo(padL, y);
  688. ctx.lineTo(padL + plotW, y);
  689. ctx.stroke();
  690. ctx.fillText(yVal + "", padL - 5 * dp, y);
  691. }
  692. // grid lines - vertical (time ticks)
  693. ctx.textAlign = "center";
  694. ctx.textBaseline = "top";
  695. var timeSpan = timeEnd - timeStart;
  696. var tickInterval = timeSpan <= 60 ? 10 : timeSpan <= 120 ? 15 : 30;
  697. var firstTick = Math.ceil(timeStart / tickInterval) * tickInterval;
  698. for (var t = firstTick; t <= timeEnd; t += tickInterval) {
  699. var x = padL + ((t - timeStart) / timeSpan) * plotW;
  700. ctx.beginPath();
  701. ctx.strokeStyle = gridColor;
  702. ctx.moveTo(x, padT);
  703. ctx.lineTo(x, padT + plotH);
  704. ctx.stroke();
  705. ctx.fillStyle = textColor;
  706. ctx.fillText(fmtTime(t), x, padT + plotH + 4 * dp);
  707. }
  708. // axis labels
  709. ctx.fillStyle = textColor;
  710. ctx.textAlign = "right";
  711. ctx.textBaseline = "top";
  712. ctx.fillText("ms", padL - 5 * dp, padT - 2 * dp);
  713. // plot border
  714. ctx.strokeStyle = gridColor;
  715. ctx.lineWidth = dp;
  716. ctx.strokeRect(padL, padT, plotW, plotH);
  717. // alert threshold line
  718. if (alertThresholdMs > 0 && alertThresholdMs <= yMax) {
  719. var threshY = padT + plotH - (alertThresholdMs / yMax) * plotH;
  720. ctx.save();
  721. ctx.setLineDash([6 * dp, 4 * dp]);
  722. ctx.strokeStyle = thresholdColor;
  723. ctx.lineWidth = 1.5 * dp;
  724. ctx.beginPath();
  725. ctx.moveTo(padL, threshY);
  726. ctx.lineTo(padL + plotW, threshY);
  727. ctx.stroke();
  728. ctx.restore();
  729. }
  730. if (data.length < 2) return;
  731. // filter visible data (using binary search start index)
  732. var visible = [];
  733. for (var i = visStart; i < data.length && data[i].t <= timeEnd; i++) {
  734. visible.push(data[i]);
  735. }
  736. if (visible.length < 1) return;
  737. // draw filled area
  738. ctx.beginPath();
  739. var started = false;
  740. for (var i = 0; i < visible.length; i++) {
  741. if (visible[i].lost) continue;
  742. var px = padL + ((visible[i].t - timeStart) / timeSpan) * plotW;
  743. var py = padT + plotH - (visible[i].ping / yMax) * plotH;
  744. if (!started) {
  745. ctx.moveTo(px, padT + plotH);
  746. ctx.lineTo(px, py);
  747. started = true;
  748. } else {
  749. ctx.lineTo(px, py);
  750. }
  751. }
  752. // close the fill path
  753. if (started) {
  754. // find last non-lost point
  755. for (var i = visible.length - 1; i >= 0; i--) {
  756. if (!visible[i].lost) {
  757. var px = padL + ((visible[i].t - timeStart) / timeSpan) * plotW;
  758. ctx.lineTo(px, padT + plotH);
  759. break;
  760. }
  761. }
  762. ctx.closePath();
  763. ctx.fillStyle = fillColor;
  764. ctx.fill();
  765. }
  766. // draw line
  767. ctx.beginPath();
  768. started = false;
  769. for (var i = 0; i < visible.length; i++) {
  770. if (visible[i].lost) {
  771. started = false;
  772. continue;
  773. }
  774. var px = padL + ((visible[i].t - timeStart) / timeSpan) * plotW;
  775. var py = padT + plotH - (visible[i].ping / yMax) * plotH;
  776. if (!started) {
  777. ctx.moveTo(px, py);
  778. started = true;
  779. } else {
  780. ctx.lineTo(px, py);
  781. }
  782. }
  783. ctx.strokeStyle = lineColor;
  784. ctx.lineWidth = 2 * dp;
  785. ctx.lineJoin = "round";
  786. ctx.stroke();
  787. // draw failed request markers
  788. for (var i = 0; i < visible.length; i++) {
  789. if (!visible[i].lost) continue;
  790. var px = padL + ((visible[i].t - timeStart) / timeSpan) * plotW;
  791. ctx.beginPath();
  792. ctx.arc(px, padT + plotH - 10 * dp, 3 * dp, 0, Math.PI * 2);
  793. ctx.fillStyle = lostColor;
  794. ctx.fill();
  795. }
  796. }
  797. function getYSteps(yMax) {
  798. // generate sensible Y-axis grid steps
  799. if (yMax <= 50) return [10, 20, 30, 40, 50];
  800. if (yMax <= 100) return [20, 40, 60, 80, 100];
  801. if (yMax <= 200) return [50, 100, 150, 200];
  802. if (yMax <= 500) return [100, 200, 300, 400, 500];
  803. // for very high values
  804. var step = Math.ceil(yMax / 5 / 100) * 100;
  805. var steps = [];
  806. for (var v = step; v <= yMax; v += step) steps.push(v);
  807. return steps;
  808. }
  809. // Animation frame loop
  810. window.requestAnimationFrame =
  811. window.requestAnimationFrame ||
  812. window.webkitRequestAnimationFrame ||
  813. window.mozRequestAnimationFrame ||
  814. window.msRequestAnimationFrame ||
  815. function (callback) {
  816. setTimeout(callback, 1000 / 60);
  817. };
  818. function frame() {
  819. requestAnimationFrame(frame);
  820. updateUI();
  821. drawChart();
  822. }
  823. frame();
  824. // Alert threshold
  825. function updateThreshold(val) {
  826. alertThresholdMs = parseInt(val);
  827. I("thresholdValue").textContent = alertThresholdMs > 0 ? alertThresholdMs + " ms" : "Off";
  828. }
  829. function playBeep() {
  830. var now = new Date().getTime();
  831. if (now - lastBeepTime < 1000) return; // debounce 1s
  832. lastBeepTime = now;
  833. try {
  834. if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  835. var osc = audioCtx.createOscillator();
  836. var gain = audioCtx.createGain();
  837. osc.frequency.value = 800;
  838. gain.gain.value = 0.3;
  839. osc.connect(gain);
  840. gain.connect(audioCtx.destination);
  841. osc.start();
  842. osc.stop(audioCtx.currentTime + 0.1);
  843. } catch (e) {}
  844. }
  845. // CSV download
  846. function downloadCsv() {
  847. if (allPingData.length === 0) return;
  848. var csv = "elapsed_s,ping_ms,failed\n";
  849. for (var i = 0; i < allPingData.length; i++) {
  850. var d = allPingData[i];
  851. csv += d.t.toFixed(3) + "," + d.ping.toFixed(2) + "," + (d.lost ? "1" : "0") + "\n";
  852. }
  853. var blob = new Blob([csv], { type: "text/csv" });
  854. var url = URL.createObjectURL(blob);
  855. var a = document.createElement("a");
  856. a.href = url;
  857. a.download = "stability_test_" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".csv";
  858. document.body.appendChild(a);
  859. a.click();
  860. document.body.removeChild(a);
  861. URL.revokeObjectURL(url);
  862. }
  863. // Init — load server list first (async), then initialize UI
  864. loadServers(function () {
  865. initServers();
  866. drawChart();
  867. });
  868. </script>
  869. </body>
  870. </html>