-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLockStore.ts
218 lines (180 loc) · 5.02 KB
/
LockStore.ts
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
import {first, noop} from 'lodash-es';
import {ValueOf} from 'type-fest';
import {getNewId} from '../id/index.js';
import {getDeferredPromise} from '../promise/getDeferredPromise.js';
import {AnyFn, OrPromise, PartialRecord} from '../types.js';
import {ListenableResource} from './ListenableResource.js';
import {DisposableResource} from './disposables.js';
const kLockQueueItemState = {
waiting: 'w',
waitingOnResolve: 'wr',
} as const;
type LockQueueItemState = ValueOf<typeof kLockQueueItemState>;
interface LockQueueItem {
state: LockQueueItemState;
resolveFn: AnyFn;
}
interface ILockWaiter {
remaining: number;
resolveFn: AnyFn;
timeoutId?: unknown;
}
type LocksMap = PartialRecord<string, ListenableResource<LockQueueItem>[]>;
export class LockStore implements DisposableResource {
protected locks: LocksMap = {};
protected waiters: Array<ILockWaiter> = [];
run<TFn extends AnyFn>(
name: string,
fn: TFn
): Promise<Awaited<ReturnType<TFn>>> {
const item = this.queue(name);
return this.__run(name, item, fn);
}
has(name: string) {
return !!this.getLockQueue(name, false)?.length;
}
wait(params: {name: string; remaining?: number; timeoutMs?: number}) {
const {name, timeoutMs} = params;
const queueLength = this.getLockQueue(name, false)?.length ?? 0;
const remaining = params.remaining ?? queueLength;
if (queueLength === 0 || remaining <= 0) {
return Promise.resolve();
}
const p = getDeferredPromise();
const waiter: ILockWaiter = {
remaining,
resolveFn: p.resolve,
timeoutId: undefined,
};
this.waiters.push(waiter);
if (timeoutMs) {
waiter.timeoutId = setTimeout(() => {
p.reject(new Error('Timeout'));
this.waiters = this.waiters.filter(w => w !== waiter);
}, timeoutMs);
}
return p.promise;
}
dispose() {
this.waiters.forEach(waiter => {
if (waiter.timeoutId) {
clearTimeout(waiter.timeoutId as unknown as number);
}
});
}
protected async __run(
name: string,
item: ListenableResource<LockQueueItem>,
fn: AnyFn
) {
await this.acquire(name, item);
try {
return await fn();
} finally {
this.release(name);
}
}
protected queue(name: string) {
const queue = this.getLockQueue(name, true);
const item = new ListenableResource<LockQueueItem>({
state: kLockQueueItemState.waitingOnResolve,
resolveFn: noop,
});
queue.push(item);
return item;
}
protected acquire(name: string, item: ListenableResource<LockQueueItem>) {
const p = new Promise<void>(resolve => {
item.set({
state: kLockQueueItemState.waiting,
resolveFn: resolve,
});
});
setTimeout(() => this.execNext(name), 0);
return p;
}
protected release(name: string) {
const queue = this.getLockQueue(name, true);
queue.shift();
this.waiters = this.waiters.filter(w => {
w.remaining--;
const isWaitDone = w.remaining <= 0;
if (isWaitDone) {
if (w.timeoutId) {
clearTimeout(w.timeoutId as unknown as number);
}
w.resolveFn();
}
return !isWaitDone;
});
this.execNext(name);
}
protected execNext = (name: string) => {
const queue = this.getLockQueue(name, true);
const next = first(queue);
const item = next?.get();
if (!next || !item) {
return;
}
if (item.state === kLockQueueItemState.waitingOnResolve) {
next.listen(this.execLockItem);
}
this.execLockItem(item);
};
protected execLockItem = (item?: LockQueueItem) => {
if (item?.state === kLockQueueItemState.waiting) {
item.resolveFn();
return true;
}
return false;
};
protected getLockQueue<
TInitQueue extends boolean = true,
TResult = TInitQueue extends true
? ListenableResource<LockQueueItem>[]
: ListenableResource<LockQueueItem>[] | undefined,
>(name: string, init: TInitQueue): TResult {
let queue = this.locks[name];
if (!queue && init) {
queue = this.locks[name] = [];
}
return queue as TResult;
}
}
export class LockableResource<T> {
protected resource: T;
protected name: string;
constructor(
protected locks: LockStore,
resource: T,
name = getNewId()
) {
this.resource = resource;
this.name = name;
}
async run(fn: AnyFn<[T], OrPromise<T | void>>) {
await this.locks.run(this.name, async () => {
const newData = await fn(this.resource);
if (newData) {
this.resource = newData;
}
});
}
}
interface ISingleInstanceRunnerMakeOptions<TFn extends AnyFn> {
instanceSpecifier: (...args: Parameters<TFn>) => string;
fn: TFn;
}
export class SingleInstanceRunner {
static make<TFn extends AnyFn>(
locks: LockStore,
opts: ISingleInstanceRunnerMakeOptions<TFn>
) {
return async (
...args: Parameters<TFn>
): Promise<Awaited<ReturnType<TFn>>> => {
const id = opts.instanceSpecifier(...args);
return await locks.run(id, () => opts.fn(...args));
};
}
}