aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/vendor/async-mutex/semaphore.ts
blob: 385e814bbb8419827dd4422e318ee573137e0cea (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { E_CANCELED } from './errors';
import type { SemaphoreInterface } from './semaphoreinterface';

interface Priority {
  priority: number;
}

interface QueueEntry {
  resolve(result: [number, SemaphoreInterface.Releaser]): void;
  reject(error: unknown): void;
  weight: number;
  priority: number;
}

interface Waiter {
  resolve(): void;
  priority: number;
}

class Semaphore implements SemaphoreInterface {
  constructor(
    private _value: number,
    private _cancelError: Error = E_CANCELED
  ) {}

  acquire(
    weight = 1,
    priority = 0
  ): Promise<[number, SemaphoreInterface.Releaser]> {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);

    return new Promise((resolve, reject) => {
      const task: QueueEntry = { resolve, reject, weight, priority };
      const i = findIndexFromEnd(
        this._queue,
        (other) => priority <= other.priority
      );
      if (i === -1 && weight <= this._value) {
        // Needs immediate dispatch, skip the queue
        this._dispatchItem(task);
      } else {
        this._queue.splice(i + 1, 0, task);
      }
    });
  }

  async runExclusive<T>(
    callback: SemaphoreInterface.Worker<T>,
    weight = 1,
    priority = 0
  ): Promise<T> {
    const [value, release] = await this.acquire(weight, priority);

    try {
      return await callback(value);
    } finally {
      release();
    }
  }

  waitForUnlock(weight = 1, priority = 0): Promise<void> {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);

    if (this._couldLockImmediately(weight, priority)) {
      return Promise.resolve();
    } else {
      return new Promise((resolve) => {
        if (!this._weightedWaiters[weight - 1])
          this._weightedWaiters[weight - 1] = [];
        insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });
      });
    }
  }

  isLocked(): boolean {
    return this._value <= 0;
  }

  getValue(): number {
    return this._value;
  }

  setValue(value: number): void {
    this._value = value;
    this._dispatchQueue();
  }

  release(weight = 1): void {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);

    this._value += weight;
    this._dispatchQueue();
  }

  cancel(): void {
    this._queue.forEach((entry) => entry.reject(this._cancelError));
    this._queue = [];
  }

  private _dispatchQueue(): void {
    this._drainUnlockWaiters();
    while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
      this._dispatchItem(this._queue.shift()!);
      this._drainUnlockWaiters();
    }
  }

  private _dispatchItem(item: QueueEntry): void {
    const previousValue = this._value;
    this._value -= item.weight;
    item.resolve([previousValue, this._newReleaser(item.weight)]);
  }

  private _newReleaser(weight: number): () => void {
    let called = false;

    return () => {
      if (called) return;
      called = true;

      this.release(weight);
    };
  }

  private _drainUnlockWaiters(): void {
    if (this._queue.length === 0) {
      for (let weight = this._value; weight > 0; weight--) {
        const waiters = this._weightedWaiters[weight - 1];
        if (!waiters) continue;
        waiters.forEach((waiter) => waiter.resolve());
        this._weightedWaiters[weight - 1] = [];
      }
    } else {
      const queuedPriority = this._queue[0].priority;
      for (let weight = this._value; weight > 0; weight--) {
        const waiters = this._weightedWaiters[weight - 1];
        if (!waiters) continue;
        const i = waiters.findIndex(
          (waiter) => waiter.priority <= queuedPriority
        );
        (i === -1 ? waiters : waiters.splice(0, i)).forEach((waiter) =>
          waiter.resolve()
        );
      }
    }
  }

  private _couldLockImmediately(weight: number, priority: number) {
    return (
      (this._queue.length === 0 || this._queue[0].priority < priority) &&
      weight <= this._value
    );
  }

  private _queue: Array<QueueEntry> = [];
  private _weightedWaiters: Array<Array<Waiter>> = [];
}

function insertSorted<T extends Priority>(a: T[], v: T) {
  const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
  a.splice(i + 1, 0, v);