aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/vendor/lock.ts
blob: 43249cdd2d9d3a200f822f8b5188d3bcc017e411 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import { Mutex, type MutexInterface } from './async-mutex';

export interface RWLockInterface {
  readonly readerCount: number;
  readonly writerCount: number;
  acquireRead(priority?: number): Promise<() => void>;
  acquireWrite(priority?: number): Promise<() => void>;
  withRead<T>(f: () => Promise<T>): Promise<T>;
  withWrite<T>(f: () => Promise<T>): Promise<T>;
  isLocked(): boolean;
  waitForUnlock(priority?: number): Promise<void>;
}

/** RWLock Helper Methods + Base Interface */
export abstract class RWLockAbstract implements RWLockInterface {
  protected abstract _readerCount: number;
  protected abstract _writerCount: number;
  public get readerCount(): number {
    return this._readerCount;
  }
  public get writerCount(): number {
    return this._writerCount;
  }
  public abstract acquireRead(priority?: number): Promise<() => void>;
  public abstract acquireWrite(priority?: number): Promise<() => void>;
  public async withRead<T>(f: () => Promise<T>): Promise<T> {
    const release = await this.acquireRead();
    try {
      return await f();
    } finally {
      release();
    }
  }
  public async withWrite<T>(f: () => Promise<T>): Promise<T> {
    const release = await this.acquireWrite();
    try {
      return await f();
    } finally {
      release();
    }
  }
  public abstract isLocked(): boolean;
  public abstract waitForUnlock(priority?: number): Promise<void>;
}

/**
 * Single threaded read write lock
 *
 * Based on https://gist.github.com/CMCDragonkai/4de5c1526fc58dac259e321db8cf5331
 */
export class RWLockImpl extends RWLockAbstract {
  protected _readerCount: number = 0;
  protected _writerCount: number = 0;
  protected lock: Mutex = new Mutex();
  protected release?: MutexInterface.Releaser;

  public async acquireRead(priority?: number): Promise<() => void> {
    const readerCount = ++this._readerCount;
    // The first reader locks
    if (readerCount === 1) {
      this.release = await this.lock.acquire(priority);
    }
    return () => {
      const readerCount = --this._readerCount;
      // The last reader unlocks
      if (readerCount === 0) {
        if (!this.release)
          throw new ReferenceError('this.release is undefined');
        this.release();
      }
    };
  }

  public async acquireWrite(priority?: number): Promise<() => void> {
    ++this._writerCount;
    this.release = await this.lock.acquire(priority);
    return () => {
      --this._writerCount;
      if (!this.release) throw new ReferenceError('this.release is undefined');
      this.release();
    };
  }

  public isLocked(): boolean {
    return this.lock.isLocked();
  }

  public async waitForUnlock(priority?: number): Promise<void> {
    return this.lock.waitForUnlock(priority);
  }
}
export type RWLock = RWLockAbstract;
export const RWLock = RWLockImpl;
/**
 * Joined RWLock - Joins multiple {@link RWLock}s, allowing them to be used as one; read locking will read lock all children, write locking will write lock all children.
 * Note: Locking increments readerCount and writerCount by however many locks are in the join
 */
export class JoinedRWLock extends RWLockAbstract {
  public constructor(...childLocks: RWLockAbstract[]) {
    super();
    this._children = childLocks;
  }
  protected _children: RWLockAbstract[];
  protected get _readerCount() {
    return this._children
      .map((v) => v['_readerCount'])
      .reduce((pv, cv) => pv + cv, 0);
  }
  protected get _writerCount() {
    return this._children
      .map((v) => v['_writerCount'])
      .reduce((pv, cv) => pv + cv, 0);
  }
  /**
   * Helper for acquireRead and acquireWrite
   * @param priority Priority passed to acquire
   * @param greedy If we should attempt to get the underlying locks whilst waiting on others. This gives us priority, but may make other operations take forever. `-1`=Never be greedy, `0`=Immediately be greedy, `>0`=Wait `greedyAfter` seconds before being greedy (leaks a Promise if timeout reached)
   */
  private async acquireGeneric(
    acquire: (lock: RWLock, priority?: number) => Promise<() => void>,
    priority?: number,
    greedyAfter = -1
  ) {
    if (greedyAfter === -1) await this.waitForUnlock(priority);
    else if (greedyAfter !== 0)
      await Promise.race([
        this.waitForUnlock(priority),
        new Promise((rs) => setTimeout(rs, greedyAfter * 1000)),
      ]);
    else {
      // being greedy immediately, just aquire locks now
    }
    const _locks = await Promise.allSettled(
      this._children.map((v) => acquire(v))
    );
    const errs = [] as unknown[];
    const locks = _locks.map((v) => {
      if (v.status === 'rejected') {
        errs.push(v.reason);
        return null as never;
      } else {
        return v.value;
      }
    });
    if (errs.length) {
      let unlockErrs: unknown[] =