@cldmv/holdmytask 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 +210 -0
- package/README.md +777 -0
- package/dist/hold-my-task.mjs +584 -0
- package/dist/utils.mjs +120 -0
- package/index.cjs +29 -0
- package/index.mjs +23 -0
- package/package.json +117 -0
- package/types/dist/hold-my-task.d.mts +189 -0
- package/types/dist/hold-my-task.d.mts.map +1 -0
- package/types/dist/utils.d.mts +72 -0
- package/types/dist/utils.d.mts.map +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
# @cldmv/holdmytask
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@cldmv/holdmytask)
|
|
4
|
+
[](https://www.npmjs.com/package/@cldmv/holdmytask)
|
|
5
|
+
[](https://github.com/CLDMV/holdmytask/releases)
|
|
6
|
+
[](https://github.com/CLDMV/holdmytask/commits)
|
|
7
|
+
[](https://www.npmjs.com/package/@cldmv/holdmytask)
|
|
8
|
+
|
|
9
|
+
[](https://github.com/CLDMV/holdmytask/graphs/contributors) [](https://github.com/sponsors/shinrai)
|
|
10
|
+
|
|
11
|
+
A tiny, dependency-free task queue for Node.js that executes tasks with priority ordering, concurrency control, and completion delays. Perfect for managing asynchronous workflows with sophisticated timing requirements.
|
|
12
|
+
|
|
13
|
+
## ✨ Features
|
|
14
|
+
|
|
15
|
+
- **Priority-based execution** - Higher priority tasks run first
|
|
16
|
+
- **Concurrency control** - Limit simultaneous task execution
|
|
17
|
+
- **Completion delays** - Configurable delays between task completions
|
|
18
|
+
- **Delay bypass** - Urgent tasks can skip active delay periods
|
|
19
|
+
- **Timeout support** - Automatic task cancellation on timeout
|
|
20
|
+
- **Dual API support** - Both callback and Promise-based APIs
|
|
21
|
+
- **AbortController integration** - Cooperative cancellation support
|
|
22
|
+
- **Dual ESM/CJS exports** - Works with both module systems
|
|
23
|
+
- **TypeScript ready** - Full type definitions included
|
|
24
|
+
- **Zero dependencies** - Lightweight and fast
|
|
25
|
+
|
|
26
|
+
## 📦 Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install @cldmv/holdmytask
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## � Import Options
|
|
33
|
+
|
|
34
|
+
The library provides flexible import options for different use cases:
|
|
35
|
+
|
|
36
|
+
### Production (Default)
|
|
37
|
+
|
|
38
|
+
```javascript
|
|
39
|
+
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
40
|
+
// Uses optimized distribution files
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Development Source Access
|
|
44
|
+
|
|
45
|
+
```javascript
|
|
46
|
+
import { HoldMyTask } from "@cldmv/holdmytask/main";
|
|
47
|
+
// Conditional: uses source files in development, dist files in production
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Direct Source Import (Development Only)
|
|
51
|
+
|
|
52
|
+
```javascript
|
|
53
|
+
import { HoldMyTask } from "@cldmv/holdmytask/src";
|
|
54
|
+
// Always uses source files - bypasses devcheck
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Note:** The main import automatically runs environment checks in development mode to ensure proper configuration.
|
|
58
|
+
|
|
59
|
+
## �🚀 Quick Start
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
63
|
+
|
|
64
|
+
const queue = new HoldMyTask({
|
|
65
|
+
concurrency: 2,
|
|
66
|
+
delays: { 1: 100, 2: 200 } // 100ms delay after priority 1 tasks, 200ms after priority 2
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// Enqueue a task
|
|
70
|
+
queue.enqueue(
|
|
71
|
+
async (signal) => {
|
|
72
|
+
// Your task logic here
|
|
73
|
+
return "task result";
|
|
74
|
+
},
|
|
75
|
+
(error, result) => {
|
|
76
|
+
if (error) {
|
|
77
|
+
console.error("Task failed:", error);
|
|
78
|
+
} else {
|
|
79
|
+
console.log("Task completed:", result);
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
{ priority: 1, timeout: 5000 }
|
|
83
|
+
);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## 🔄 Promise API
|
|
87
|
+
|
|
88
|
+
For modern async/await codebases, you can omit the callback to get a Promise:
|
|
89
|
+
|
|
90
|
+
```javascript
|
|
91
|
+
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
92
|
+
|
|
93
|
+
const queue = new HoldMyTask({ concurrency: 2 });
|
|
94
|
+
|
|
95
|
+
// Promise-based task
|
|
96
|
+
try {
|
|
97
|
+
const result = await queue.enqueue(
|
|
98
|
+
async (signal) => {
|
|
99
|
+
// Task logic with abort support
|
|
100
|
+
if (signal.aborted) throw new Error("Aborted");
|
|
101
|
+
return "task result";
|
|
102
|
+
},
|
|
103
|
+
{ priority: 1, timeout: 5000 }
|
|
104
|
+
);
|
|
105
|
+
console.log("Task completed:", result);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error("Task failed:", error.message);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The returned Promise is also a task handle
|
|
111
|
+
const promise = queue.enqueue(() => "simple task");
|
|
112
|
+
console.log("Task ID:", promise.id);
|
|
113
|
+
promise.cancel(); // Cancel the task
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Mixing APIs
|
|
117
|
+
|
|
118
|
+
You can mix callback and promise styles in the same queue:
|
|
119
|
+
|
|
120
|
+
```javascript
|
|
121
|
+
// Callback-based
|
|
122
|
+
queue.enqueue(task1, callback, options);
|
|
123
|
+
|
|
124
|
+
// Promise-based
|
|
125
|
+
const result = await queue.enqueue(task2, options);
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## 📚 API Reference
|
|
129
|
+
|
|
130
|
+
### Constructor
|
|
131
|
+
|
|
132
|
+
```javascript
|
|
133
|
+
const queue = new HoldMyTask(options?)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
**Options:**
|
|
137
|
+
|
|
138
|
+
- `concurrency` (number, default: 1) - Maximum concurrent tasks
|
|
139
|
+
- `tick` (number, default: 25) - Scheduler tick interval in milliseconds
|
|
140
|
+
- `autoStart` (boolean, default: true) - Whether to start processing immediately
|
|
141
|
+
- `defaultPriority` (number, default: 0) - Default task priority
|
|
142
|
+
- `maxQueue` (number, default: Infinity) - Maximum queued tasks
|
|
143
|
+
- `delays` (object, default: {}) - Priority-to-delay mapping for completion delays
|
|
144
|
+
- `onError` (function) - Global error handler
|
|
145
|
+
- `now` (function) - Injectable clock for testing
|
|
146
|
+
|
|
147
|
+
### Methods
|
|
148
|
+
|
|
149
|
+
#### `enqueue(task, callback?, options?)`
|
|
150
|
+
|
|
151
|
+
Adds a task to the queue.
|
|
152
|
+
|
|
153
|
+
**Parameters:**
|
|
154
|
+
|
|
155
|
+
- `task` (function) - The task function that receives an `AbortSignal` and returns a value or Promise
|
|
156
|
+
- `callback` (function, optional) - Called with `(error, result)` when task completes. If omitted, returns a Promise.
|
|
157
|
+
- `options` (object) - Task options
|
|
158
|
+
|
|
159
|
+
**Task Options:**
|
|
160
|
+
|
|
161
|
+
- `priority` (number) - Task priority (higher = more important)
|
|
162
|
+
- `delay` (number) - Override completion delay for this task (use -1 to bypass delays)
|
|
163
|
+
- `bypassDelay` (boolean) - If true, skip any active delay period and start immediately
|
|
164
|
+
- `timeout` (number) - Timeout in milliseconds
|
|
165
|
+
- `signal` (AbortSignal) - External abort signal
|
|
166
|
+
- `timestamp` (number) - Absolute execution timestamp
|
|
167
|
+
- `metadata` (any) - Custom metadata
|
|
168
|
+
|
|
169
|
+
**Returns:** TaskHandle object with:
|
|
170
|
+
|
|
171
|
+
- `id` - Unique task identifier
|
|
172
|
+
- `cancel(reason?)` - Cancel the task
|
|
173
|
+
- `status()` - Get current status
|
|
174
|
+
- `startedAt` - When task started
|
|
175
|
+
- `finishedAt` - When task finished
|
|
176
|
+
- `result` - Task result (if completed)
|
|
177
|
+
- `error` - Task error (if failed)
|
|
178
|
+
|
|
179
|
+
When `callback` is omitted, returns a Promise that resolves with the task result or rejects with an error.
|
|
180
|
+
|
|
181
|
+
#### Control Methods
|
|
182
|
+
|
|
183
|
+
- `pause()` - Pause task execution
|
|
184
|
+
- `resume()` - Resume task execution
|
|
185
|
+
- `clear()` - Cancel all pending tasks
|
|
186
|
+
- `size()` - Get total queued tasks
|
|
187
|
+
- `inflight()` - Get currently running tasks
|
|
188
|
+
- `destroy()` - Destroy the queue and cancel all tasks
|
|
189
|
+
|
|
190
|
+
### Events
|
|
191
|
+
|
|
192
|
+
```javascript
|
|
193
|
+
queue.on("start", (task) => {
|
|
194
|
+
/* task started */
|
|
195
|
+
});
|
|
196
|
+
queue.on("success", (task) => {
|
|
197
|
+
/* task completed successfully */
|
|
198
|
+
});
|
|
199
|
+
queue.on("error", (task) => {
|
|
200
|
+
/* task failed */
|
|
201
|
+
});
|
|
202
|
+
queue.on("cancel", (task, reason) => {
|
|
203
|
+
/* task cancelled */
|
|
204
|
+
});
|
|
205
|
+
queue.on("drain", () => {
|
|
206
|
+
/* all tasks completed */
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## ⚙️ Concurrency & Delays Interaction
|
|
211
|
+
|
|
212
|
+
Understanding how concurrency and delays work together is crucial for optimal queue behavior:
|
|
213
|
+
|
|
214
|
+
### Concurrency Rules
|
|
215
|
+
|
|
216
|
+
```javascript
|
|
217
|
+
const queue = new HoldMyTask({
|
|
218
|
+
concurrency: 3, // Up to 3 tasks can run simultaneously
|
|
219
|
+
delays: { 1: 500, 2: 1000 }
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
**Key Behaviors:**
|
|
224
|
+
|
|
225
|
+
1. **Delays are Global**: When any task completes, its priority delay affects ALL subsequent task starts
|
|
226
|
+
2. **Concurrency Slots**: Multiple tasks can run simultaneously until delay blocks new starts
|
|
227
|
+
3. **Independent Completion**: Running tasks complete independently; delays only affect new starts
|
|
228
|
+
|
|
229
|
+
### Timing Examples
|
|
230
|
+
|
|
231
|
+
```javascript
|
|
232
|
+
// Timeline with concurrency: 2, delays: { 1: 1000 }
|
|
233
|
+
|
|
234
|
+
// 10:00:00 - Start: TaskA (pri 1), TaskB (pri 1) - both running
|
|
235
|
+
// 10:00:02 - TaskA completes → 1000ms delay starts, TaskB still running
|
|
236
|
+
// 10:00:03 - TaskC (pri 1) ready but blocked by delay
|
|
237
|
+
// 10:00:04 - TaskB completes → extends delay to 10:00:05 (1000ms from TaskB completion)
|
|
238
|
+
// 10:00:05 - Delay expires, TaskC and TaskD can start (fills 2 slots again)
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
**Best Practices:**
|
|
242
|
+
|
|
243
|
+
- Use **shorter delays** with **higher concurrency** for throughput with gentle rate limiting
|
|
244
|
+
- Use **longer delays** with **lower concurrency** for strict rate limiting and resource protection
|
|
245
|
+
- **Monitor `inflight()`** to understand how many tasks are actively running vs waiting
|
|
246
|
+
|
|
247
|
+
### ⚡ Technical Architecture
|
|
248
|
+
|
|
249
|
+
HoldMyTask uses a sophisticated dual-heap scheduling system for optimal performance:
|
|
250
|
+
|
|
251
|
+
**🔄 Dual-Heap System:**
|
|
252
|
+
|
|
253
|
+
- **Pending Heap**: Time-ordered queue for tasks waiting for their scheduled time (`readyAt`)
|
|
254
|
+
- **Ready Heap**: Priority-ordered queue for tasks ready to execute now
|
|
255
|
+
|
|
256
|
+
**📊 Scheduling Flow:**
|
|
257
|
+
|
|
258
|
+
```
|
|
259
|
+
1. New tasks → Pending Heap (ordered by readyAt timestamp)
|
|
260
|
+
2. Scheduler tick → Move ready tasks: Pending → Ready Heap
|
|
261
|
+
3. Execution → Take highest priority from Ready Heap
|
|
262
|
+
4. Completion → Apply delays, emit events, schedule next tick
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
**⏰ Smart Timing:**
|
|
266
|
+
|
|
267
|
+
- **Adaptive scheduling**: Uses intervals for immediate tasks, timeouts for distant tasks
|
|
268
|
+
- **Precision timing**: Sub-millisecond accuracy with injectable clock for testing
|
|
269
|
+
- **Efficient scanning**: O(log n) heap operations for thousands of tasks
|
|
270
|
+
|
|
271
|
+
**🚀 Performance Characteristics:**
|
|
272
|
+
|
|
273
|
+
- **Enqueue**: O(log n) - Insert into priority heap
|
|
274
|
+
- **Dequeue**: O(log n) - Extract from priority heap
|
|
275
|
+
- **Scheduler tick**: O(k log n) where k = ready tasks
|
|
276
|
+
- **Memory**: O(n) - Minimal overhead per task
|
|
277
|
+
|
|
278
|
+
This architecture enables handling thousands of tasks with precise timing control while maintaining excellent performance.
|
|
279
|
+
|
|
280
|
+
[](https://www.codefactor.io/repository/github/cldmv/holdmytask) [](https://npms.io/search?q=%40cldmv%2Fholdmytask)
|
|
281
|
+
|
|
282
|
+
[](https://www.npmjs.com/package/@cldmv/holdmytask) [](https://github.com/CLDMV/holdmytask)
|
|
283
|
+
|
|
284
|
+
## 🎯 Advanced Features
|
|
285
|
+
|
|
286
|
+
### Priority System
|
|
287
|
+
|
|
288
|
+
Tasks execute in priority order (highest first):
|
|
289
|
+
|
|
290
|
+
**Callback API:**
|
|
291
|
+
|
|
292
|
+
```javascript
|
|
293
|
+
queue.enqueue(task1, callback, { priority: 1 });
|
|
294
|
+
queue.enqueue(task2, callback, { priority: 10 }); // Runs first
|
|
295
|
+
queue.enqueue(task3, callback, { priority: 5 });
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
**Promise API:**
|
|
299
|
+
|
|
300
|
+
```javascript
|
|
301
|
+
await queue.enqueue(task1, { priority: 1 });
|
|
302
|
+
await queue.enqueue(task2, { priority: 10 }); // Runs first
|
|
303
|
+
await queue.enqueue(task3, { priority: 5 });
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### Priority Delays - Advanced Timing Control
|
|
307
|
+
|
|
308
|
+
Priority delays create "cool-down" periods after task completion based on the completed task's priority. This helps prevent resource overwhelming, implement rate limiting, and control timing between operations.
|
|
309
|
+
|
|
310
|
+
#### How It Works
|
|
311
|
+
|
|
312
|
+
- When a task completes, the delay for its priority level is enforced
|
|
313
|
+
- **ALL subsequent tasks** (any priority) must wait for the delay period to expire
|
|
314
|
+
- Delays apply globally - they affect the entire queue, not just tasks of the same priority
|
|
315
|
+
- Tasks can override delays on a per-task basis or bypass delays entirely
|
|
316
|
+
|
|
317
|
+
```javascript
|
|
318
|
+
const queue = new HoldMyTask({
|
|
319
|
+
concurrency: 1,
|
|
320
|
+
delays: {
|
|
321
|
+
1: 1000, // 1 second delay after priority 1 tasks complete
|
|
322
|
+
2: 500, // 500ms delay after priority 2 tasks complete
|
|
323
|
+
3: 0 // No delay after priority 3 tasks (explicit)
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// Task A (priority 1) completes at 10:00:05
|
|
328
|
+
// → Next task can't start until 10:00:06 (1000ms delay)
|
|
329
|
+
|
|
330
|
+
// Task B (priority 2) completes at 10:00:07
|
|
331
|
+
// → Next task can't start until 10:00:07.5 (500ms delay)
|
|
332
|
+
|
|
333
|
+
// Override delay for specific task
|
|
334
|
+
queue.enqueue(task, callback, { priority: 1, delay: 200 }); // Uses 200ms instead of 1000ms
|
|
335
|
+
|
|
336
|
+
// Set zero delay for specific task
|
|
337
|
+
queue.enqueue(task, callback, { priority: 1, delay: 0 }); // No delay after this task
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### Delay Bypass - Emergency Task Injection
|
|
341
|
+
|
|
342
|
+
When urgent tasks need to execute immediately, bypassing active delay periods, use the `bypassDelay` option or `delay: -1` syntax. This is perfect for emergency situations, high-priority interrupts, or critical system tasks.
|
|
343
|
+
|
|
344
|
+
#### Bypass Behavior
|
|
345
|
+
|
|
346
|
+
```javascript
|
|
347
|
+
const queue = new HoldMyTask({
|
|
348
|
+
concurrency: 1,
|
|
349
|
+
delays: { 1: 1000 } // 1 second delay after priority 1 tasks
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// Timeline example:
|
|
353
|
+
// 10:00:00 - Task A (priority 1) completes → 1000ms delay starts
|
|
354
|
+
// 10:00:00.1 - Normal task B enqueued → must wait until 10:01:00
|
|
355
|
+
// 10:00:00.2 - Urgent task C enqueued with bypass → runs immediately
|
|
356
|
+
|
|
357
|
+
queue.enqueue(normalTaskB, callback, { priority: 1 }); // Waits for delay
|
|
358
|
+
|
|
359
|
+
queue.enqueue(urgentTaskC, callback, {
|
|
360
|
+
priority: 1,
|
|
361
|
+
bypassDelay: true // Skips the 1000ms delay, runs now
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// Alternative bypass syntax
|
|
365
|
+
queue.enqueue(emergencyTaskD, callback, {
|
|
366
|
+
priority: 1,
|
|
367
|
+
delay: -1 // Same as bypassDelay: true
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
#### Advanced Bypass Scenarios
|
|
372
|
+
|
|
373
|
+
```javascript
|
|
374
|
+
const queue = new HoldMyTask({
|
|
375
|
+
concurrency: 2,
|
|
376
|
+
delays: { 1: 800, 2: 400 }
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
// Multiple tasks with different bypass behavior
|
|
380
|
+
queue.enqueue(taskA, callback, { priority: 1 }); // Completes, starts 800ms delay
|
|
381
|
+
queue.enqueue(taskB, callback, { priority: 2 }); // Waits for 800ms delay
|
|
382
|
+
queue.enqueue(taskC, callback, { priority: 2, bypassDelay: true }); // Runs immediately
|
|
383
|
+
queue.enqueue(taskD, callback, { priority: 1 }); // Waits for taskC's completion delay
|
|
384
|
+
|
|
385
|
+
// Execution order: taskA → taskC (bypass) → taskB → taskD
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
**Critical Notes:**
|
|
389
|
+
|
|
390
|
+
- ✅ **Bypass affects START timing only** - bypassed tasks still apply their own completion delays
|
|
391
|
+
- ✅ **Maintains priority ordering** - bypass doesn't override natural priority rules
|
|
392
|
+
- ✅ **Scans entire queue** - finds bypass tasks even when normal tasks are blocked
|
|
393
|
+
- ✅ **Concurrency aware** - works correctly with multiple concurrent execution slots
|
|
394
|
+
- ⚠️ **Use sparingly** - frequent bypassing defeats the purpose of delay-based rate limiting
|
|
395
|
+
|
|
396
|
+
### Timeouts
|
|
397
|
+
|
|
398
|
+
Tasks automatically timeout and either call the callback with an error or reject the promise:
|
|
399
|
+
|
|
400
|
+
**Callback API:**
|
|
401
|
+
|
|
402
|
+
```javascript
|
|
403
|
+
queue.enqueue(
|
|
404
|
+
async (signal) => {
|
|
405
|
+
// Long-running task
|
|
406
|
+
await someAsyncOperation();
|
|
407
|
+
return "result";
|
|
408
|
+
},
|
|
409
|
+
(error, result) => {
|
|
410
|
+
if (error?.type === "timeout") {
|
|
411
|
+
console.log("Task timed out!");
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
{ timeout: 5000 } // 5 second timeout
|
|
415
|
+
);
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
**Promise API:**
|
|
419
|
+
|
|
420
|
+
```javascript
|
|
421
|
+
try {
|
|
422
|
+
const result = await queue.enqueue(
|
|
423
|
+
async (signal) => {
|
|
424
|
+
// Long-running task
|
|
425
|
+
await someAsyncOperation();
|
|
426
|
+
return "result";
|
|
427
|
+
},
|
|
428
|
+
{ timeout: 5000 } // 5 second timeout
|
|
429
|
+
);
|
|
430
|
+
console.log("Task completed:", result);
|
|
431
|
+
} catch (error) {
|
|
432
|
+
if (error.message.includes("timed out")) {
|
|
433
|
+
console.log("Task timed out!");
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
## 🛑 AbortController Support
|
|
439
|
+
|
|
440
|
+
The library uses `AbortController` for cooperative task cancellation. This allows tasks to be cancelled gracefully without forcing termination.
|
|
441
|
+
|
|
442
|
+
### How It Works
|
|
443
|
+
|
|
444
|
+
1. **Timeout Cancellation**: When a task exceeds its `timeout`, an `AbortController` is aborted
|
|
445
|
+
2. **External Cancellation**: You can pass your own `AbortSignal` to cancel tasks
|
|
446
|
+
3. **Cooperative**: Tasks must check the signal and respond to cancellation
|
|
447
|
+
|
|
448
|
+
### Implementing AbortController Support in Tasks
|
|
449
|
+
|
|
450
|
+
Your task functions receive an `AbortSignal` as the first parameter. **Always check this signal** to support cancellation:
|
|
451
|
+
|
|
452
|
+
**Callback API:**
|
|
453
|
+
|
|
454
|
+
```javascript
|
|
455
|
+
// ❌ Bad - doesn't support cancellation
|
|
456
|
+
queue.enqueue(async () => {
|
|
457
|
+
await fetch("https://api.example.com/data"); // Can't be cancelled
|
|
458
|
+
return "result";
|
|
459
|
+
}, callback);
|
|
460
|
+
|
|
461
|
+
// ✅ Good - supports cancellation
|
|
462
|
+
queue.enqueue(async (signal) => {
|
|
463
|
+
const response = await fetch("https://api.example.com/data", {
|
|
464
|
+
signal // Pass the signal to fetch
|
|
465
|
+
});
|
|
466
|
+
return response.json();
|
|
467
|
+
}, callback);
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
**Promise API:**
|
|
471
|
+
|
|
472
|
+
```javascript
|
|
473
|
+
// ❌ Bad - doesn't support cancellation
|
|
474
|
+
const result = await queue.enqueue(async () => {
|
|
475
|
+
await fetch("https://api.example.com/data"); // Can't be cancelled
|
|
476
|
+
return "result";
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
// ✅ Good - supports cancellation
|
|
480
|
+
const result = await queue.enqueue(async (signal) => {
|
|
481
|
+
const response = await fetch("https://api.example.com/data", {
|
|
482
|
+
signal // Pass the signal to fetch
|
|
483
|
+
});
|
|
484
|
+
return response.json();
|
|
485
|
+
});
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
### Checking the Signal Manually
|
|
489
|
+
|
|
490
|
+
For custom cancellation logic:
|
|
491
|
+
|
|
492
|
+
**Callback API:**
|
|
493
|
+
|
|
494
|
+
```javascript
|
|
495
|
+
queue.enqueue(
|
|
496
|
+
async (signal) => {
|
|
497
|
+
// Check signal at operation points
|
|
498
|
+
if (signal.aborted) {
|
|
499
|
+
throw new Error("Task was cancelled");
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const result1 = await someOperation();
|
|
503
|
+
|
|
504
|
+
if (signal.aborted) {
|
|
505
|
+
throw new Error("Task was cancelled");
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const result2 = await anotherOperation();
|
|
509
|
+
|
|
510
|
+
return { result1, result2 };
|
|
511
|
+
},
|
|
512
|
+
callback,
|
|
513
|
+
{ timeout: 10000 }
|
|
514
|
+
);
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
**Promise API:**
|
|
518
|
+
|
|
519
|
+
```javascript
|
|
520
|
+
try {
|
|
521
|
+
const result = await queue.enqueue(
|
|
522
|
+
async (signal) => {
|
|
523
|
+
// Check signal at operation points
|
|
524
|
+
if (signal.aborted) {
|
|
525
|
+
throw new Error("Task was cancelled");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const result1 = await someOperation();
|
|
529
|
+
|
|
530
|
+
if (signal.aborted) {
|
|
531
|
+
throw new Error("Task was cancelled");
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const result2 = await anotherOperation();
|
|
535
|
+
|
|
536
|
+
return { result1, result2 };
|
|
537
|
+
},
|
|
538
|
+
{ timeout: 10000 }
|
|
539
|
+
);
|
|
540
|
+
console.log("Task completed:", result);
|
|
541
|
+
} catch (error) {
|
|
542
|
+
console.log("Task failed:", error.message);
|
|
543
|
+
}
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
### External Cancellation
|
|
547
|
+
|
|
548
|
+
Cancel tasks using your own AbortController:
|
|
549
|
+
|
|
550
|
+
**Callback API:**
|
|
551
|
+
|
|
552
|
+
```javascript
|
|
553
|
+
const controller = new AbortController();
|
|
554
|
+
|
|
555
|
+
queue.enqueue(task, callback, {
|
|
556
|
+
signal: controller.signal,
|
|
557
|
+
timeout: 5000
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// Cancel the task externally
|
|
561
|
+
controller.abort();
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
**Promise API:**
|
|
565
|
+
|
|
566
|
+
```javascript
|
|
567
|
+
const controller = new AbortController();
|
|
568
|
+
|
|
569
|
+
const promise = queue.enqueue(task, {
|
|
570
|
+
signal: controller.signal,
|
|
571
|
+
timeout: 5000
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
// Cancel the task externally
|
|
575
|
+
controller.abort();
|
|
576
|
+
|
|
577
|
+
try {
|
|
578
|
+
const result = await promise;
|
|
579
|
+
console.log("Task completed:", result);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
console.log("Task cancelled:", error.message);
|
|
582
|
+
}
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
### Best Practices
|
|
586
|
+
|
|
587
|
+
1. **Always accept the signal parameter** in your task functions
|
|
588
|
+
2. **Pass the signal to async operations** that support it (fetch, timers, etc.)
|
|
589
|
+
3. **Check `signal.aborted`** at logical breakpoints in long-running tasks
|
|
590
|
+
4. **Throw errors** when detecting cancellation
|
|
591
|
+
5. **Use descriptive error messages** for cancelled tasks
|
|
592
|
+
|
|
593
|
+
### Limitations
|
|
594
|
+
|
|
595
|
+
- **Single-threaded**: Cannot forcibly terminate synchronous JavaScript code
|
|
596
|
+
- **Cooperative**: Tasks must actively check and respond to the abort signal
|
|
597
|
+
- **Async operations**: Only cancellable if the underlying operation supports AbortSignal
|
|
598
|
+
|
|
599
|
+
## 📝 Examples
|
|
600
|
+
|
|
601
|
+
### Basic Usage
|
|
602
|
+
|
|
603
|
+
```javascript
|
|
604
|
+
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
605
|
+
|
|
606
|
+
const queue = new HoldMyTask({ concurrency: 3 });
|
|
607
|
+
|
|
608
|
+
function processUser(userId) {
|
|
609
|
+
return queue.enqueue(
|
|
610
|
+
async (signal) => {
|
|
611
|
+
const user = await fetchUser(userId, { signal });
|
|
612
|
+
await sendEmail(user.email, "Welcome!", { signal });
|
|
613
|
+
return user;
|
|
614
|
+
},
|
|
615
|
+
(error, user) => {
|
|
616
|
+
if (error) {
|
|
617
|
+
console.error(`Failed to process user ${userId}:`, error);
|
|
618
|
+
} else {
|
|
619
|
+
console.log(`Processed user: ${user.name}`);
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
{ priority: 1, timeout: 30000 }
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
### Priority Queue with Delays
|
|
628
|
+
|
|
629
|
+
```javascript
|
|
630
|
+
const queue = new HoldMyTask({
|
|
631
|
+
concurrency: 1,
|
|
632
|
+
delays: {
|
|
633
|
+
1: 1000, // 1 second between high-priority tasks
|
|
634
|
+
2: 100, // 100ms between medium-priority tasks
|
|
635
|
+
3: 0 // No delay for low-priority tasks
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
// High priority - runs immediately, 1s delay after
|
|
640
|
+
queue.enqueue(highPriorityTask, callback, { priority: 1 });
|
|
641
|
+
|
|
642
|
+
// Medium priority - waits for high priority delay, then 100ms between these
|
|
643
|
+
queue.enqueue(mediumTask1, callback, { priority: 2 });
|
|
644
|
+
queue.enqueue(mediumTask2, callback, { priority: 2 });
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
### Batch Processing with Timeouts
|
|
648
|
+
|
|
649
|
+
```javascript
|
|
650
|
+
const queue = new HoldMyTask({
|
|
651
|
+
concurrency: 5,
|
|
652
|
+
delays: { 1: 50 } // Small delay between batches
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
async function processBatch(items) {
|
|
656
|
+
const results = [];
|
|
657
|
+
|
|
658
|
+
for (const item of items) {
|
|
659
|
+
queue.enqueue(
|
|
660
|
+
async (signal) => {
|
|
661
|
+
return await processItem(item, { signal });
|
|
662
|
+
},
|
|
663
|
+
(error, result) => {
|
|
664
|
+
if (error) {
|
|
665
|
+
console.error(`Item ${item.id} failed:`, error);
|
|
666
|
+
} else {
|
|
667
|
+
results.push(result);
|
|
668
|
+
}
|
|
669
|
+
},
|
|
670
|
+
{ priority: 1, timeout: 10000 }
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Wait for all to complete
|
|
675
|
+
await new Promise((resolve) => queue.on("drain", resolve));
|
|
676
|
+
return results;
|
|
677
|
+
}
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
### Emergency Task Management with Delay Bypass
|
|
681
|
+
|
|
682
|
+
Real-world scenario: API rate limiting with emergency override capability.
|
|
683
|
+
|
|
684
|
+
```javascript
|
|
685
|
+
const apiQueue = new HoldMyTask({
|
|
686
|
+
concurrency: 2,
|
|
687
|
+
delays: {
|
|
688
|
+
1: 2000, // 2 second delay between API calls (rate limiting)
|
|
689
|
+
2: 5000, // 5 second delay for heavy operations
|
|
690
|
+
9: 0 // No delay for monitoring tasks
|
|
691
|
+
}
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
// Regular API operations
|
|
695
|
+
apiQueue.enqueue(fetchUserData, handleResponse, { priority: 1 });
|
|
696
|
+
apiQueue.enqueue(syncDatabase, handleResponse, { priority: 2 });
|
|
697
|
+
|
|
698
|
+
// System monitoring (high priority, no delays)
|
|
699
|
+
apiQueue.enqueue(healthCheck, handleResponse, { priority: 9 });
|
|
700
|
+
|
|
701
|
+
// EMERGENCY: Critical security alert needs immediate processing
|
|
702
|
+
// This bypasses any active delays and runs immediately
|
|
703
|
+
apiQueue.enqueue(processSecurityAlert, handleEmergency, {
|
|
704
|
+
priority: 1,
|
|
705
|
+
bypassDelay: true, // Skip delay, run NOW
|
|
706
|
+
timeout: 10000, // 10 second timeout for critical task
|
|
707
|
+
metadata: { urgency: "critical", alertId: "SEC-001" }
|
|
708
|
+
});
|
|
709
|
+
|
|
710
|
+
// Alternative syntax for bypass
|
|
711
|
+
apiQueue.enqueue(emergencyShutdown, handleEmergency, {
|
|
712
|
+
priority: 1,
|
|
713
|
+
delay: -1, // Same as bypassDelay: true
|
|
714
|
+
metadata: { action: "shutdown" }
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
function handleEmergency(error, result) {
|
|
718
|
+
if (error) {
|
|
719
|
+
console.error("Emergency task failed:", error);
|
|
720
|
+
// Implement fallback procedures
|
|
721
|
+
} else {
|
|
722
|
+
console.log("Emergency handled:", result);
|
|
723
|
+
// Log to incident management system
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// Monitor queue status
|
|
728
|
+
setInterval(() => {
|
|
729
|
+
console.log(`Queue: ${apiQueue.size()} total, ${apiQueue.inflight()} running`);
|
|
730
|
+
}, 1000);
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
## 🧪 Testing & Development
|
|
734
|
+
|
|
735
|
+
```bash
|
|
736
|
+
# Run tests
|
|
737
|
+
npm test
|
|
738
|
+
|
|
739
|
+
# Run tests with coverage
|
|
740
|
+
npm run test:coverage
|
|
741
|
+
|
|
742
|
+
# Run tests in watch mode
|
|
743
|
+
npm run test:run
|
|
744
|
+
|
|
745
|
+
# Lint code
|
|
746
|
+
npm run lint
|
|
747
|
+
|
|
748
|
+
# Build for publishing
|
|
749
|
+
npm run build
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
### Testing with Injectable Clock
|
|
753
|
+
|
|
754
|
+
```javascript
|
|
755
|
+
const queue = new HoldMyTask({
|
|
756
|
+
now: () => mockTime // Control time in tests
|
|
757
|
+
});
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
## 📄 License
|
|
761
|
+
|
|
762
|
+
[](https://github.com/CLDMV/holdmytask/blob/HEAD/LICENSE) [](https://www.npmjs.com/package/@cldmv/holdmytask)
|
|
763
|
+
|
|
764
|
+
Apache License 2.0 - see [LICENSE](LICENSE) file for details.
|
|
765
|
+
|
|
766
|
+
## 🤝 Contributing
|
|
767
|
+
|
|
768
|
+
Contributions welcome! Please ensure:
|
|
769
|
+
|
|
770
|
+
- All tests pass
|
|
771
|
+
- Code follows existing style
|
|
772
|
+
- New features include tests
|
|
773
|
+
- Documentation is updated
|
|
774
|
+
|
|
775
|
+
---
|
|
776
|
+
|
|
777
|
+
**Made with ❤️ for robust task management**
|