aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/utils/ConditionVariable.ts
blob: 1d3431f72e423cb871b65a1d42f1209afd45198a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import PendingTask from './PendingTask';
import getLogger from './getLogger';

const log = getLogger('utils.ConditionVariable');

export type Condition = () => boolean;

export default class ConditionVariable {
  private readonly condition: Condition;

  private readonly defaultTimeout: number;

  private listeners: PendingTask<void>[] = [];

  constructor(condition: Condition, defaultTimeout = 0) {
    this.condition = condition;
    this.defaultTimeout = defaultTimeout;
  }

  async waitFor(timeoutMs?: number | undefined): Promise<void> {
    if (this.condition()) {
      return;
    }
    const timeoutOrDefault = timeoutMs ?? this.defaultTimeout;
    let nowMs = Date.now();
    const endMs = nowMs + timeoutOrDefault;
    while (!this.condition() && nowMs < endMs) {
      const remainingMs = endMs - nowMs;
      const promise = new Promise<void>((resolve, reject) => {
        if (this.condition()) {
          resolve();
          return;
        }
        const task = new PendingTask(resolve, reject, remainingMs);
        this.listeners.push(task);
      });
      // We must keep waiting until the update has completed,
      // so the tasks can't be started in parallel.
      // eslint-disable-next-line no-await-in-loop
      await promise;
      nowMs = Date.now();
    }
    if (!this.condition()) {
      log.error('Condition still does not hold after', timeoutOrDefault, 'ms');
      throw new Error('Failed to wait for condition');
    }
  }

  notifyAll(): void {
    this.clearListenersWith((listener) => listener.resolve());
  }

  rejectAll(error: unknown): void {
    this.clearListenersWith((listener) => listener.reject(error));
  }

  private clearListenersWith(callback: (listener: PendingTask<void>) => void) {
    // Copy `listeners` so that we don't get into a race condition
    // if one of the listeners adds another listener.
    const { listeners } = this;
    this.listeners = [];
    listeners.forEach(callback);
  }
}