@buttercup-fork/channel-queue 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +182 -2
- package/dist/Channel.d.ts +134 -0
- package/dist/Channel.js +293 -0
- package/dist/ChannelQueue.d.ts +45 -0
- package/dist/ChannelQueue.js +74 -0
- package/dist/ParallelChannel.d.ts +39 -0
- package/dist/ParallelChannel.js +97 -0
- package/dist/Task.d.ts +69 -0
- package/dist/Task.js +132 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/tools.d.ts +1 -0
- package/dist/tools.js +20 -0
- package/dist/types.d.ts +28 -0
- package/dist/types.js +27 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 Buttercup
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,183 @@
|
|
|
1
|
-
#
|
|
1
|
+
# channel-queue
|
|
2
|
+
A queue management library with channels.
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+

|
|
5
|
+
|
|
6
|
+
## About
|
|
7
|
+
|
|
8
|
+
This library provides a queue system, organised by channels (or "topics"), that allows for finer-grain control over asynchronous method execution. It allows for queuing tasks by channels (string-based names) - tasks executing sequentially when the previous task is done. It also allows for 3 priority levels : **normal**, **high** and **tail**.
|
|
9
|
+
|
|
10
|
+
Check out the [API documentation](API.md).
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
Simply run:
|
|
15
|
+
|
|
16
|
+
```shell
|
|
17
|
+
npm install @buttercup-fork/channel-queue --save
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The fork is published on npm as `@buttercup-fork/channel-queue` (`@buttercup/channel-queue` on npm is upstream's 1.5.0). It is an ES module and needs NodeJS 22 or newer (or a browser or React Native).
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
The simplest usage is to just queue some tasks:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { ChannelQueue } from "@buttercup-fork/channel-queue";
|
|
27
|
+
|
|
28
|
+
const queue = new ChannelQueue();
|
|
29
|
+
const work = queue.channel("myChannel").enqueue(() => 123);
|
|
30
|
+
// 'work' will resolve with 123
|
|
31
|
+
|
|
32
|
+
const someChannel = queue.channel("someChannel");
|
|
33
|
+
someChannel.enqueue(job1);
|
|
34
|
+
someChannel.enqueue(job2);
|
|
35
|
+
someChannel.enqueue(job3);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
You can push tasks above others by setting them as high-priority:
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
import { ChannelQueue, TaskPriority } from "@buttercup-fork/channel-queue";
|
|
42
|
+
|
|
43
|
+
const queue = new ChannelQueue();
|
|
44
|
+
const workChannel = queue.channel("work");
|
|
45
|
+
// some other tasks added to the queue...
|
|
46
|
+
workChannel.enqueue(importantJobMethod, TaskPriority.High).then(result => {
|
|
47
|
+
// 'result' is the resolved result from the 'importantJobMethod' function
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Tasks can also be run as "low" priority or at the **tail** end of the queue:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { ChannelQueue, TaskPriority } from "@buttercup-fork/channel-queue";
|
|
55
|
+
|
|
56
|
+
const queue = new ChannelQueue();
|
|
57
|
+
const workChannel = queue.channel("work");
|
|
58
|
+
// some other tasks added to the queue...
|
|
59
|
+
workChannel.enqueue(runNearEnd, TaskPriority.Tail);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Error Handling
|
|
63
|
+
|
|
64
|
+
Regardless whether an enqueued task fails or not, the channel will continue processing after it's done.
|
|
65
|
+
|
|
66
|
+
By default, if the task enqueued in `enqueue` throws an error, it will throw at the `enqueue` call:
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
// The following throws:
|
|
70
|
+
await channel.enqueue(() => Promise.reject(new Error("Fails!")));
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Always handle that promise. A failing task whose promise nobody awaits or catches is an unhandled rejection, and NodeJS ends the process on one by default:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
// Don't: if the task fails, NodeJS exits
|
|
77
|
+
channel.enqueue(mightFail);
|
|
78
|
+
// Do:
|
|
79
|
+
channel.enqueue(mightFail).catch(handleError);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
You can disable enqueued functions throwing errors by setting `tasksThrow` to `false`:
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
channel.tasksThrow = false;
|
|
86
|
+
// The following will not throw:
|
|
87
|
+
await channel.enqueue(() => Promise.reject(new Error("Fails!")));
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Disabling this is really only useful if you use `waitForEmpty` with the `throwForFailures` set to `true`. This allows you to delay error handling until the channel is waited upon:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
channel.tasksThrow = false;
|
|
94
|
+
channel.enqueue(() => /* ... */)
|
|
95
|
+
channel.enqueue(() => Promise.reject(new Error("Fails!")));
|
|
96
|
+
|
|
97
|
+
// Later:
|
|
98
|
+
await channel.waitForEmpty({ throwForFailures: true });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`waitForEmpty({ throwForFailures: true })` rejects with the first failure since the last wait. Each failure is reported once, and at most 100 unreported failures are kept. Both options work the same on a `ParallelChannel`.
|
|
102
|
+
|
|
103
|
+
### Time Limits
|
|
104
|
+
|
|
105
|
+
`enqueue` takes an optional time limit in milliseconds as its fourth argument:
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { ErrorCode } from "@buttercup-fork/channel-queue";
|
|
109
|
+
import { Layerr } from "layerr";
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
await channel.enqueue(slowTask, undefined, undefined, 5000);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
if (Layerr.info(err).code === ErrorCode.TaskTimeout) {
|
|
115
|
+
// took longer than 5 s
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
A time limit does **not** stop the task. When it runs out, the promise rejects and the channel starts the next task, but the timed-out function keeps running and its side effects still happen. Make the task itself stop (an `AbortSignal`, for example) if that matters.
|
|
121
|
+
|
|
122
|
+
### Stacking
|
|
123
|
+
Items can be "stacked": a stack name allows only 1 pending task in the queue. While a task with that stack name is still waiting, a new `enqueue` call with the same name adds nothing and returns the waiting task's promise. Once that task has started, the next call queues a new one. The stack is the third argument:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { ChannelQueue } from "@buttercup-fork/channel-queue";
|
|
127
|
+
|
|
128
|
+
const queue = new ChannelQueue();
|
|
129
|
+
const workChannel = queue.channel("work");
|
|
130
|
+
|
|
131
|
+
const promise1 = workChannel.enqueue(saveWorkFn, undefined, /* Stack ID */ "save");
|
|
132
|
+
const promise2 = workChannel.enqueue(saveWorkFn, undefined, "save");
|
|
133
|
+
const promise3 = workChannel.enqueue(saveWorkFn, undefined, "save");
|
|
134
|
+
// All three are the same promise: the first task had not started yet when
|
|
135
|
+
// the other two calls came, so saveWorkFn runs once
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Parallel Execution
|
|
139
|
+
Tasks can be run in parallel using the `ParallelChannel` class. You can create a parallel channel, in place of a regular channel, by calling `ChannelQueue#createParallelChannel`:
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
import { ChannelQueue } from "@buttercup-fork/channel-queue";
|
|
143
|
+
|
|
144
|
+
const queue = new ChannelQueue();
|
|
145
|
+
const workChannel = queue.createParallelChannel("work");
|
|
146
|
+
workChannel.enqueue(someTask);
|
|
147
|
+
|
|
148
|
+
// The same channel can be fetched later using the familiar channel() method:
|
|
149
|
+
queue.channel("work"); // The parallel channel
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Parallel channels, like their name implies, can run tasks in parallel. Instead of running them head-to-tail like regular channels, parallel channels can execute many tasks side-by-side. You can also limit them to a certain number of _threads_ (default is 2) by calling `queue.createParallelChannel("name", 5)` (where `5` is the maximum number of simultaneous tasks). A task added while the channel runs starts at once when a slot is free. `parallelism` must be a number of at least 1; anything else throws.
|
|
153
|
+
|
|
154
|
+
Parallel channels by default do not run tasks of different priorities simultaneously. This means that if the current running tasks are high-priority, no normal priority tasks will be started. This feature can be disabled by running `parallelChannel.canRunAcrossTaskTypes = true`.
|
|
155
|
+
|
|
156
|
+
### Waiting and Clearing
|
|
157
|
+
|
|
158
|
+
You can wait for a channel to empty (having all tasks completed) by using `waitForEmpty`:
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
channel.enqueue(someTask);
|
|
162
|
+
channel.enqueue(someTask);
|
|
163
|
+
|
|
164
|
+
// Later:
|
|
165
|
+
await channel.waitForEmpty();
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
You can clear all enqueued items in a `Channel` by calling `clear()`:
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
queue.channel("myChannel").clear();
|
|
172
|
+
// Or only one priority:
|
|
173
|
+
queue.channel("myChannel").clear(TaskPriority.Tail);
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`clear()` removes tasks that have not started; running tasks finish as normal. The promise of each removed task rejects with an error whose code is `ErrorCode.TaskCleared`, so code awaiting it does not hang. A caller that kept no promise gets no unhandled rejection from this.
|
|
177
|
+
|
|
178
|
+
## Development & Supported Node Versions
|
|
179
|
+
This library needs NodeJS **22** or newer; CI tests NodeJS 22 and 24.
|
|
180
|
+
|
|
181
|
+
To contribute, clone this project and run `npm install` before beginning development.
|
|
182
|
+
|
|
183
|
+
To test, simply run `npm test`.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { EventEmitter } from "eventemitter3";
|
|
2
|
+
import { Task } from "./Task.js";
|
|
3
|
+
import { Callable, TaskPriority } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Channel class (queue)
|
|
6
|
+
* @augments EventEmitter
|
|
7
|
+
*/
|
|
8
|
+
export declare class Channel extends EventEmitter {
|
|
9
|
+
private _autostart;
|
|
10
|
+
private _name;
|
|
11
|
+
private _running;
|
|
12
|
+
protected _taskErrors: Error[];
|
|
13
|
+
private _tasks;
|
|
14
|
+
private _tasksThrow;
|
|
15
|
+
/**
|
|
16
|
+
* Constructor for a Channel
|
|
17
|
+
* @param {String} name The name of the channel
|
|
18
|
+
* @memberof Channel
|
|
19
|
+
*/
|
|
20
|
+
constructor(name: string);
|
|
21
|
+
/**
|
|
22
|
+
* Whether the execution should start automatically or not
|
|
23
|
+
* Defaults to true
|
|
24
|
+
* @type {Boolean}
|
|
25
|
+
* @memberof Channel
|
|
26
|
+
*/
|
|
27
|
+
get autostart(): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Whether the queue is empty or not
|
|
30
|
+
* @type {Boolean}
|
|
31
|
+
* @readonly
|
|
32
|
+
* @memberof Channel
|
|
33
|
+
*/
|
|
34
|
+
get isEmpty(): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Whether the queue is currently running or not
|
|
37
|
+
* @type {Boolean}
|
|
38
|
+
* @readonly
|
|
39
|
+
* @memberof Channel
|
|
40
|
+
*/
|
|
41
|
+
get isRunning(): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* The name of the channel
|
|
44
|
+
* @type {String}
|
|
45
|
+
* @readonly
|
|
46
|
+
* @memberof Channel
|
|
47
|
+
*/
|
|
48
|
+
get name(): string;
|
|
49
|
+
/**
|
|
50
|
+
* Array of tasks (in queue)
|
|
51
|
+
* @type {Array.<Task>}
|
|
52
|
+
* @readonly
|
|
53
|
+
* @memberof Channel
|
|
54
|
+
*/
|
|
55
|
+
get tasks(): Task[];
|
|
56
|
+
/**
|
|
57
|
+
* Whether or not tasks throw errors
|
|
58
|
+
* @type {Boolean}
|
|
59
|
+
* @memberof Channel
|
|
60
|
+
*/
|
|
61
|
+
get tasksThrow(): boolean;
|
|
62
|
+
set autostart(auto: boolean);
|
|
63
|
+
set isRunning(isRunning: boolean);
|
|
64
|
+
set tasksThrow(tasksThrow: boolean);
|
|
65
|
+
/**
|
|
66
|
+
* Remove all pending tasks from the channel
|
|
67
|
+
* @param {String=} priorityType Optional priority type to clear
|
|
68
|
+
* only tasks with a certain priority value
|
|
69
|
+
* @memberof Channel
|
|
70
|
+
*/
|
|
71
|
+
clear(priorityType?: TaskPriority): void;
|
|
72
|
+
/**
|
|
73
|
+
* Enqueues a function
|
|
74
|
+
* @param {Function|Promise} item The item to place into the queue
|
|
75
|
+
* @param {TaskPriority=} type The task priority to use
|
|
76
|
+
* @param {String=} stack The stack name
|
|
77
|
+
* @param {Number=} timeout Optional millisecond time-limt
|
|
78
|
+
* @returns {Promise} A promise that eventually resolves with the result from the
|
|
79
|
+
* enqueued function or promise
|
|
80
|
+
* @memberof Channel
|
|
81
|
+
*/
|
|
82
|
+
enqueue<T>(item: Callable<T>, type?: TaskPriority, stack?: string, timeout?: number): Promise<T>;
|
|
83
|
+
/**
|
|
84
|
+
* Get all task items for a stack name
|
|
85
|
+
* @param {String} stack The stack name
|
|
86
|
+
* @returns {Array.<Task>} An array of task instances
|
|
87
|
+
* @memberof Channel
|
|
88
|
+
*/
|
|
89
|
+
getStackedItems(stack: string): Task[];
|
|
90
|
+
/**
|
|
91
|
+
* Get the next queued Task instance
|
|
92
|
+
* This modifies the task queue by removing the task
|
|
93
|
+
* @returns {Task|undefined} A task instance if there are any in queue
|
|
94
|
+
* @memberof Channel
|
|
95
|
+
*/
|
|
96
|
+
retrieveNextItem(): Task | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Sort the tasks
|
|
99
|
+
* @memberof Channel
|
|
100
|
+
*/
|
|
101
|
+
sort(): void;
|
|
102
|
+
/**
|
|
103
|
+
* Start processing the queue
|
|
104
|
+
* Will automatically return early if queue has already started
|
|
105
|
+
* @fires Channel#started
|
|
106
|
+
* @fires Channel#stopped
|
|
107
|
+
* @returns {Boolean} Returns true if started, false if already started
|
|
108
|
+
* @memberof Channel
|
|
109
|
+
*/
|
|
110
|
+
start(): boolean;
|
|
111
|
+
/**
|
|
112
|
+
* Wait for the queue to become empty
|
|
113
|
+
* @returns {Promise}
|
|
114
|
+
*/
|
|
115
|
+
waitForEmpty(opts?: {
|
|
116
|
+
throwForFailures?: boolean;
|
|
117
|
+
}): Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Put a task into its sorted place in the queue
|
|
120
|
+
* The queue is always sorted, so a binary search finds the place without
|
|
121
|
+
* sorting the whole queue on every enqueue. The task goes after every task
|
|
122
|
+
* it compares equal to: the same order a stable sort after a push gives.
|
|
123
|
+
* @param task The task to insert
|
|
124
|
+
* @private
|
|
125
|
+
*/
|
|
126
|
+
_insertTask(task: Task): void;
|
|
127
|
+
/**
|
|
128
|
+
* Keep a finished task's error for waitForEmpty({ throwForFailures })
|
|
129
|
+
* @param item The task that finished
|
|
130
|
+
* @protected
|
|
131
|
+
*/
|
|
132
|
+
_recordError(item: Task): void;
|
|
133
|
+
_runNextItem(): void;
|
|
134
|
+
}
|
package/dist/Channel.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { EventEmitter } from "eventemitter3";
|
|
2
|
+
import { Layerr } from "layerr";
|
|
3
|
+
import { Task } from "./Task.js";
|
|
4
|
+
import { ErrorCode, TaskPriority } from "./types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Failures kept for waitForEmpty({ throwForFailures }) until a wait reports them
|
|
7
|
+
*/
|
|
8
|
+
const MAX_KEPT_ERRORS = 100;
|
|
9
|
+
/**
|
|
10
|
+
* Compare two tasks for sorting
|
|
11
|
+
* @param {Task} taskA A task
|
|
12
|
+
* @param {Task} taskB Another task
|
|
13
|
+
* @returns {Number} The sorting operation regarding the provided tasks
|
|
14
|
+
* @private
|
|
15
|
+
* @static
|
|
16
|
+
* @memberof Channel
|
|
17
|
+
*/
|
|
18
|
+
function compareTasks(taskA, taskB) {
|
|
19
|
+
const { type: typeA, created: createdA } = taskA;
|
|
20
|
+
const { type: typeB, created: createdB } = taskB;
|
|
21
|
+
// Sort by priority:
|
|
22
|
+
if (typeA === TaskPriority.High && typeB !== TaskPriority.High) {
|
|
23
|
+
// A is high priority, and B isn't
|
|
24
|
+
return -1;
|
|
25
|
+
}
|
|
26
|
+
else if (typeB === TaskPriority.High && typeA !== TaskPriority.High) {
|
|
27
|
+
// B is high priority, and A isn't
|
|
28
|
+
return 1;
|
|
29
|
+
}
|
|
30
|
+
else if (typeB === TaskPriority.Tail && typeA !== TaskPriority.Tail) {
|
|
31
|
+
// B is a tail-task, and A isn't
|
|
32
|
+
return -1;
|
|
33
|
+
}
|
|
34
|
+
else if (typeA === TaskPriority.Tail && typeB !== TaskPriority.Tail) {
|
|
35
|
+
// A is a tail-task, and B isn't
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
// Sort by created time:
|
|
39
|
+
if (createdA < createdB) {
|
|
40
|
+
// A is older
|
|
41
|
+
return -1;
|
|
42
|
+
}
|
|
43
|
+
else if (createdB < createdA) {
|
|
44
|
+
// B is older
|
|
45
|
+
return 1;
|
|
46
|
+
}
|
|
47
|
+
// Equal priority
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Channel class (queue)
|
|
52
|
+
* @augments EventEmitter
|
|
53
|
+
*/
|
|
54
|
+
export class Channel extends EventEmitter {
|
|
55
|
+
/**
|
|
56
|
+
* Constructor for a Channel
|
|
57
|
+
* @param {String} name The name of the channel
|
|
58
|
+
* @memberof Channel
|
|
59
|
+
*/
|
|
60
|
+
constructor(name) {
|
|
61
|
+
super();
|
|
62
|
+
this._taskErrors = [];
|
|
63
|
+
this._tasksThrow = true;
|
|
64
|
+
if (typeof name !== "string" || name.length <= 0) {
|
|
65
|
+
throw new Error("Failed creating Channel: Invalid or empty name");
|
|
66
|
+
}
|
|
67
|
+
this._name = name;
|
|
68
|
+
this._tasks = [];
|
|
69
|
+
this._running = false;
|
|
70
|
+
this._autostart = true;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Whether the execution should start automatically or not
|
|
74
|
+
* Defaults to true
|
|
75
|
+
* @type {Boolean}
|
|
76
|
+
* @memberof Channel
|
|
77
|
+
*/
|
|
78
|
+
get autostart() {
|
|
79
|
+
return this._autostart;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Whether the queue is empty or not
|
|
83
|
+
* @type {Boolean}
|
|
84
|
+
* @readonly
|
|
85
|
+
* @memberof Channel
|
|
86
|
+
*/
|
|
87
|
+
get isEmpty() {
|
|
88
|
+
return !this.isRunning && this.tasks.length === 0;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Whether the queue is currently running or not
|
|
92
|
+
* @type {Boolean}
|
|
93
|
+
* @readonly
|
|
94
|
+
* @memberof Channel
|
|
95
|
+
*/
|
|
96
|
+
get isRunning() {
|
|
97
|
+
return this._running;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The name of the channel
|
|
101
|
+
* @type {String}
|
|
102
|
+
* @readonly
|
|
103
|
+
* @memberof Channel
|
|
104
|
+
*/
|
|
105
|
+
get name() {
|
|
106
|
+
return this._name;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Array of tasks (in queue)
|
|
110
|
+
* @type {Array.<Task>}
|
|
111
|
+
* @readonly
|
|
112
|
+
* @memberof Channel
|
|
113
|
+
*/
|
|
114
|
+
get tasks() {
|
|
115
|
+
return this._tasks;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Whether or not tasks throw errors
|
|
119
|
+
* @type {Boolean}
|
|
120
|
+
* @memberof Channel
|
|
121
|
+
*/
|
|
122
|
+
get tasksThrow() {
|
|
123
|
+
return this._tasksThrow;
|
|
124
|
+
}
|
|
125
|
+
set autostart(auto) {
|
|
126
|
+
this._autostart = !!auto;
|
|
127
|
+
}
|
|
128
|
+
set isRunning(isRunning) {
|
|
129
|
+
this._running = isRunning;
|
|
130
|
+
}
|
|
131
|
+
set tasksThrow(tasksThrow) {
|
|
132
|
+
this._tasksThrow = tasksThrow;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Remove all pending tasks from the channel
|
|
136
|
+
* @param {String=} priorityType Optional priority type to clear
|
|
137
|
+
* only tasks with a certain priority value
|
|
138
|
+
* @memberof Channel
|
|
139
|
+
*/
|
|
140
|
+
clear(priorityType) {
|
|
141
|
+
const removed = [];
|
|
142
|
+
for (let i = this.tasks.length - 1; i >= 0; i -= 1) {
|
|
143
|
+
if (!priorityType || this.tasks[i].type === priorityType) {
|
|
144
|
+
removed.push(...this.tasks.splice(i, 1));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Settle the callers' promises: a removed task never runs, so its promise
|
|
148
|
+
// would otherwise stay pending for good. A caller that awaits it gets the
|
|
149
|
+
// rejection; the no-op handler stops a caller that didn't keep the promise
|
|
150
|
+
// from getting an unhandled rejection, which ends a NodeJS process.
|
|
151
|
+
for (const task of removed.reverse()) {
|
|
152
|
+
task.queuedPromise.catch(() => { });
|
|
153
|
+
task.cancel(new Layerr({ info: { code: ErrorCode.TaskCleared } }, "Task was cleared from the queue before it ran"));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Enqueues a function
|
|
158
|
+
* @param {Function|Promise} item The item to place into the queue
|
|
159
|
+
* @param {TaskPriority=} type The task priority to use
|
|
160
|
+
* @param {String=} stack The stack name
|
|
161
|
+
* @param {Number=} timeout Optional millisecond time-limt
|
|
162
|
+
* @returns {Promise} A promise that eventually resolves with the result from the
|
|
163
|
+
* enqueued function or promise
|
|
164
|
+
* @memberof Channel
|
|
165
|
+
*/
|
|
166
|
+
enqueue(item, type = TaskPriority.Normal, stack, timeout) {
|
|
167
|
+
if (stack) {
|
|
168
|
+
const stackItems = this.getStackedItems(stack);
|
|
169
|
+
if (stackItems.length > 0) {
|
|
170
|
+
return stackItems[stackItems.length - 1].queuedPromise;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const task = new Task(item, type, stack);
|
|
174
|
+
if (typeof timeout === "number" && timeout >= 0) {
|
|
175
|
+
task.timeLimit = timeout;
|
|
176
|
+
}
|
|
177
|
+
this._insertTask(task);
|
|
178
|
+
if (this.autostart) {
|
|
179
|
+
this.start();
|
|
180
|
+
}
|
|
181
|
+
return task.queuedPromise;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Get all task items for a stack name
|
|
185
|
+
* @param {String} stack The stack name
|
|
186
|
+
* @returns {Array.<Task>} An array of task instances
|
|
187
|
+
* @memberof Channel
|
|
188
|
+
*/
|
|
189
|
+
getStackedItems(stack) {
|
|
190
|
+
return this.tasks.filter(task => task.stack && task.stack === stack);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Get the next queued Task instance
|
|
194
|
+
* This modifies the task queue by removing the task
|
|
195
|
+
* @returns {Task|undefined} A task instance if there are any in queue
|
|
196
|
+
* @memberof Channel
|
|
197
|
+
*/
|
|
198
|
+
retrieveNextItem() {
|
|
199
|
+
return this.tasks.shift();
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Sort the tasks
|
|
203
|
+
* @memberof Channel
|
|
204
|
+
*/
|
|
205
|
+
sort() {
|
|
206
|
+
this.tasks.sort(compareTasks);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Start processing the queue
|
|
210
|
+
* Will automatically return early if queue has already started
|
|
211
|
+
* @fires Channel#started
|
|
212
|
+
* @fires Channel#stopped
|
|
213
|
+
* @returns {Boolean} Returns true if started, false if already started
|
|
214
|
+
* @memberof Channel
|
|
215
|
+
*/
|
|
216
|
+
start() {
|
|
217
|
+
if (this.isRunning) {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
this.emit("started");
|
|
221
|
+
this.isRunning = true;
|
|
222
|
+
setTimeout(() => this._runNextItem(), 0);
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Wait for the queue to become empty
|
|
227
|
+
* @returns {Promise}
|
|
228
|
+
*/
|
|
229
|
+
async waitForEmpty(opts = {}) {
|
|
230
|
+
const { throwForFailures = false } = opts;
|
|
231
|
+
await new Promise(resolve => {
|
|
232
|
+
if (this.isEmpty)
|
|
233
|
+
return resolve();
|
|
234
|
+
this.once("stopped", () => {
|
|
235
|
+
resolve();
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
// Each failure is reported once: the next wait starts with a clean list
|
|
239
|
+
const errors = this._taskErrors.splice(0, Infinity);
|
|
240
|
+
if (throwForFailures && errors.length > 0) {
|
|
241
|
+
throw new Layerr(errors[0], "Enqueued task failed");
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Put a task into its sorted place in the queue
|
|
246
|
+
* The queue is always sorted, so a binary search finds the place without
|
|
247
|
+
* sorting the whole queue on every enqueue. The task goes after every task
|
|
248
|
+
* it compares equal to: the same order a stable sort after a push gives.
|
|
249
|
+
* @param task The task to insert
|
|
250
|
+
* @private
|
|
251
|
+
*/
|
|
252
|
+
_insertTask(task) {
|
|
253
|
+
const tasks = this.tasks;
|
|
254
|
+
let low = 0;
|
|
255
|
+
let high = tasks.length;
|
|
256
|
+
while (low < high) {
|
|
257
|
+
const middle = (low + high) >>> 1;
|
|
258
|
+
if (compareTasks(tasks[middle], task) <= 0) {
|
|
259
|
+
low = middle + 1;
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
high = middle;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
tasks.splice(low, 0, task);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Keep a finished task's error for waitForEmpty({ throwForFailures })
|
|
269
|
+
* @param item The task that finished
|
|
270
|
+
* @protected
|
|
271
|
+
*/
|
|
272
|
+
_recordError(item) {
|
|
273
|
+
// Bounded: with tasksThrow off and nobody waiting, failures would pile up
|
|
274
|
+
if (item.error && this._taskErrors.length < MAX_KEPT_ERRORS) {
|
|
275
|
+
this._taskErrors.push(item.error);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
_runNextItem() {
|
|
279
|
+
const item = this.retrieveNextItem();
|
|
280
|
+
if (!item) {
|
|
281
|
+
this.isRunning = false;
|
|
282
|
+
this.emit("stopped");
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
item.execute(this._tasksThrow)
|
|
286
|
+
.then(() => this._recordError(item))
|
|
287
|
+
.then(() => this._runNextItem())
|
|
288
|
+
.catch(err => {
|
|
289
|
+
console.error(err);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { EventEmitter } from "eventemitter3";
|
|
2
|
+
import { Channel } from "./Channel.js";
|
|
3
|
+
import { ParallelChannel } from "./ParallelChannel.js";
|
|
4
|
+
/**
|
|
5
|
+
* ChannelQueue class, for managing channels
|
|
6
|
+
* @augments EventEmitter
|
|
7
|
+
*/
|
|
8
|
+
export declare class ChannelQueue extends EventEmitter {
|
|
9
|
+
private _channels;
|
|
10
|
+
constructor();
|
|
11
|
+
/**
|
|
12
|
+
* The channels
|
|
13
|
+
* @type {Object}
|
|
14
|
+
*/
|
|
15
|
+
get channels(): Record<string, Channel | ParallelChannel>;
|
|
16
|
+
/**
|
|
17
|
+
* Create a new channel
|
|
18
|
+
* @param {String} name The channel name
|
|
19
|
+
* @returns {Channel} The new channel
|
|
20
|
+
* @throws {Error} Throws if the channel already exists
|
|
21
|
+
*/
|
|
22
|
+
createChannel(name: string): Channel;
|
|
23
|
+
/**
|
|
24
|
+
* Create a new parallel channel
|
|
25
|
+
* Creates a special channel that supports running several tasks in parallel.
|
|
26
|
+
* @param {String} name The name of the channel
|
|
27
|
+
* @param {Number=} parallelism Optional number of maximum parallel tasks
|
|
28
|
+
* @returns {ParallelChannel} The new channel
|
|
29
|
+
* @throws {Error} Throws if the channel already exists
|
|
30
|
+
*/
|
|
31
|
+
createParallelChannel(name: string, parallelism?: number): ParallelChannel;
|
|
32
|
+
/**
|
|
33
|
+
* Get channel by name
|
|
34
|
+
* Creates a new channel automatically if it doesn't yet exist
|
|
35
|
+
* @param {String} name The channel name
|
|
36
|
+
* @returns {Channel} The channel which was requested
|
|
37
|
+
*/
|
|
38
|
+
channel(name: string): Channel;
|
|
39
|
+
/**
|
|
40
|
+
* Check if a channel exists
|
|
41
|
+
* @param {String} name The name of the channel
|
|
42
|
+
* @returns {Boolean} True if it exists
|
|
43
|
+
*/
|
|
44
|
+
channelExists(name: string): boolean;
|
|
45
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { EventEmitter } from "eventemitter3";
|
|
2
|
+
import { Channel } from "./Channel.js";
|
|
3
|
+
import { ParallelChannel } from "./ParallelChannel.js";
|
|
4
|
+
/**
|
|
5
|
+
* ChannelQueue class, for managing channels
|
|
6
|
+
* @augments EventEmitter
|
|
7
|
+
*/
|
|
8
|
+
export class ChannelQueue extends EventEmitter {
|
|
9
|
+
constructor() {
|
|
10
|
+
super();
|
|
11
|
+
// No prototype: a channel named "__proto__" or "hasOwnProperty" is a plain key
|
|
12
|
+
this._channels = Object.create(null);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The channels
|
|
16
|
+
* @type {Object}
|
|
17
|
+
*/
|
|
18
|
+
get channels() {
|
|
19
|
+
return this._channels;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Create a new channel
|
|
23
|
+
* @param {String} name The channel name
|
|
24
|
+
* @returns {Channel} The new channel
|
|
25
|
+
* @throws {Error} Throws if the channel already exists
|
|
26
|
+
*/
|
|
27
|
+
createChannel(name) {
|
|
28
|
+
if (this.channelExists(name)) {
|
|
29
|
+
throw new Error(`Cannot create channel: channel already exists: ${name}`);
|
|
30
|
+
}
|
|
31
|
+
this.channels[name] = new Channel(name);
|
|
32
|
+
return this.channels[name];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Create a new parallel channel
|
|
36
|
+
* Creates a special channel that supports running several tasks in parallel.
|
|
37
|
+
* @param {String} name The name of the channel
|
|
38
|
+
* @param {Number=} parallelism Optional number of maximum parallel tasks
|
|
39
|
+
* @returns {ParallelChannel} The new channel
|
|
40
|
+
* @throws {Error} Throws if the channel already exists
|
|
41
|
+
*/
|
|
42
|
+
createParallelChannel(name, parallelism) {
|
|
43
|
+
if (this.channelExists(name)) {
|
|
44
|
+
throw new Error(`Cannot create channel: channel already exists: ${name}`);
|
|
45
|
+
}
|
|
46
|
+
const channel = new ParallelChannel(name);
|
|
47
|
+
// Checked by the setter (0 used to fall back to 2); a refused value creates no channel
|
|
48
|
+
if (parallelism !== undefined) {
|
|
49
|
+
channel.parallelism = parallelism;
|
|
50
|
+
}
|
|
51
|
+
this.channels[name] = channel;
|
|
52
|
+
return channel;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Get channel by name
|
|
56
|
+
* Creates a new channel automatically if it doesn't yet exist
|
|
57
|
+
* @param {String} name The channel name
|
|
58
|
+
* @returns {Channel} The channel which was requested
|
|
59
|
+
*/
|
|
60
|
+
channel(name) {
|
|
61
|
+
if (this.channelExists(name) !== true) {
|
|
62
|
+
return this.createChannel(name);
|
|
63
|
+
}
|
|
64
|
+
return this.channels[name];
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Check if a channel exists
|
|
68
|
+
* @param {String} name The name of the channel
|
|
69
|
+
* @returns {Boolean} True if it exists
|
|
70
|
+
*/
|
|
71
|
+
channelExists(name) {
|
|
72
|
+
return Object.prototype.hasOwnProperty.call(this.channels, name);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Channel } from "./Channel.js";
|
|
2
|
+
import { Task } from "./Task.js";
|
|
3
|
+
/**
|
|
4
|
+
* ParallelChannel class (queue)
|
|
5
|
+
* @augments Channel
|
|
6
|
+
*/
|
|
7
|
+
export declare class ParallelChannel extends Channel {
|
|
8
|
+
private _parallelism;
|
|
9
|
+
private _runningTasks;
|
|
10
|
+
canRunAcrossTaskTypes: boolean;
|
|
11
|
+
constructor(name: string);
|
|
12
|
+
/**
|
|
13
|
+
* Whether the queue is empty or not
|
|
14
|
+
* @type {Boolean}
|
|
15
|
+
* @readonly
|
|
16
|
+
*/
|
|
17
|
+
get isEmpty(): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* The amount of allowed parallel executed tasks
|
|
20
|
+
* @type {Number}
|
|
21
|
+
* @readonly
|
|
22
|
+
*/
|
|
23
|
+
get parallelism(): number;
|
|
24
|
+
/**
|
|
25
|
+
* Get the currently running tasks
|
|
26
|
+
* @type {Array<Task>}
|
|
27
|
+
* @readonly
|
|
28
|
+
*/
|
|
29
|
+
get runningTasks(): Task[];
|
|
30
|
+
set parallelism(count: number);
|
|
31
|
+
/**
|
|
32
|
+
* Start processing the queue. When it is already running, a task added
|
|
33
|
+
* since then starts at once if a slot is free, instead of waiting for a
|
|
34
|
+
* running task to end.
|
|
35
|
+
* @returns {Boolean} Returns true if started, false if already started
|
|
36
|
+
*/
|
|
37
|
+
start(): boolean;
|
|
38
|
+
_runNextItem(): void;
|
|
39
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Channel } from "./Channel.js";
|
|
2
|
+
/**
|
|
3
|
+
* ParallelChannel class (queue)
|
|
4
|
+
* @augments Channel
|
|
5
|
+
*/
|
|
6
|
+
export class ParallelChannel extends Channel {
|
|
7
|
+
constructor(name) {
|
|
8
|
+
super(name);
|
|
9
|
+
this._parallelism = 2;
|
|
10
|
+
this._runningTasks = [];
|
|
11
|
+
this.canRunAcrossTaskTypes = false;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Whether the queue is empty or not
|
|
15
|
+
* @type {Boolean}
|
|
16
|
+
* @readonly
|
|
17
|
+
*/
|
|
18
|
+
get isEmpty() {
|
|
19
|
+
return super.isEmpty && this._runningTasks.length <= 0;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The amount of allowed parallel executed tasks
|
|
23
|
+
* @type {Number}
|
|
24
|
+
* @readonly
|
|
25
|
+
*/
|
|
26
|
+
get parallelism() {
|
|
27
|
+
return this._parallelism;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Get the currently running tasks
|
|
31
|
+
* @type {Array<Task>}
|
|
32
|
+
* @readonly
|
|
33
|
+
*/
|
|
34
|
+
get runningTasks() {
|
|
35
|
+
return this._runningTasks;
|
|
36
|
+
}
|
|
37
|
+
set parallelism(count) {
|
|
38
|
+
// NaN or a string would stop the channel for good (Math.max(NaN, 1) is NaN)
|
|
39
|
+
if (typeof count !== "number" || !Number.isFinite(count) || count < 1) {
|
|
40
|
+
throw new Error(`Invalid parallelism: expected a number of at least 1, got ${count}`);
|
|
41
|
+
}
|
|
42
|
+
this._parallelism = Math.floor(count);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Start processing the queue. When it is already running, a task added
|
|
46
|
+
* since then starts at once if a slot is free, instead of waiting for a
|
|
47
|
+
* running task to end.
|
|
48
|
+
* @returns {Boolean} Returns true if started, false if already started
|
|
49
|
+
*/
|
|
50
|
+
start() {
|
|
51
|
+
if (this.isRunning) {
|
|
52
|
+
setTimeout(() => this._runNextItem(), 0);
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return super.start();
|
|
56
|
+
}
|
|
57
|
+
_runNextItem() {
|
|
58
|
+
const stopChannel = () => {
|
|
59
|
+
this.isRunning = false;
|
|
60
|
+
this.emit("stopped");
|
|
61
|
+
};
|
|
62
|
+
if (this.runningTasks.length === 0 && this.tasks.length === 0) {
|
|
63
|
+
stopChannel();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
let itemsToRun = this.parallelism - this.runningTasks.length;
|
|
67
|
+
if (itemsToRun <= 0) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
while (itemsToRun > 0) {
|
|
71
|
+
// First check to see if any other tasks are running, and whether or not
|
|
72
|
+
// we're allowed to run tasks of different priorities at the same time
|
|
73
|
+
if (!this.canRunAcrossTaskTypes &&
|
|
74
|
+
this.runningTasks.length > 0 &&
|
|
75
|
+
this.tasks.length > 0) {
|
|
76
|
+
const runningType = this.runningTasks[0].type;
|
|
77
|
+
const nextType = this.tasks[0].type;
|
|
78
|
+
if (runningType !== nextType) {
|
|
79
|
+
// Next item is not of the same type, so we'll skip this round
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
itemsToRun -= 1;
|
|
84
|
+
const item = this.retrieveNextItem();
|
|
85
|
+
if (!item) {
|
|
86
|
+
// No item, skip
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
this.runningTasks.push(item);
|
|
90
|
+
item.execute(this.tasksThrow).then(() => {
|
|
91
|
+
this.runningTasks.splice(this.runningTasks.indexOf(item), 1);
|
|
92
|
+
this._recordError(item);
|
|
93
|
+
this._runNextItem();
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
package/dist/Task.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Callable, TaskPriority } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Internal Task class, for handling executions
|
|
4
|
+
*/
|
|
5
|
+
export declare class Task {
|
|
6
|
+
private _created;
|
|
7
|
+
private _error;
|
|
8
|
+
private _queuedPromise;
|
|
9
|
+
private _rejectFn;
|
|
10
|
+
private _resolveFn;
|
|
11
|
+
private _stack;
|
|
12
|
+
private _target;
|
|
13
|
+
private _timeLimit;
|
|
14
|
+
private _type;
|
|
15
|
+
/**
|
|
16
|
+
* Constructor for a Task
|
|
17
|
+
* @param {Function|Promise} item The item to enqueue
|
|
18
|
+
* @param {TaskPriority=} type The priority to set
|
|
19
|
+
* @param {String=} stack The stack name
|
|
20
|
+
*/
|
|
21
|
+
constructor(item: Callable<any>, type?: TaskPriority, stack?: string | null);
|
|
22
|
+
/**
|
|
23
|
+
* Creation timestamp
|
|
24
|
+
* @type {Number}
|
|
25
|
+
* @readonly
|
|
26
|
+
*/
|
|
27
|
+
get created(): number;
|
|
28
|
+
/**
|
|
29
|
+
* Execution error, if one occurred
|
|
30
|
+
* @type {Error | null}
|
|
31
|
+
*/
|
|
32
|
+
get error(): Error | null;
|
|
33
|
+
/**
|
|
34
|
+
* Promise which resolves when work has completed
|
|
35
|
+
* @type {Promise}
|
|
36
|
+
*/
|
|
37
|
+
get queuedPromise(): Promise<any>;
|
|
38
|
+
/**
|
|
39
|
+
* The stack name
|
|
40
|
+
* @type {String}
|
|
41
|
+
*/
|
|
42
|
+
get stack(): string;
|
|
43
|
+
/**
|
|
44
|
+
* The target function
|
|
45
|
+
* @type {Function}
|
|
46
|
+
*/
|
|
47
|
+
get target(): Callable<any>;
|
|
48
|
+
/**
|
|
49
|
+
* Current time limit
|
|
50
|
+
* @type {Number}
|
|
51
|
+
*/
|
|
52
|
+
get timeLimit(): number;
|
|
53
|
+
/**
|
|
54
|
+
* The task priority type
|
|
55
|
+
* @type {TaskPriority}
|
|
56
|
+
*/
|
|
57
|
+
get type(): TaskPriority;
|
|
58
|
+
set timeLimit(newLimit: number);
|
|
59
|
+
/**
|
|
60
|
+
* Reject the task's promise without running it (it was removed from the queue)
|
|
61
|
+
* @param err The reason
|
|
62
|
+
*/
|
|
63
|
+
cancel(err: Error): void;
|
|
64
|
+
/**
|
|
65
|
+
* Execute the task
|
|
66
|
+
* @returns {Promise}
|
|
67
|
+
*/
|
|
68
|
+
execute(throws?: boolean): Promise<void>;
|
|
69
|
+
}
|
package/dist/Task.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { timeLimit } from "./tools.js";
|
|
2
|
+
import { TaskPriority } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Internal Task class, for handling executions
|
|
5
|
+
*/
|
|
6
|
+
export class Task {
|
|
7
|
+
/**
|
|
8
|
+
* Constructor for a Task
|
|
9
|
+
* @param {Function|Promise} item The item to enqueue
|
|
10
|
+
* @param {TaskPriority=} type The priority to set
|
|
11
|
+
* @param {String=} stack The stack name
|
|
12
|
+
*/
|
|
13
|
+
constructor(item, type = TaskPriority.Normal, stack) {
|
|
14
|
+
this._error = null;
|
|
15
|
+
this._rejectFn = null;
|
|
16
|
+
this._resolveFn = null;
|
|
17
|
+
this._stack = null;
|
|
18
|
+
if (item instanceof Promise !== true && typeof item !== "function") {
|
|
19
|
+
throw new Error("Invalid task item: Expected a Promise or Function");
|
|
20
|
+
}
|
|
21
|
+
this._target = typeof item === "function" ? item : () => item;
|
|
22
|
+
this._stack = stack ?? null;
|
|
23
|
+
this._type = type;
|
|
24
|
+
this._timeLimit = -1;
|
|
25
|
+
this._resolveFn = null;
|
|
26
|
+
this._rejectFn = null;
|
|
27
|
+
this._queuedPromise = new Promise((resolve, reject) => {
|
|
28
|
+
this._resolveFn = resolve;
|
|
29
|
+
this._rejectFn = reject;
|
|
30
|
+
});
|
|
31
|
+
const now = new Date();
|
|
32
|
+
this._created = now.getTime();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creation timestamp
|
|
36
|
+
* @type {Number}
|
|
37
|
+
* @readonly
|
|
38
|
+
*/
|
|
39
|
+
get created() {
|
|
40
|
+
return this._created;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Execution error, if one occurred
|
|
44
|
+
* @type {Error | null}
|
|
45
|
+
*/
|
|
46
|
+
get error() {
|
|
47
|
+
return this._error;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Promise which resolves when work has completed
|
|
51
|
+
* @type {Promise}
|
|
52
|
+
*/
|
|
53
|
+
get queuedPromise() {
|
|
54
|
+
return this._queuedPromise;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The stack name
|
|
58
|
+
* @type {String}
|
|
59
|
+
*/
|
|
60
|
+
get stack() {
|
|
61
|
+
return this._stack;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The target function
|
|
65
|
+
* @type {Function}
|
|
66
|
+
*/
|
|
67
|
+
get target() {
|
|
68
|
+
return this._target;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Current time limit
|
|
72
|
+
* @type {Number}
|
|
73
|
+
*/
|
|
74
|
+
get timeLimit() {
|
|
75
|
+
return this._timeLimit;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The task priority type
|
|
79
|
+
* @type {TaskPriority}
|
|
80
|
+
*/
|
|
81
|
+
get type() {
|
|
82
|
+
return this._type;
|
|
83
|
+
}
|
|
84
|
+
set timeLimit(newLimit) {
|
|
85
|
+
this._timeLimit = newLimit;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Reject the task's promise without running it (it was removed from the queue)
|
|
89
|
+
* @param err The reason
|
|
90
|
+
*/
|
|
91
|
+
cancel(err) {
|
|
92
|
+
this._rejectFn?.(err);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Execute the task
|
|
96
|
+
* @returns {Promise}
|
|
97
|
+
*/
|
|
98
|
+
async execute(throws = true) {
|
|
99
|
+
const fn = this.target;
|
|
100
|
+
let output;
|
|
101
|
+
try {
|
|
102
|
+
output = fn();
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
this._error = err;
|
|
106
|
+
if (throws) {
|
|
107
|
+
this._rejectFn?.(err);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
this._resolveFn?.();
|
|
111
|
+
}
|
|
112
|
+
return Promise.resolve();
|
|
113
|
+
}
|
|
114
|
+
let chainOutput = output instanceof Promise ? output : Promise.resolve(output);
|
|
115
|
+
if (this.timeLimit >= 0) {
|
|
116
|
+
chainOutput = timeLimit(chainOutput, this.timeLimit);
|
|
117
|
+
}
|
|
118
|
+
await chainOutput
|
|
119
|
+
.then(result => {
|
|
120
|
+
this._resolveFn?.(result);
|
|
121
|
+
})
|
|
122
|
+
.catch(err => {
|
|
123
|
+
this._error = err;
|
|
124
|
+
if (throws) {
|
|
125
|
+
this._rejectFn?.(err);
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
this._resolveFn?.();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function timeLimit<T>(promise: Promise<T>, time: number): Promise<T | void>;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Layerr } from "layerr";
|
|
2
|
+
import { ErrorCode } from "./types.js";
|
|
3
|
+
export function timeLimit(promise, time) {
|
|
4
|
+
let timeout;
|
|
5
|
+
return Promise.race([
|
|
6
|
+
promise,
|
|
7
|
+
new Promise((_, reject) => {
|
|
8
|
+
timeout = setTimeout(() => {
|
|
9
|
+
reject(new Layerr({
|
|
10
|
+
info: {
|
|
11
|
+
code: ErrorCode.TaskTimeout
|
|
12
|
+
}
|
|
13
|
+
}, `Timed-out waiting for task: ${time} ms`));
|
|
14
|
+
}, time);
|
|
15
|
+
})
|
|
16
|
+
]).finally(() => {
|
|
17
|
+
// Whether the task finished, failed or timed out, the timer must not stay behind
|
|
18
|
+
clearTimeout(timeout);
|
|
19
|
+
});
|
|
20
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface Callable<R> {
|
|
2
|
+
(...args: any[]): R;
|
|
3
|
+
}
|
|
4
|
+
export declare enum ErrorCode {
|
|
5
|
+
/**
|
|
6
|
+
* The task was removed from the queue by clear() before it ran
|
|
7
|
+
*/
|
|
8
|
+
TaskCleared = "TASKCLEARED",
|
|
9
|
+
TaskTimeout = "TASKTIMEOUT"
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Task Priority
|
|
13
|
+
* @typedef {TaskPriority.Normal|TaskPriority.High|TaskPriority.Tail} TaskPriority
|
|
14
|
+
*/
|
|
15
|
+
export declare enum TaskPriority {
|
|
16
|
+
/**
|
|
17
|
+
* Normal task priority
|
|
18
|
+
*/
|
|
19
|
+
Normal = "normal",
|
|
20
|
+
/**
|
|
21
|
+
* High task priority
|
|
22
|
+
*/
|
|
23
|
+
High = "high-priority",
|
|
24
|
+
/**
|
|
25
|
+
* Task tail-priority
|
|
26
|
+
*/
|
|
27
|
+
Tail = "tail"
|
|
28
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export var ErrorCode;
|
|
2
|
+
(function (ErrorCode) {
|
|
3
|
+
/**
|
|
4
|
+
* The task was removed from the queue by clear() before it ran
|
|
5
|
+
*/
|
|
6
|
+
ErrorCode["TaskCleared"] = "TASKCLEARED";
|
|
7
|
+
ErrorCode["TaskTimeout"] = "TASKTIMEOUT";
|
|
8
|
+
})(ErrorCode || (ErrorCode = {}));
|
|
9
|
+
/**
|
|
10
|
+
* Task Priority
|
|
11
|
+
* @typedef {TaskPriority.Normal|TaskPriority.High|TaskPriority.Tail} TaskPriority
|
|
12
|
+
*/
|
|
13
|
+
export var TaskPriority;
|
|
14
|
+
(function (TaskPriority) {
|
|
15
|
+
/**
|
|
16
|
+
* Normal task priority
|
|
17
|
+
*/
|
|
18
|
+
TaskPriority["Normal"] = "normal";
|
|
19
|
+
/**
|
|
20
|
+
* High task priority
|
|
21
|
+
*/
|
|
22
|
+
TaskPriority["High"] = "high-priority";
|
|
23
|
+
/**
|
|
24
|
+
* Task tail-priority
|
|
25
|
+
*/
|
|
26
|
+
TaskPriority["Tail"] = "tail";
|
|
27
|
+
})(TaskPriority || (TaskPriority = {}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buttercup-fork/channel-queue",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "A queue management library with channels",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"exports": "./dist/index.js",
|
|
7
|
+
"react-native": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"type": "module",
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "npm run clean && tsc",
|
|
12
|
+
"clean": "rimraf dist",
|
|
13
|
+
"format": "prettier --write \"{source,test}/**/*.{js,ts}\"",
|
|
14
|
+
"prepare": "npm run build",
|
|
15
|
+
"prepublishOnly": "npm run build",
|
|
16
|
+
"pretest": "npm run build",
|
|
17
|
+
"test": "npm run test:unit && npm run test:format",
|
|
18
|
+
"test:format": "prettier --check \"{source,test}/**/*.{js,ts}\"",
|
|
19
|
+
"test:unit": "mocha -r test/index.js 'test/unit/**/*.spec.js'"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist/**/*"
|
|
23
|
+
],
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/buttercup-fork/channel-queue.git"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"queue",
|
|
30
|
+
"channel",
|
|
31
|
+
"enqueue",
|
|
32
|
+
"promise",
|
|
33
|
+
"event",
|
|
34
|
+
"emitter"
|
|
35
|
+
],
|
|
36
|
+
"author": "Buttercup <buttercup@codekunde.net>",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=22"
|
|
40
|
+
},
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/buttercup/channel-queue/issues"
|
|
43
|
+
},
|
|
44
|
+
"homepage": "https://github.com/buttercup/channel-queue#readme",
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"eventemitter3": "^5.0.1",
|
|
47
|
+
"layerr": "^3.0.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/node": "^22.20.4",
|
|
51
|
+
"chai": "^6.2.2",
|
|
52
|
+
"chai-as-promised": "^8.0.2",
|
|
53
|
+
"mocha": "^12.0.2",
|
|
54
|
+
"prettier": "^3.9.9",
|
|
55
|
+
"rimraf": "^6.1.3",
|
|
56
|
+
"sinon": "^22.1.0",
|
|
57
|
+
"sleep-promise": "^9.1.0",
|
|
58
|
+
"typescript": "^6.0.3"
|
|
59
|
+
},
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public"
|
|
62
|
+
}
|
|
63
|
+
}
|