-
Notifications
You must be signed in to change notification settings - Fork 0
/
async-disposable.js
451 lines (411 loc) · 12 KB
/
async-disposable.js
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import { createAsyncIterator } from "./iterator-prototypes.js";
import { symbolDispose, symbolAsyncDispose } from "./symbols.js";
/** @typedef {import("./async-disposable.js").AsyncDisposable.Constructor} DisposableConstructor */
/** @typedef {import("./async-disposable.js").AsyncDisposable} IAsyncDisposable */
/** @typedef {import("./disposable.js").Disposable} IDisposable */
/** @typedef {import("./async-disposable.js").AsyncDisposable.Resource} DisposableResource */
/** @typedef {import("./async-disposable.js").AsyncDisposable.OnDispose<any>} DisposeMethod */
/** @typedef {(value: any) => DisposableResource} MapFn */
/** @typedef {import("./async-disposable.js").AsyncDisposable.Aggregate} DisposableAggregate */
/**
* @typedef {Object} DisposableResourceRecord
* @property {unknown} resourceValue
* @property {'sync' | 'async'} hint
* @property {DisposeMethod} disposeMethod
*/
/** @type {MapFn} */
const defaultMapFn = (value) => value;
/** @type {(value: any, resource: any) => DisposableResourceRecord | undefined } */
const getRecordFromValue = (value, resource) => {
const asyncDispose = value[symbolAsyncDispose];
const asyncDisposeType = typeof asyncDispose;
if (asyncDisposeType !== "undefined") {
if (asyncDisposeType === "function") {
return {
resourceValue: value,
hint: "async",
disposeMethod: asyncDispose,
};
}
} else {
const syncDispose = value[symbolDispose];
if (typeof syncDispose === "function") {
return {
resourceValue: value,
hint: "sync",
disposeMethod: syncDispose,
};
} else if (typeof value === "function") {
return {
resourceValue: resource,
hint: "async",
disposeMethod: value,
};
}
}
return undefined;
};
/**
* @template {DisposableResource} T
* @param {T} disposable
* @param {unknown} resource
* @param {Array<DisposableResourceRecord>} stack
* @param {(err: unknown) => void} [onError]
*/
const addDisposable = (disposable, resource, stack, onError) => {
try {
const record = getRecordFromValue(disposable, resource);
if (!record) {
throw new TypeError("Invalid disposable");
} else {
stack.push(record);
}
} catch (error) {
if (onError) {
onError(error);
} else {
throw error;
}
}
return disposable;
};
/**
* @param {Iterator<unknown> | AsyncIterator<unknown>} iter
* @param {MapFn} getDisposable
*/
const wrapIterator = (iter, getDisposable) => {
const hasReturn = typeof iter.return === "function";
const hasThrow = typeof iter.throw === "function";
let closed = false;
/** @type {DisposableResourceRecord | undefined} */
let pendingRecord;
const dispose = () => {
if (!pendingRecord) return;
const { disposeMethod, resourceValue } = pendingRecord;
pendingRecord = undefined;
return disposeMethod.call(resourceValue);
};
/**
* @template T
* @param {() => T} fn
* @param {boolean} [closeIter]
*/
const tryOrClose = async (fn, closeIter) => {
try {
return fn();
} catch (err) {
closed = true;
try {
await dispose();
} catch (disposeError) {
throw new AggregateError([err, disposeError]);
} finally {
if (closeIter && hasReturn) {
// @ts-ignore
await iter.return();
}
}
throw err;
}
};
/** @type {AsyncIterableIterator<any>} */
const wrapped = createAsyncIterator({
/** @param {[] | [any]} args */
next: async (...args) => {
await tryOrClose(dispose, true);
const nextResult = closed
? { value: undefined, done: true }
: await tryOrClose(async () => iter.next(...args));
await tryOrClose(async () => {
if (!nextResult.done) {
/** @type {DisposableResourceRecord[]} */
const stack = [];
const { value } = nextResult;
addDisposable(getDisposable(value), value, stack);
// Call dispose in case of some re-entrancy
await dispose();
pendingRecord = stack[0];
}
}, true);
return nextResult;
},
/** @param {[] | [any]} args */
return: async (...args) => {
closed = true;
await dispose();
if (hasReturn) {
// @ts-ignore
return iter.return(...args);
} else {
return { value: args[0], done: true };
}
},
/** @param {[] | [any]} args */
throw: async (...args) => {
closed = true;
await dispose();
if (hasThrow) {
// @ts-ignore
return iter.throw(...args);
} else {
if (hasReturn) {
// @ts-ignore
await iter.return(undefined);
}
throw args[0];
}
},
[Symbol.asyncIterator]: () => wrapped,
async [symbolAsyncDispose]() {
// @ts-ignore
await wrapped.return();
},
});
return wrapped;
};
export const AsyncDisposable = /** @type {DisposableConstructor} */ (
class AsyncDisposable {
/** @type {Array<DisposableResourceRecord>} */
#resourceStack = [];
/** @type {'pending'|'disposed'} */
#state = "pending";
/**
* @param {DisposableResource[]} args
*/
constructor(...args) {
Object.defineProperty(this, "using", {
value: this.using.bind(this),
configurable: true,
writable: true,
enumerable: true,
});
if (args.length) {
let fromDone = false;
let fromError;
this.#from(args, undefined, (err) => {
fromDone = true;
fromError = err;
});
if (fromError) {
throw fromError;
}
if (!fromDone) {
throw new Error("Internal Error");
}
}
}
async [symbolAsyncDispose]() {
if (this.#state === "disposed") {
return;
}
this.#state = "disposed";
const errors = [];
const multipleResources = this.#resourceStack.length > 1;
while (this.#resourceStack.length) {
const { resourceValue, hint, disposeMethod } =
/** @type {DisposableResourceRecord} */ (this.#resourceStack.pop());
try {
switch (hint) {
case "sync":
disposeMethod.call(resourceValue);
break;
case "async":
await disposeMethod.call(resourceValue);
break;
default:
throw new TypeError("Invalid disposable record");
}
} catch (err) {
errors.push(err);
}
}
if (errors.length) {
if (multipleResources) {
throw new AggregateError(errors);
} else {
throw errors.pop();
}
}
}
/**
* @param {any} value
* @param {DisposeMethod} [onDispose]
*/
using(value, onDispose) {
const stack = this.#resourceStack;
typeof onDispose === "function"
? addDisposable(onDispose, value, stack)
: addDisposable(value, value, stack);
return value;
}
/**
* @param {Iterable<unknown> | AsyncIterable<unknown>} disposables
* @param {MapFn} [mapFn]
* @param {(err?: unknown) => void} [syncDone]
*/
async #from(disposables, mapFn = defaultMapFn, syncDone = undefined) {
const res = this;
const stack = res.#resourceStack;
const errors = [];
let iterationError;
try {
const asyncIterable = /** @type {AsyncIterable<unknown>} */ (
disposables
);
const syncIterable = /** @type {Iterable<unknown>} */ (disposables);
if (!syncDone && Symbol.asyncIterator in asyncIterable) {
for await (const disposable of asyncIterable) {
addDisposable(mapFn(disposable), disposable, stack, (err) =>
errors.push(err)
);
}
} else {
for (const disposable of syncIterable) {
addDisposable(mapFn(disposable), disposable, stack, (err) =>
errors.push(err)
);
}
}
} catch (err) {
iterationError = err;
}
if (iterationError || errors.length) {
let disposeResult;
const multipleResources = stack.length;
try {
disposeResult = res[symbolAsyncDispose]();
if (!syncDone) {
await disposeResult;
}
} catch (err) {
const disposeErrors = multipleResources
? /** @type {AggregateError} */ (err).errors
: [err];
errors.push(...disposeErrors);
}
let error;
if (!errors.length) {
error = iterationError;
} else {
error = new AggregateError(errors);
if (iterationError) {
Object.defineProperty(error, "cause", {
value: iterationError,
enumerable: false,
writable: true,
configurable: true,
});
}
}
if (syncDone) {
syncDone(error);
return disposeResult;
} else {
throw error;
}
} else if (syncDone) {
syncDone();
}
}
/**
* @param {Iterable<unknown> | AsyncIterable<unknown>} disposables
* @param {MapFn} [mapFn]
*/
static async from(disposables, mapFn = undefined) {
const res = new (this || AsyncDisposable)();
await res.#from(disposables, mapFn);
return res;
}
/**
*
* @param {Iterable<unknown> | AsyncIterable<unknown>} values
* @param {MapFn} [mapFn]
*/
static usingFrom(values, mapFn = defaultMapFn) {
const asyncIterable = /** @type {AsyncIterable<unknown>} */ (values);
const syncIterable = /** @type {Iterable<unknown>} */ (values);
const isAsync = typeof asyncIterable[Symbol.asyncIterator] === "function";
if (!isAsync) {
if (typeof syncIterable[Symbol.iterator] !== "function") {
throw new TypeError("values is not iterable");
}
}
if (typeof mapFn !== "function") {
throw new TypeError("mapFn is not a function");
}
return {
[Symbol.asyncIterator]() {
const iterator = isAsync
? asyncIterable[Symbol.asyncIterator]()
: syncIterable[Symbol.iterator]();
return wrapIterator(iterator, mapFn);
},
};
}
static [Symbol.asyncIterator]() {
/** @type {DisposableAggregate | undefined} */
let res = new (this || Disposable)();
let used = false;
/** @type {import("./async-disposable.js").AsyncDisposable.UsingAsyncIterator} */
const iterator = createAsyncIterator({
async next() {
if (!used && res) {
used = true;
return {
value: res,
done: false,
};
} else {
if (res) {
await res[symbolAsyncDispose]();
res = undefined;
}
return {
value: res,
done: true,
};
}
},
async return() {
used = true;
try {
if (res) {
await res[symbolAsyncDispose]();
res = undefined;
}
} catch (disposeError) {
// TODO: find a way to report when `return` triggered by a throw
throw disposeError;
}
return {
value: res,
done: true,
};
},
async throw(err) {
used = true;
try {
if (res) {
await res[symbolAsyncDispose]();
res = undefined;
}
} catch (disposeError) {
if (!("cause" in /** @type {Object}*/ (disposeError))) {
Object.defineProperty(disposeError, "cause", {
value: err,
enumerable: false,
writable: true,
configurable: true,
});
throw disposeError;
} else {
throw new AggregateError([err, disposeError]);
}
}
throw err;
},
});
return iterator;
}
}
);