-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.ts
418 lines (381 loc) · 14.1 KB
/
task.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
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
import { TEvent } from "./event"
import { abort } from "./fn"
import { isNone, Voidable } from "./maybe"
/** Cancellation Token */
export interface CancelToken {
/** Has it been cancelled or whether cancellation has been requested */
readonly cancelled: boolean
/** Communicates a request for cancellation */
cancel(): void
/** If cancelled, throw `CancelGuard` */
guard(): void
/** Register an event that will be triggered when cancelled */
reg(f: () => void): void
/** Waiting for cancellation */
reg(): Promise<void>
/** Unregister event */
unReg(f: () => void): void
}
/** Cancel Guard */
export class CancelGuard {
#source: CancelToken
private constructor(source: CancelToken) {
this.#source = source
}
is(source: CancelToken) {
return source === this.#source
}
static new(source: CancelToken) {
return new CancelGuard(source)
}
}
/** Cancellation provider */
class CancelSource implements CancelToken {
#cancelled = false
#reg?: TEvent
get cancelled() {
return this.#cancelled
}
cancel() {
if (!this.#cancelled) {
this.#reg?.emit()
}
this.#cancelled = true
}
guard() {
if (this.#cancelled) throw CancelGuard.new(this)
}
reg(): Promise<void>
reg(f: () => any): void
reg(f?: () => any) {
if (isNone(f)) return new Promise<void>(res => this.reg(() => res()))
if (isNone(this.#reg)) this.#reg = new TEvent
this.#reg.once(f)
}
unReg(f: () => any) {
this.#reg?.off(f)
}
}
/** Sync cancelable */
export function syncCancelable<R>(f: (ctx: CancelToken) => R): R | void {
const token = new CancelSource
try {
return f(token)
} catch (e) {
if (e instanceof CancelGuard && e.is(token)) return
throw e
}
}
/** Async cancelable */
export async function cancelable<R>(f: (ctx: CancelToken) => Promise<R>): Promise<R | void> {
const token = new CancelSource
try {
return await f(token)
} catch (e) {
if (e instanceof CancelGuard && e.is(token)) return
throw e
}
}
/** Task Like */
export interface TaskLike<T> extends CancelToken, PromiseLike<T | void> {
/** Run task */
run(): PromiseLike<T | void>
/** Is running */
running: boolean
/** Whether finished */
finished: boolean
}
const TaskNoInit = Symbol('TaskNoInit')
/** Cancelable async task */
export class Task<T> implements TaskLike<T>, Promise<T | void> {
// @ts-ignore
#p: Promise<T | void>
#cancelled = false
#finished = false
#reg?: TEvent
/** Creates a new Task */
constructor(f: (self: Task<T>) => PromiseLike<T>)
/** Creates a new Task with CancelToken */
constructor(token: CancelToken, f: (self: Task<T>) => PromiseLike<T>)
constructor(a: any, b?: any) {
if (a === TaskNoInit) return
if (typeof b === 'function') [a, b] = [b, a]
const token: Voidable<CancelToken> = b, f: (self: Task<T>) => PromiseLike<T> = a
if (token?.cancelled === true) return Task.abort()
const cancel = () => this.cancel()
token?.reg(cancel)
this.#p = (async () => {
try {
return await f(this)
} catch (e) {
if (e instanceof CancelGuard && e.is(this)) return
throw e
} finally {
this.#finished = true
token?.unReg(cancel)
}
})()
}
/** Communicates a request for cancellation */
cancel() {
if (!this.#cancelled) {
this.#cancelled = true
this.#reg?.emit()
}
}
/** If cancelled, throw CancelGuard */
guard() {
if (this.#cancelled) throw CancelGuard.new(this)
}
/** If cancelled will not continue */
aguard(): Promise<void> {
if (this.#cancelled) return abort()
else return Promise.resolve()
}
/** Register an event that will be triggered when cancelled */
reg(f: () => any): void
/** Waiting for cancellation */
reg(): Promise<void>
reg(f?: () => any) {
if (isNone(f)) return new Promise<void>(res => this.reg(() => res()))
if (isNone(this.#reg)) this.#reg = new TEvent
this.#reg.once(f)
}
/** Unregister event */
unReg(f: () => any) {
this.#reg?.off(f)
}
/** Has it been cancelled or whether cancellation has been requested */
get cancelled() {
return this.#cancelled
}
/** Whether finished */
get finished() {
return this.#finished
}
/** Is running */
get running() {
return !this.#cancelled && !this.#finished
}
/** Run task
*
* Even if this function is not called the task will still run
*/
run(): Promise<T | void> {
return this.#p
}
/** Attaches callbacks for the resolution and/or rejection of the Promise. */
then<TResult1 = T | void, TResult2 = never>(onfulfilled?: ((value: T | void) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2> {
return this.#p.then(onfulfilled, onrejected)
}
/** Attaches a callback for only the rejection of the Promise. */
async catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult | void> {
return this.#p.catch(onrejected)
}
[Symbol.toStringTag]: string
/** Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback. */
finally(onfinally?: (() => void) | null): Promise<T | void> {
return this.#p.finally(onfinally)
}
/** Run Task */
static run<T>(f: (self: Task<T>) => PromiseLike<T>): Task<T>
/** Run Task with CancelToken */
static run<T>(token: CancelToken, f: (self: Task<T>) => PromiseLike<T>): Task<T>
static run<T>(a: any, b?: any): Task<T> {
return new Task<T>(a, b)
}
/** Run task with promise parameters
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
static exec<T>(executor: (self: Task<T>, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Task<T>
/** Run task with promise parameters with CancelToken
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
static exec<T>(token: CancelToken, executor: (self: Task<T>, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Task<T>
static exec<T>(a: any, b?: any): Task<T> {
if (typeof b === 'function') {
if (a?.cancelled === true) return Task.abort()
return new Task(a, self => new Promise((res, rej) => b(self, res, rej)))
}
return new Task(self => new Promise((res, rej) => a(self, res, rej)))
}
/** Cancelable async delay */
static delay(ms?: number): Task<void>
/** Cancelable async delay with CancelToken */
static delay(token: CancelToken, ms?: number): Task<void>
static delay(a?: any, b?: number): Task<void> {
if (typeof b === 'number') {
if (a?.cancelled === true) return Task.abort()
return Task.exec(a, (self, res) => {
const f = () => clearTimeout(id)
const id = setTimeout(() => {
self.unReg(f)
res()
}, b);
self.reg(f)
})
}
return Task.exec((self, res) => {
const f = () => clearTimeout(id)
const id = setTimeout(() => {
self.unReg(f)
res()
}, a);
self.reg(f)
})
}
/** Yield time slice and not continue if cancelled */
static yield(token?: CancelToken): Task<void> {
if (isNone(token)) return Task.exec((self, res) => {
queueMicrotask(() => {
if (!self.#cancelled) res()
})
})
if (token.cancelled) return Task.abort()
return Task.exec(token, (self, res) => {
queueMicrotask(() => {
if (!(self.#cancelled || token.cancelled)) res()
})
})
}
/** Yield time slice and not continue if cancelled, using this as CancelToken */
yield(): Task<void> {
return Task.yield(this)
}
/** Cancelable async delay, using this as CancelToken */
delay(ms?: number): Task<void> {
return Task.delay(this, ms)
}
/** Run Task, using this as CancelToken */
subRun<T>(f: (self: Task<T>) => PromiseLike<T>): Task<T> {
return Task.run(this, f)
}
/** Run task with promise parameters, using this as CancelToken
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
exec<T>(executor: (self: Task<T>, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Task<T> {
return Task.exec(this, executor)
}
/** Creates a new cancelled task
* @returns A cancelled task */
static abort(): Task<never> {
const task = new Task<never>(TaskNoInit as any)
task.#p = abort()
task.#cancelled = true
return task
}
/**
* Creates a new resolved task.
* @returns A resolved task.
*/
static resolve(): Task<void>
/**
* Creates a new resolved task for the provided value.
* @param value A task.
* @returns A task whose internal state matches the provided task.
*/
static resolve<T>(value: T | PromiseLike<T>): Task<T>
static resolve<T>(value?: T | PromiseLike<T>): Task<T>{
const task = new Task<T>(TaskNoInit as any)
task.#p = Promise.resolve(value!)
task.#finished = true
return task
}
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
static reject<T = never>(reason?: any): Task<T> {
const task = new Task<T>(TaskNoInit as any)
task.#p = Promise.reject(reason)
task.#finished = true
return task
}
/** Wait or cancel all task */
static all<T extends any[]>(token: CancelToken, ...args: T): Task<{ [K in keyof T]: T[K] extends PromiseLike<infer V> ? V : T[K] }> {
return Task.exec<any>(token, (self, res) => {
const fs: (() => void)[] = [];
(async () => {
try {
await Promise.all(args.map(v => {
if ('cancel' in v) {
const f = () => v.cancel()
fs.push(f)
self.reg(f)
}
return v
})).then(res)
} catch (e) {
for (const f of fs) {
f()
}
throw e
} finally {
for (const f of fs) {
self.unReg(f)
}
}
})()
})
}
/** Wait or cancel all task */
all<T extends any[]>(...args: T): Task<{ [K in keyof T]: T[K] extends PromiseLike<infer V> ? V : T[K] }> {
return Task.all(this, ...args)
}
/** Wait one and cancel other task */
static race<T>(token: CancelToken, ...args: T[]): Task<T extends PromiseLike<infer U> ? U : T> {
return Task.exec<any>(token, (self, res) => {
const fs: (() => void)[] = [];
(async () => {
try {
await Promise.race(args.map(v => {
if ('cancel' in v) {
const f = () => (v as any).cancel()
fs.push(f)
self.reg()
}
return v
})).then(res)
} finally {
for (const f of fs) {
f()
self.unReg(f)
}
}
})()
})
}
/** Wait one and cancel other task */
race<T>(...args: T[]): Task<T extends PromiseLike<infer U> ? U : T> {
return Task.race(this, ...args)
}
static async scope<T extends TaskLike<any>>(token: CancelToken, promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
static async scope<T extends PromiseLike<any>>(token: CancelToken, promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
static async scope<T>(token: CancelToken, promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
static async scope<T>(token: CancelToken, promise: T): Promise<T extends PromiseLike<infer R> ? R : T> {
let f: (() => void) | undefined
if ('cancel' in promise) {
f = () => (promise as any).cancel()
token.reg(f)
}
try {
return await (promise as any)
} finally {
if (f != null) token.unReg(f)
}
}
scope<T extends TaskLike<any>>(promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
scope<T extends PromiseLike<any>>(promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
scope<T>(promise: T): Promise<T extends PromiseLike<infer R> ? R : T>
scope<T>(promise: T): Promise<T extends PromiseLike<infer R> ? R : T> {
return Task.scope(this, promise)
}
}
Task.prototype[Symbol.toStringTag] = 'Task'