-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTaskRunner.ts
525 lines (452 loc) · 12.1 KB
/
TaskRunner.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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { DefaultOptions } from "./DefaultOptions";
import {
AdditionMethods,
Done,
HookDefaults,
RemovalMethods,
RunnerDuration,
RunnerEvents,
RunnerHooks,
RunnerOptions,
TasksCount,
TaskStatus,
TasksWithDone,
TaskWithDone,
} from "./Interface";
import { List } from "./List";
import { Task, Tasks } from "./Task";
import { isArray, isFunction } from "./Utils";
export class TaskRunner<T = any> {
static #instances = 0;
#_busy = false;
#_paused = false;
#_destroyed = false;
readonly #_pending = new List<T>();
readonly #_completed = new List<T>();
readonly #_running = new List<T>();
readonly #_options: RunnerOptions<T>;
readonly #_duration: RunnerDuration = {
start: 0,
end: 0,
total: 0,
};
#_concurrency = 0;
#_taskIds = 0;
set #concurrency(concurrency: number) {
if (!concurrency || concurrency < -1) {
throw new RangeError(
`Invalid range for concurrency. Range should be a positive integer, or -1. Found ${concurrency} instead`
);
}
if (concurrency === -1) {
this.#_concurrency = Infinity;
} else {
this.#_concurrency = concurrency;
}
}
get #total(): number {
return this.#pending + this.#running + this.#completed;
}
get #completed(): number {
return this.#_completed.size;
}
get #pending(): number {
return this.#_pending.size;
}
get #running(): number {
return this.#_running.size;
}
#runHook<
Hook extends keyof RunnerHooks<T>,
Data extends Omit<
Parameters<RunnerHooks<T>[Hook]>[0],
keyof HookDefaults
> extends infer D
? D extends Record<string, never>
? null
: D
: null,
>(
...[hook, data]: Data extends null ? [hook: Hook] : [hook: Hook, data: Data]
) {
(this as any)[hook]?.({
...(data || {}),
tasks: this.tasks,
count: this.count,
duration: this.duration,
});
}
#createTask(task: TaskWithDone<T>): Task<T> {
return new Task(this.#_taskIds++, task);
}
#done(task: Task<T>): Done<T> {
return ((result: T) => {
task.status = TaskStatus.DONE;
this.#_running.removeById(task.id);
this.#_completed.add(task);
this.#runHook(RunnerEvents.DONE, {
task,
result,
});
if (!this.#_paused && !this.#_destroyed) {
return this.#run();
}
if (!this.#running) {
if (this.#_paused) {
return this.#runHook(RunnerEvents.PAUSE);
}
if (this.#_destroyed) {
return this.#runHook(RunnerEvents.DESTROY);
}
}
}) as unknown as Done<T>;
}
#run() {
if (this.#completed !== this.#total) {
if (!this.#_paused && this.#running < this.#_concurrency) {
this.#_busy = true;
const difference = this.#_concurrency - this.#running;
const tasks = this.#_pending.removeRange(0, difference) as Tasks<T>;
tasks.forEach((task) => {
task.status = TaskStatus.RUNNING;
this.#_running.add(task);
task.run(this.#done(task));
/* istanbul ignore next */
this.#runHook(RunnerEvents.RUN, {
task,
});
});
}
} else {
this.#_busy = false;
this.#_duration.end = Date.now();
this.#_duration.total = Math.ceil(
this.#_duration.end - this.#_duration.start
);
/* istanbul ignore next */
this.#runHook(RunnerEvents.END);
}
}
#provideRemovedTasks(removedTasks: Tasks<T> | Task<T> | void): Tasks<T> {
if (isArray(removedTasks)) {
return removedTasks;
}
if (removedTasks) {
return [removedTasks];
}
/* istanbul ignore next */
return [];
}
constructor(options?: Partial<RunnerOptions<T>>) {
this.#_options = {
...DefaultOptions(`Runner-${TaskRunner.#instances++}`),
...options,
};
this.#concurrency = this.#_options.concurrency;
Object.values(RunnerEvents).forEach((value) => {
(this as any)[value] = this.#_options[value];
});
}
/**
* Returns the concurrency of the runner.
*/
public get concurrency(): number {
return this.#_concurrency;
}
/**
* Get whether the runner is busy executing tasks or not.
*/
public get busy(): boolean {
return this.#_busy;
}
/**
* Get whether the runner is paused or not.
*/
public get paused(): boolean {
return this.#_paused;
}
/**
* Get whether the runner is destroyed or not.
*/
public get destroyed(): boolean {
return this.#_destroyed;
}
/**
* Get the counts for the runner
*/
public get count(): TasksCount {
return {
total: this.#total,
completed: this.#completed,
running: this.#running,
pending: this.#pending,
};
}
public get duration(): RunnerDuration {
return {
...this.#_duration,
};
}
/**
* Get the list of tasks of the runner.
*/
public get tasks() {
const completed = this.#_completed.entries();
const pending = this.#_pending.entries();
const running = this.#_running.entries();
return {
completed,
pending,
running,
all: [...running, ...pending, ...completed],
};
}
/**
* Start task execution.
*/
public start(): boolean {
if (this.#_destroyed) {
return false;
}
const previousPause = this.#_paused;
if (previousPause) {
this.#_paused = false;
}
if (this.#_busy) {
return false;
}
this.#_duration.start = Date.now();
/* istanbul ignore next */
if (!previousPause) {
this.#runHook(RunnerEvents.START);
}
this.#run();
return true;
}
/**
* Pause task execution.
*/
public pause(): boolean {
if (this.#_destroyed) {
return false;
}
this.#_paused = true;
return true;
}
/**
* Destroy a runner instance. This will ensure that the current instance is marked as dead, and no additional tasks are run.
*
* This does not affect currently running tasks.
*/
public destroy(): void {
this.#_destroyed = true;
this.#runHook(RunnerEvents.DESTROY);
}
/**
* Set the concurrency value
*/
public setConcurrency(concurrency: number): void {
if (!this.#_destroyed) {
this.#concurrency = concurrency;
this.#run();
}
}
/**
* Add a single task to the end of the list.
*
* ```ts
* console.log(runner.tasks.pending) // []
* runner.add(t1)
* console.log(runner.tasks.pending) // [t1]
* ```
*/
public add(task: TaskWithDone<T>, prepend?: boolean): void {
if (!this.#_destroyed) {
if (!isFunction(task) || task instanceof Task) {
throw new TypeError(
"A task cannot be anything but a function, nor an instance of `Task`. Pass a function instead."
);
} else {
if (prepend) {
this.#_pending.addFirst(this.#createTask(task));
} else {
this.#_pending.add(this.#createTask(task));
}
}
/* istanbul ignore next */
this.#runHook(RunnerEvents.ADD, {
method: prepend ? AdditionMethods.FIRST : AdditionMethods.LAST,
});
}
}
/**
* Add a single task to the beginning of the list.
*
* ```ts
* console.log(runner.tasks.pending) // [t1, t2, t3]
* runner.addFirst(t4)
* console.log(runner.tasks.pending) // [t4, t1, t2, t3]
* ```
*/
public addFirst(task: TaskWithDone<T>): void {
this.add(task, true);
}
/**
* Add a single task at a particular index.
*
* ```ts
* console.log(runner.tasks) // [t1, t2, t3, t4, t5, t6]
* runner.addAt(1, t)
* console.log(runner.tasks.pending) // [t1, t7, t2, t3, t4, t5, t6]
* ```
*/
public addAt(index: number, task: TaskWithDone<T>): void {
if (!this.#_destroyed) {
this.#_pending.addAt(index, this.#createTask(task));
/* istanbul ignore next */
this.#runHook(RunnerEvents.ADD, {
method: AdditionMethods.AT_INDEX,
});
}
}
/**
* Add multiple tasks to the end of the list.
*
* ```ts
* console.log(runner.tasks) // [t1, t2, t3, t4, t5, t6]
* runner.addMultiple([t7, t8, t9, t10, t11, t12])
* console.log(runner.tasks.pending) // [t1, t2, t4, t5, t6, t7, t8, t9, t10, t11, t12]
* ```
*/
public addMultiple(tasks: TasksWithDone<T>, prepend?: boolean): void {
if (!this.#_destroyed) {
this.#_pending.concat(tasks.map(this.#createTask.bind(this)), prepend);
/* istanbul ignore next */
this.#runHook(RunnerEvents.ADD, {
method: prepend
? AdditionMethods.MULTIPLE_FIRST
: AdditionMethods.MULTIPLE_LAST,
});
}
}
/**
* Add multiple tasks to the beginning of the list.
*
* ```ts
* console.log(runner.tasks) // [t1, t2, t3, t4, t5, t6]
* runner.addMultiple([t7, t8, t9, t10, t11, t12])
* console.log(runner.tasks.pending) // [t1, t2, t4, t5, t6, t7, t8, t9, t10, t11, t12]
* ```
*/
public addMultipleFirst(tasks: TasksWithDone<T>): void {
this.addMultiple(tasks, true);
}
/**
* Remove the last pending task in the list.
*
* ```ts
* runner.addMultiple([t1, t2, t3, t4, t5, t6])
* runner.remove()
* console.log(runner.tasks.pending) // [t1, t2, t3, t4, t5]
* ```
*/
public remove(first?: boolean): void {
const removedTasks = first
? this.#_pending.removeFirst()
: this.#_pending.remove();
/* istanbul ignore next */
this.#runHook(RunnerEvents.REMOVE, {
removedTasks: this.#provideRemovedTasks(removedTasks),
method: first ? RemovalMethods.FIRST : RemovalMethods.LAST,
});
}
/**
* Remove the first pending task in the list.
*
* ```ts
* runner.addMultiple([t1, t2, t3, t4, t5, t6])
* runner.removeFirst()
* console.log(runner.tasks.pending) // [t2, t3, t4, t5, t6]
* ```
*/
public removeFirst(): void {
this.remove(true);
}
/**
* Remove a pending task at a particular index.
*
* ```ts
* runner.addMultiple([t1, t2, t3, t4, t5, t6])
* runner.removeAt(2)
* console.log(runner.tasks.pending) // [t1, t2, t4, t5, t6]
* ```
*/
public removeAt(index: number): void {
const removedTasks = this.#_pending.removeAt(index);
/* istanbul ignore next */
this.#runHook(RunnerEvents.REMOVE, {
removedTasks: this.#provideRemovedTasks(removedTasks),
method: RemovalMethods.BY_INDEX,
});
}
/**
* Remove a range of pending tasks. The range is inclusive of the starting index specified.
*
* ```ts
* runner.addMultiple([t1, t2, t3, t4, t5, t6])
* runner.removeRange(2, 2)
* console.log(runner.tasks.pending) // [t1, t4, t5, t6]
* ```
*/
public removeRange(start: number, count: number): void {
const removedTasks = this.#_pending.removeRange(start, count);
/* istanbul ignore next */
this.#runHook(RunnerEvents.REMOVE, {
removedTasks: this.#provideRemovedTasks(removedTasks),
method: RemovalMethods.RANGE,
});
}
/**
* Remove all pending tasks.
*
* ```ts
* runner.addMultiple([t1, t2, t3, t4, t5, t6])
* runner.removeAll()
* console.log(runner.tasks.pending) // []
* ```
*/
public removeAll(): void {
const removedTasks = this.#_pending.clear();
/* istanbul ignore next */
this.#runHook(RunnerEvents.REMOVE, {
removedTasks: this.#provideRemovedTasks(removedTasks),
method: RemovalMethods.ALL,
});
}
/**
* Add a listener to any of the supported events of the runner. Only one listener per event can be attached at any time. Adding another will overwrite the existing listener.
*/
public addListener<E extends RunnerEvents>(
event: `${E}`,
listener: E extends RunnerEvents ? RunnerHooks<T>[E] : never
): void {
if (!this.#_destroyed) {
if (!isFunction(listener)) {
throw new TypeError(
`Invalid listener callback provided. Expected ${event} to be a function, but found ${typeof listener} instead.`
);
}
Object.assign(this, {
[event]: listener,
});
}
}
/**
* Remove a previously registered listener for an event supported by the runner.
*/
public removeListener<E extends `${keyof RunnerHooks<T>}`>(event: E): void {
Object.assign(this, {
[event]: undefined,
});
}
}