@borewit/async-queue 0.1.1 → 1.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.txt +9 -9
- package/README.md +129 -17
- package/lib/queue.d.ts +106 -2
- package/lib/queue.js +227 -17
- package/package.json +65 -47
package/LICENSE.txt
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
The MIT License (MIT)
|
|
2
|
-
|
|
3
|
-
Copyright © 2025 Borewit
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
-
|
|
7
|
-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
-
|
|
9
|
-
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright © 2025 Borewit
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
|
-
[](https://github.com/Borewit/async-queue/actions/workflows/ci.yml)
|
|
2
|
+
[](https://npmjs.org/package/@borewit/async-queue)
|
|
3
|
+
[](https://npmcharts.com/compare/@borewit/async-queue?start=356)
|
|
2
4
|
|
|
3
5
|
# @borewit/async-queue
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
`@borewit/async-queue` is a lightweight, generic, and type-safe asynchronous queue implemented in TypeScript.
|
|
8
|
+
It allows you to enqueue items and retrieve them one at a time using promises, making it ideal for processing events or messages in a first-in-first-out (FIFO) order.
|
|
9
|
+
This is especially handy when reading asynchronous items received via events.
|
|
10
|
+
It has no dependencies.
|
|
6
11
|
|
|
7
12
|
## Features
|
|
8
13
|
|
|
9
14
|
- **Generic & Type-Safe:** Write once and use with any type (e.g., string, number, object).
|
|
10
15
|
- **FIFO Order:** Processes items in the order they were received.
|
|
11
16
|
- **Promise-Based:** Retrieve items asynchronously using promises.
|
|
17
|
+
- **Async Iterable:** Consume items with `for await`, until the queue is closed.
|
|
18
|
+
- **Cancellable:** Stop waiting for an item with an `AbortSignal`.
|
|
12
19
|
- **Event Integration:** Perfect for handling asynchronous events like user actions, network messages, or other event-driven data.
|
|
13
20
|
|
|
14
21
|
## Installation
|
|
@@ -20,7 +27,9 @@ npm install @borewit/async-queue
|
|
|
20
27
|
```
|
|
21
28
|
|
|
22
29
|
## Usage
|
|
23
|
-
|
|
30
|
+
|
|
31
|
+
Below is an example of how to add and read string messages to/from the queue.
|
|
32
|
+
This example simulates asynchronous events (using `setTimeout`) that push string messages into the queue:
|
|
24
33
|
|
|
25
34
|
```ts
|
|
26
35
|
import { AsyncQueue } from '@borewit/async-queue';
|
|
@@ -30,29 +39,57 @@ const queue = new AsyncQueue<string>();
|
|
|
30
39
|
|
|
31
40
|
// Example: Simulate incoming messages via asynchronous events
|
|
32
41
|
function simulateIncomingMessages() {
|
|
33
|
-
setTimeout(() => queue.push(
|
|
34
|
-
setTimeout(() => queue.push(
|
|
35
|
-
setTimeout(() => queue.push(
|
|
42
|
+
setTimeout(() => queue.push('Hello'), 1000);
|
|
43
|
+
setTimeout(() => queue.push('World'), 2000);
|
|
44
|
+
setTimeout(() => queue.push('From AsyncQueue!'), 3000);
|
|
45
|
+
setTimeout(() => queue.close(), 4000);
|
|
36
46
|
}
|
|
37
47
|
|
|
38
48
|
simulateIncomingMessages();
|
|
39
49
|
|
|
40
50
|
// Process messages asynchronously, one at a time
|
|
41
51
|
async function processMessages() {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
console.log("Received message:", message);
|
|
52
|
+
for await (const message of queue) {
|
|
53
|
+
console.log('Received message:', message);
|
|
45
54
|
// Add additional processing logic here...
|
|
46
55
|
}
|
|
56
|
+
console.log('Queue closed');
|
|
47
57
|
}
|
|
48
58
|
|
|
49
59
|
processMessages();
|
|
50
60
|
```
|
|
51
|
-
In this example, the queue is used to collect string messages that are simulated to arrive at different times.
|
|
61
|
+
In this example, the queue is used to collect string messages that are simulated to arrive at different times.
|
|
62
|
+
The `for await` loop in `processMessages` waits for each message, ensuring they are handled in FIFO order, and ends when the queue is closed.
|
|
63
|
+
|
|
64
|
+
Individual items can also be read with `next()`, optionally with an `AbortSignal` to stop waiting:
|
|
52
65
|
|
|
66
|
+
```ts
|
|
67
|
+
try {
|
|
68
|
+
const message = await queue.next({ signal: AbortSignal.timeout(5000) });
|
|
69
|
+
console.log('Received message:', message);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
// Timed out, or the queue was closed or failed
|
|
72
|
+
}
|
|
73
|
+
```
|
|
53
74
|
|
|
54
75
|
## API
|
|
55
76
|
|
|
77
|
+
```ts
|
|
78
|
+
new AsyncQueue<T>(options?: { maxSize?: number, overflow?: 'throw' | 'drop-oldest' | 'drop-newest' })
|
|
79
|
+
```
|
|
80
|
+
Creates a queue.
|
|
81
|
+
Throws a `RangeError` if `maxSize` is neither a positive integer nor `Infinity`, or if `overflow` is not one of the policies below.
|
|
82
|
+
|
|
83
|
+
- Parameters
|
|
84
|
+
- `options.maxSize` - Maximum number of buffered items: a positive integer, or `Infinity` for no limit. Default: `Infinity`.
|
|
85
|
+
- `options.overflow` - What `push()` does when the buffer is full. Default: `'throw'`.
|
|
86
|
+
- `'throw'`: throw a `QueueFullError`, the item is not added.
|
|
87
|
+
- `'drop-oldest'`: discard the oldest buffered item to make room for the new one.
|
|
88
|
+
- `'drop-newest'`: discard the item being pushed.
|
|
89
|
+
|
|
90
|
+
By default the buffer is unlimited: if items are pushed faster than they are consumed, memory use keeps growing.
|
|
91
|
+
Items handed directly to a waiting consumer are not buffered, and do not count towards `maxSize`.
|
|
92
|
+
|
|
56
93
|
```ts
|
|
57
94
|
push(item: T): void
|
|
58
95
|
```
|
|
@@ -61,26 +98,101 @@ Adds an item to the queue.
|
|
|
61
98
|
- Parameters
|
|
62
99
|
- `item: T` - The item to add.
|
|
63
100
|
|
|
64
|
-
If there are pending consumers waiting for an item (via `next(`)
|
|
65
|
-
the
|
|
101
|
+
If there are pending consumers waiting for an item (via `next()` or `for await`),
|
|
102
|
+
the first one receives the new item immediately.
|
|
103
|
+
Throws a `QueueClosedError` if the queue has been closed or failed.
|
|
104
|
+
If the buffer is full, the `overflow` policy of the queue applies.
|
|
66
105
|
|
|
67
106
|
```ts
|
|
68
|
-
next(): Promise<T>
|
|
107
|
+
next(options?: { signal?: AbortSignal }): Promise<T>
|
|
69
108
|
```
|
|
70
109
|
Returns a promise that resolves with the next item in the queue.
|
|
110
|
+
|
|
111
|
+
- Parameters
|
|
112
|
+
- `options.signal` - Optional `AbortSignal` to stop waiting.
|
|
71
113
|
- Returns:
|
|
72
114
|
- `Promise<T>` - A promise that resolves to the next item.
|
|
73
115
|
|
|
74
116
|
If the queue already contains an item, the promise resolves immediately;
|
|
75
117
|
otherwise, it waits until an item is pushed.
|
|
118
|
+
The promise rejects:
|
|
119
|
+
|
|
120
|
+
- with the abort reason, when `options.signal` is aborted; no item is consumed in that case.
|
|
121
|
+
- with a `QueueClosedError`, when the queue is closed and all buffered items have been consumed.
|
|
122
|
+
- with the error passed to `fail()`, when the queue has failed.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
close(): void
|
|
126
|
+
```
|
|
127
|
+
Ends the queue gracefully.
|
|
128
|
+
Items which are already buffered can still be consumed;
|
|
129
|
+
after that, `for await` loops end and `next()` rejects with a `QueueClosedError`.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
fail(error: unknown): void
|
|
133
|
+
```
|
|
134
|
+
Ends the queue with an error.
|
|
135
|
+
Buffered items are discarded, and pending and future consumers reject with the given error.
|
|
136
|
+
|
|
137
|
+
Calling `close()` or `fail()` on a queue which has already ended has no effect.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<T>
|
|
141
|
+
```
|
|
142
|
+
Allows the queue to be consumed with `for await (const item of queue)`.
|
|
143
|
+
The loop ends when the queue is closed and drained, and throws when the queue has failed.
|
|
144
|
+
Leaving the loop early (`break` or `return`) does not close the queue, the remaining items can still be consumed.
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
tryNext(): T | undefined
|
|
148
|
+
```
|
|
149
|
+
Takes the next item without waiting.
|
|
150
|
+
Returns `undefined` if no item is buffered, also when the queue has been closed or failed.
|
|
151
|
+
Check `size` first if `undefined` is a valid item in your queue.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
clear(): void
|
|
155
|
+
```
|
|
156
|
+
Discards all buffered items.
|
|
157
|
+
Waiting consumers keep waiting, and the queue stays open.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
readonly size: number
|
|
161
|
+
```
|
|
162
|
+
The number of buffered items, which have been pushed but not yet consumed.
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
readonly pending: number
|
|
166
|
+
```
|
|
167
|
+
The number of consumers waiting for an item.
|
|
168
|
+
At most one of `size` and `pending` is non-zero.
|
|
169
|
+
|
|
170
|
+
Each item is delivered to exactly one consumer.
|
|
76
171
|
|
|
77
172
|
## When to Use This Queue
|
|
78
173
|
|
|
79
|
-
This queue is particularly useful when you need to process asynchronous events in a controlled, sequential manner.
|
|
174
|
+
This queue is particularly useful when you need to process asynchronous events in a controlled, sequential manner.
|
|
175
|
+
Instead of handling events directly as they arrive, you can push them into the queue and then process them one by one.
|
|
176
|
+
This approach is beneficial in scenarios such as:
|
|
177
|
+
|
|
178
|
+
- Handling user input events.
|
|
179
|
+
- Processing network messages.
|
|
180
|
+
- Handing items from a callback-based producer to an `async` consumer.
|
|
181
|
+
|
|
182
|
+
## Alternatives
|
|
183
|
+
|
|
184
|
+
This is a small utility, and it is not the right tool for every job.
|
|
185
|
+
Consider one of these instead:
|
|
186
|
+
|
|
187
|
+
- **Iterating over the events of a Node.js `EventEmitter`:** [`events.on()`](https://nodejs.org/api/events.html#eventsonemitter-eventname-options), which is built into Node.js.
|
|
188
|
+
- **Backpressure, where a slow consumer slows down the producer:** [`ReadableStream`](https://developer.mozilla.org/docs/Web/API/ReadableStream), or [`@repeaterjs/repeater`](https://www.npmjs.com/package/@repeaterjs/repeater).
|
|
189
|
+
- **Setting up and tearing down the event source together with the iteration:** [`@repeaterjs/repeater`](https://www.npmjs.com/package/@repeaterjs/repeater).
|
|
190
|
+
- **A pushable source for the `it-*` family of iterable utilities:** [`it-pushable`](https://www.npmjs.com/package/it-pushable).
|
|
191
|
+
- **Running jobs with a concurrency limit or priorities:** a job queue, such as [`p-queue`](https://www.npmjs.com/package/p-queue).
|
|
80
192
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
193
|
+
`push()` is synchronous and never waits for the consumer.
|
|
194
|
+
A full buffer is handled by the `overflow` policy, which rejects or drops items; it does not slow down the producer.
|
|
195
|
+
This queue does not run tasks either: it only hands items from producers to consumers.
|
|
84
196
|
|
|
85
197
|
## License
|
|
86
198
|
|
package/lib/queue.d.ts
CHANGED
|
@@ -1,6 +1,110 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Options for {@link AsyncQueue.next}.
|
|
3
|
+
*/
|
|
4
|
+
export interface NextOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Abort waiting for the next item.
|
|
7
|
+
* The returned promise rejects with the abort reason, and no item is consumed.
|
|
8
|
+
*/
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Thrown by {@link AsyncQueue.next} when the queue is closed and all buffered items have been consumed,
|
|
13
|
+
* and by {@link AsyncQueue.push} when an item is pushed after the queue has ended.
|
|
14
|
+
*/
|
|
15
|
+
export declare class QueueClosedError extends Error {
|
|
16
|
+
constructor(message?: string);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Thrown by {@link AsyncQueue.push} when the buffer is full and the overflow policy is `'throw'`.
|
|
20
|
+
*/
|
|
21
|
+
export declare class QueueFullError extends Error {
|
|
22
|
+
constructor(message?: string);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* What {@link AsyncQueue.push} does when the buffer holds {@link AsyncQueueOptions.maxSize} items:
|
|
26
|
+
* - `'throw'`: throw a {@link QueueFullError}, the item is not added.
|
|
27
|
+
* - `'drop-oldest'`: discard the oldest buffered item to make room for the new one.
|
|
28
|
+
* - `'drop-newest'`: discard the item being pushed.
|
|
29
|
+
*/
|
|
30
|
+
export type OverflowPolicy = 'throw' | 'drop-oldest' | 'drop-newest';
|
|
31
|
+
/**
|
|
32
|
+
* Options for the {@link AsyncQueue} constructor.
|
|
33
|
+
*/
|
|
34
|
+
export interface AsyncQueueOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Maximum number of buffered items: a positive integer, or `Infinity` for no limit.
|
|
37
|
+
* Items handed directly to a waiting consumer are not buffered and do not count.
|
|
38
|
+
* Default: `Infinity`, unlimited.
|
|
39
|
+
*/
|
|
40
|
+
maxSize?: number;
|
|
41
|
+
/**
|
|
42
|
+
* What `push()` does when the buffer is full.
|
|
43
|
+
* Default: `'throw'`.
|
|
44
|
+
*/
|
|
45
|
+
overflow?: OverflowPolicy;
|
|
46
|
+
}
|
|
47
|
+
export declare class AsyncQueue<T> implements AsyncIterable<T> {
|
|
2
48
|
private queue;
|
|
3
49
|
private waiters;
|
|
50
|
+
private state;
|
|
51
|
+
private error;
|
|
52
|
+
private readonly maxSize;
|
|
53
|
+
private readonly overflow;
|
|
54
|
+
/**
|
|
55
|
+
* @throws RangeError if `options.maxSize` is neither a positive integer nor `Infinity`, or `options.overflow` is not a known policy.
|
|
56
|
+
*/
|
|
57
|
+
constructor(options?: AsyncQueueOptions);
|
|
58
|
+
/**
|
|
59
|
+
* Number of buffered items, which have been pushed but not yet consumed.
|
|
60
|
+
*/
|
|
61
|
+
get size(): number;
|
|
62
|
+
/**
|
|
63
|
+
* Number of consumers waiting for an item.
|
|
64
|
+
*/
|
|
65
|
+
get pending(): number;
|
|
66
|
+
/**
|
|
67
|
+
* Add an item to the queue.
|
|
68
|
+
* If a consumer is waiting, it receives the item immediately.
|
|
69
|
+
* If the buffer is full, the overflow policy of the queue applies.
|
|
70
|
+
* @throws QueueClosedError if the queue has been closed or failed.
|
|
71
|
+
* @throws QueueFullError if the buffer is full and the overflow policy is `'throw'`.
|
|
72
|
+
*/
|
|
4
73
|
push(item: T): void;
|
|
5
|
-
|
|
74
|
+
/**
|
|
75
|
+
* Returns a promise that resolves with the next item.
|
|
76
|
+
* Rejects with {@link QueueClosedError} when the queue is closed and empty,
|
|
77
|
+
* with the error passed to {@link fail}, or with the abort reason of `options.signal`.
|
|
78
|
+
*/
|
|
79
|
+
next(options?: NextOptions): Promise<T>;
|
|
80
|
+
/**
|
|
81
|
+
* Take the next item without waiting.
|
|
82
|
+
* Returns `undefined` if no item is buffered; check {@link size} first if `undefined` is a valid item.
|
|
83
|
+
* Does not throw when the queue has been closed or failed.
|
|
84
|
+
*/
|
|
85
|
+
tryNext(): T | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Discard all buffered items.
|
|
88
|
+
* Waiting consumers keep waiting, and the queue stays open.
|
|
89
|
+
*/
|
|
90
|
+
clear(): void;
|
|
91
|
+
/**
|
|
92
|
+
* End the queue gracefully.
|
|
93
|
+
* Items already buffered can still be consumed; after that, consumers are told the queue is done.
|
|
94
|
+
* Has no effect if the queue has already been closed or failed.
|
|
95
|
+
*/
|
|
96
|
+
close(): void;
|
|
97
|
+
/**
|
|
98
|
+
* End the queue with an error.
|
|
99
|
+
* Buffered items are discarded, and pending and future consumers reject with `error`.
|
|
100
|
+
* Has no effect if the queue has already been closed or failed.
|
|
101
|
+
*/
|
|
102
|
+
fail(error: unknown): void;
|
|
103
|
+
/**
|
|
104
|
+
* Iterate over the items with `for await`.
|
|
105
|
+
* The iteration ends when the queue is closed and drained, and throws when the queue has failed.
|
|
106
|
+
* Leaving the loop early does not close the queue.
|
|
107
|
+
*/
|
|
108
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
|
|
109
|
+
private pull;
|
|
6
110
|
}
|
package/lib/queue.js
CHANGED
|
@@ -1,29 +1,239 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by {@link AsyncQueue.next} when the queue is closed and all buffered items have been consumed,
|
|
3
|
+
* and by {@link AsyncQueue.push} when an item is pushed after the queue has ended.
|
|
4
|
+
*/
|
|
5
|
+
export class QueueClosedError extends Error {
|
|
6
|
+
constructor(message = 'Queue is closed') {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'QueueClosedError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Thrown by {@link AsyncQueue.push} when the buffer is full and the overflow policy is `'throw'`.
|
|
13
|
+
*/
|
|
14
|
+
export class QueueFullError extends Error {
|
|
15
|
+
constructor(message = 'Queue is full') {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'QueueFullError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const overflowPolicies = ['throw', 'drop-oldest', 'drop-newest'];
|
|
21
|
+
/**
|
|
22
|
+
* First-in-first-out list with constant time removal from the front.
|
|
23
|
+
* `Array.prototype.shift()` moves all remaining elements, which makes draining a large backlog quadratic.
|
|
24
|
+
*/
|
|
25
|
+
class Fifo {
|
|
2
26
|
constructor() {
|
|
3
|
-
this.
|
|
4
|
-
this.
|
|
27
|
+
this.items = [];
|
|
28
|
+
this.head = 0; // Index of the first item, the slots before it have been consumed
|
|
29
|
+
}
|
|
30
|
+
get length() {
|
|
31
|
+
return this.items.length - this.head;
|
|
5
32
|
}
|
|
6
|
-
// Called when a new message arrives (e.g., from an event)
|
|
7
33
|
push(item) {
|
|
8
|
-
|
|
34
|
+
this.items.push(item);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Remove and return the first item.
|
|
38
|
+
* Must not be called on an empty list.
|
|
39
|
+
*/
|
|
40
|
+
shift() {
|
|
41
|
+
const item = this.items[this.head];
|
|
42
|
+
this.items[this.head++] = undefined; // Release the reference
|
|
43
|
+
if (this.head === this.items.length) {
|
|
44
|
+
this.clear();
|
|
45
|
+
}
|
|
46
|
+
else if (this.head >= Fifo.compactThreshold && this.head * 2 >= this.items.length) {
|
|
47
|
+
// At least half of the array is consumed: drop that part, which keeps the cost amortized constant
|
|
48
|
+
this.items = this.items.slice(this.head);
|
|
49
|
+
this.head = 0;
|
|
50
|
+
}
|
|
51
|
+
return item;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Remove the given item, wherever it is in the list.
|
|
55
|
+
*/
|
|
56
|
+
remove(item) {
|
|
57
|
+
const index = this.items.indexOf(item, this.head);
|
|
58
|
+
if (index !== -1) {
|
|
59
|
+
this.items.splice(index, 1);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Remove and return all items.
|
|
64
|
+
*/
|
|
65
|
+
drain() {
|
|
66
|
+
const items = this.items.slice(this.head);
|
|
67
|
+
this.clear();
|
|
68
|
+
return items;
|
|
69
|
+
}
|
|
70
|
+
clear() {
|
|
71
|
+
this.items = [];
|
|
72
|
+
this.head = 0;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
Fifo.compactThreshold = 1024;
|
|
76
|
+
export class AsyncQueue {
|
|
77
|
+
/**
|
|
78
|
+
* @throws RangeError if `options.maxSize` is neither a positive integer nor `Infinity`, or `options.overflow` is not a known policy.
|
|
79
|
+
*/
|
|
80
|
+
constructor(options = {}) {
|
|
81
|
+
this.queue = new Fifo(); // Holds items that have arrived
|
|
82
|
+
this.waiters = new Fifo(); // Holds pending consumers
|
|
83
|
+
this.state = 'open';
|
|
84
|
+
const { maxSize = Number.POSITIVE_INFINITY, overflow = 'throw' } = options;
|
|
85
|
+
if (maxSize !== Number.POSITIVE_INFINITY && !(Number.isInteger(maxSize) && maxSize >= 1)) {
|
|
86
|
+
throw new RangeError(`maxSize must be a positive integer or Infinity, got ${maxSize}`);
|
|
87
|
+
}
|
|
88
|
+
if (!overflowPolicies.includes(overflow)) {
|
|
89
|
+
throw new RangeError(`Unknown overflow policy: ${overflow}`);
|
|
90
|
+
}
|
|
91
|
+
this.maxSize = maxSize;
|
|
92
|
+
this.overflow = overflow;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Number of buffered items, which have been pushed but not yet consumed.
|
|
96
|
+
*/
|
|
97
|
+
get size() {
|
|
98
|
+
return this.queue.length;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Number of consumers waiting for an item.
|
|
102
|
+
*/
|
|
103
|
+
get pending() {
|
|
104
|
+
return this.waiters.length;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Add an item to the queue.
|
|
108
|
+
* If a consumer is waiting, it receives the item immediately.
|
|
109
|
+
* If the buffer is full, the overflow policy of the queue applies.
|
|
110
|
+
* @throws QueueClosedError if the queue has been closed or failed.
|
|
111
|
+
* @throws QueueFullError if the buffer is full and the overflow policy is `'throw'`.
|
|
112
|
+
*/
|
|
113
|
+
push(item) {
|
|
114
|
+
if (this.state !== 'open') {
|
|
115
|
+
throw new QueueClosedError('Cannot push: queue is closed');
|
|
116
|
+
}
|
|
9
117
|
if (this.waiters.length > 0) {
|
|
10
|
-
|
|
11
|
-
|
|
118
|
+
this.waiters.shift().resolve({ done: false, value: item });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (this.queue.length >= this.maxSize) {
|
|
122
|
+
switch (this.overflow) {
|
|
123
|
+
case 'drop-newest':
|
|
124
|
+
return;
|
|
125
|
+
case 'drop-oldest':
|
|
126
|
+
this.queue.shift();
|
|
127
|
+
break;
|
|
128
|
+
default:
|
|
129
|
+
throw new QueueFullError(`Cannot push: queue is full (${this.maxSize} items)`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
this.queue.push(item);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Returns a promise that resolves with the next item.
|
|
136
|
+
* Rejects with {@link QueueClosedError} when the queue is closed and empty,
|
|
137
|
+
* with the error passed to {@link fail}, or with the abort reason of `options.signal`.
|
|
138
|
+
*/
|
|
139
|
+
async next(options) {
|
|
140
|
+
const result = await this.pull(options?.signal);
|
|
141
|
+
if (result.done) {
|
|
142
|
+
throw new QueueClosedError();
|
|
143
|
+
}
|
|
144
|
+
return result.value;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Take the next item without waiting.
|
|
148
|
+
* Returns `undefined` if no item is buffered; check {@link size} first if `undefined` is a valid item.
|
|
149
|
+
* Does not throw when the queue has been closed or failed.
|
|
150
|
+
*/
|
|
151
|
+
tryNext() {
|
|
152
|
+
return this.queue.length > 0 ? this.queue.shift() : undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Discard all buffered items.
|
|
156
|
+
* Waiting consumers keep waiting, and the queue stays open.
|
|
157
|
+
*/
|
|
158
|
+
clear() {
|
|
159
|
+
this.queue.clear();
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* End the queue gracefully.
|
|
163
|
+
* Items already buffered can still be consumed; after that, consumers are told the queue is done.
|
|
164
|
+
* Has no effect if the queue has already been closed or failed.
|
|
165
|
+
*/
|
|
166
|
+
close() {
|
|
167
|
+
if (this.state !== 'open') {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
this.state = 'closed';
|
|
171
|
+
// Consumers only wait while the buffer is empty, so there is nothing left for them.
|
|
172
|
+
for (const waiter of this.waiters.drain()) {
|
|
173
|
+
waiter.resolve({ done: true, value: undefined });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* End the queue with an error.
|
|
178
|
+
* Buffered items are discarded, and pending and future consumers reject with `error`.
|
|
179
|
+
* Has no effect if the queue has already been closed or failed.
|
|
180
|
+
*/
|
|
181
|
+
fail(error) {
|
|
182
|
+
if (this.state !== 'open') {
|
|
183
|
+
return;
|
|
12
184
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
185
|
+
this.state = 'failed';
|
|
186
|
+
this.error = error;
|
|
187
|
+
this.queue.clear();
|
|
188
|
+
for (const waiter of this.waiters.drain()) {
|
|
189
|
+
waiter.reject(error);
|
|
16
190
|
}
|
|
17
191
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
192
|
+
/**
|
|
193
|
+
* Iterate over the items with `for await`.
|
|
194
|
+
* The iteration ends when the queue is closed and drained, and throws when the queue has failed.
|
|
195
|
+
* Leaving the loop early does not close the queue.
|
|
196
|
+
*/
|
|
197
|
+
[Symbol.asyncIterator]() {
|
|
198
|
+
return {
|
|
199
|
+
next: () => this.pull(),
|
|
200
|
+
return: async () => ({ done: true, value: undefined }),
|
|
201
|
+
[Symbol.asyncIterator]() {
|
|
202
|
+
return this;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
pull(signal) {
|
|
207
|
+
if (signal?.aborted) {
|
|
208
|
+
return Promise.reject(signal.reason);
|
|
209
|
+
}
|
|
21
210
|
if (this.queue.length > 0) {
|
|
22
|
-
return Promise.resolve(this.queue.shift());
|
|
211
|
+
return Promise.resolve({ done: false, value: this.queue.shift() });
|
|
212
|
+
}
|
|
213
|
+
if (this.state === 'failed') {
|
|
214
|
+
return Promise.reject(this.error);
|
|
215
|
+
}
|
|
216
|
+
if (this.state === 'closed') {
|
|
217
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
23
218
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
const waiter = {
|
|
221
|
+
resolve: result => {
|
|
222
|
+
signal?.removeEventListener('abort', onAbort);
|
|
223
|
+
resolve(result);
|
|
224
|
+
},
|
|
225
|
+
reject: reason => {
|
|
226
|
+
signal?.removeEventListener('abort', onAbort);
|
|
227
|
+
reject(reason);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const onAbort = () => {
|
|
231
|
+
// Withdraw this consumer, so the next pushed item is not delivered to nobody.
|
|
232
|
+
this.waiters.remove(waiter);
|
|
233
|
+
reject(signal?.reason);
|
|
234
|
+
};
|
|
235
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
236
|
+
this.waiters.push(waiter);
|
|
27
237
|
});
|
|
28
238
|
}
|
|
29
239
|
}
|
package/package.json
CHANGED
|
@@ -1,49 +1,67 @@
|
|
|
1
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
|
-
|
|
2
|
+
"name": "@borewit/async-queue",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "async iterable queue",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"types": "./lib/queue.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./lib/queue.d.ts",
|
|
11
|
+
"default": "./lib/queue.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"clean": "del-cli 'lib/**/*.js' 'lib/**/*.d.ts'",
|
|
16
|
+
"compile": "tsc -p lib && tsc -p test",
|
|
17
|
+
"build": "yarn run clean && yarn run compile",
|
|
18
|
+
"prepublishOnly": "yarn run build",
|
|
19
|
+
"lint": "biome check",
|
|
20
|
+
"fix": "biome check --write",
|
|
21
|
+
"lint:package": "publint --strict && attw --pack . --profile esm-only",
|
|
22
|
+
"test:smoke": "node test/smoke.mjs",
|
|
23
|
+
"test": "vitest run",
|
|
24
|
+
"test:build": "vitest run --mode build",
|
|
25
|
+
"test:coverage": "vitest run --coverage"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"lib/**/*.js",
|
|
29
|
+
"lib/**/*.d.ts"
|
|
30
|
+
],
|
|
31
|
+
"author": {
|
|
32
|
+
"name": "Borewit",
|
|
33
|
+
"url": "https://github.com/Borewit"
|
|
34
|
+
},
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/Borewit/async-queue.git"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=18"
|
|
42
|
+
},
|
|
43
|
+
"packageManager": "yarn@4.6.0",
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
46
|
+
"@biomejs/biome": "2.6.10",
|
|
47
|
+
"@vitest/coverage-v8": "^5.1.2",
|
|
48
|
+
"del-cli": "^8.0.1",
|
|
49
|
+
"publint": "^0.3.25",
|
|
50
|
+
"typescript": "^5.7.3",
|
|
51
|
+
"vite": "^8.4.1",
|
|
52
|
+
"vitest": "^5.1.2"
|
|
53
|
+
},
|
|
54
|
+
"keywords": [
|
|
55
|
+
"async",
|
|
56
|
+
"queue",
|
|
57
|
+
"await",
|
|
58
|
+
"iterable",
|
|
59
|
+
"FIFO",
|
|
60
|
+
"event-driven",
|
|
61
|
+
"asynchronous",
|
|
62
|
+
"TypeScript",
|
|
63
|
+
"event-queue",
|
|
64
|
+
"async-iterator",
|
|
65
|
+
"abort-signal"
|
|
66
|
+
]
|
|
49
67
|
}
|