tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

NetworkThrottlingUtils.js (2160B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 const lazy = {};
      6 
      7 ChromeUtils.defineESModuleGetters(lazy, {
      8  NetworkObserver:
      9    "resource://devtools/shared/network-observer/NetworkObserver.sys.mjs",
     10 });
     11 
     12 /**
     13 * The NetworkThrottler uses the dev tools NetworkObserver to provide api to throttle all network activity.
     14 * This can be used to fix network conditions in browsertime pageload tests.
     15 *
     16 */
     17 
     18 // A minimal struct for onNetworkEvent handling
     19 class NetworkEventRecord {
     20  addCacheDetails() {}
     21  addRawHeaders() {}
     22  addRequestPostData() {}
     23  addResponseStart() {}
     24  addSecurityInfo() {}
     25  addEventTimings() {}
     26  addResponseCache() {}
     27  addResponseContent() {}
     28  addResponseContentComplete() {}
     29  addServerTimings() {}
     30  addServiceWorkerTimings() {}
     31 }
     32 
     33 class NetworkThrottler {
     34  #devtoolsNetworkObserver;
     35  #throttling;
     36 
     37  constructor() {
     38    this.#throttling = false;
     39  }
     40 
     41  destroy() {
     42    this.stop();
     43  }
     44 
     45  start(throttleData) {
     46    if (this.#throttling) {
     47      console.error("NetworkThrottler already started");
     48      return;
     49    }
     50 
     51    this.#devtoolsNetworkObserver = new lazy.NetworkObserver({
     52      ignoreChannelFunction: this.#ignoreChannelFunction,
     53      onNetworkEvent: this.#onNetworkEvent,
     54    });
     55 
     56    this.#devtoolsNetworkObserver.setThrottleData(throttleData);
     57 
     58    this.#throttling = true;
     59  }
     60 
     61  stop() {
     62    if (!this.#throttling) {
     63      return;
     64    }
     65 
     66    this.#devtoolsNetworkObserver.destroy();
     67    this.#devtoolsNetworkObserver = null;
     68 
     69    this.#throttling = false;
     70  }
     71 
     72  #ignoreChannelFunction = channel => {
     73    // Ignore chrome-privileged or DevTools-initiated requests
     74    if (
     75      channel.loadInfo?.loadingDocument === null &&
     76      (channel.loadInfo.loadingPrincipal ===
     77        Services.scriptSecurityManager.getSystemPrincipal() ||
     78        channel.loadInfo.isInDevToolsContext)
     79    ) {
     80      return true;
     81    }
     82    return false;
     83  };
     84 
     85  #onNetworkEvent = (networkEvent, channel) => {
     86    return new NetworkEventRecord(networkEvent, channel, this);
     87  };
     88 }