tor-browser

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

sync-pressure-observer.js (1392B)


      1 // Wrapper around a PressureObserver that:
      2 // 1. Receives and stores multiple updates.
      3 // 2. Allows callers to synchronously wait for an update.
      4 //
      5 // Usage:
      6 //   const syncObserver = new SyncPressureObserver(t);
      7 //   await syncObserver.observer().observe('cpu');
      8 //   await update_virtual_pressure_source(..);
      9 //   await syncObserver.waitForUpdate();
     10 //   const changes = syncObserver.changes();
     11 //   assert_equals(changes[0][0].state, 'nominal');
     12 class SyncPressureObserver {
     13  #observer = null;
     14  #changes = [];
     15 
     16  #promisesWithResolver = [Promise.withResolvers()];
     17  #currentPromisePosition = 0;
     18  #currentResolvePosition = 0;
     19 
     20  constructor(t) {
     21    this.#observer = new PressureObserver(changes => {
     22      this.#changes.push(changes);
     23 
     24      if (this.#currentResolvePosition === this.#promisesWithResolver.length) {
     25        this.#promisesWithResolver.push(Promise.withResolvers());
     26      }
     27      this.#promisesWithResolver[this.#currentResolvePosition++].resolve();
     28    });
     29    t.add_cleanup(() => {this.#observer.disconnect()});
     30  }
     31 
     32  changes() {
     33    return this.#changes;
     34  }
     35 
     36  observer() {
     37    return this.#observer;
     38  }
     39 
     40  async waitForUpdate() {
     41    if (this.#currentPromisePosition === this.#promisesWithResolver.length) {
     42      this.#promisesWithResolver.push(Promise.withResolvers());
     43    }
     44    await this.#promisesWithResolver[this.#currentPromisePosition++].promise;
     45  }
     46 };