@cldmv/holdmytask 1.1.0 → 1.3.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/README.md +760 -7
- package/dist/hold-my-task.mjs +1241 -43
- package/index.cjs +10 -1
- package/index.mjs +13 -1
- package/package.json +3 -3
- package/types/dist/hold-my-task.d.mts +473 -32
- package/types/dist/hold-my-task.d.mts.map +1 -1
- package/types/index.d.mts +3 -0
- package/types/index.d.mts.map +1 -0
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@ A tiny, dependency-free task queue for Node.js that executes tasks with priority
|
|
|
13
13
|
## ✨ Features
|
|
14
14
|
|
|
15
15
|
- **Smart scheduling** - Dynamic timeout-based scheduling for optimal performance
|
|
16
|
+
- **Task coalescing** - Intelligent merging of similar tasks for efficiency
|
|
16
17
|
- **Priority-based execution** - Higher priority tasks run first
|
|
17
18
|
- **Concurrency control** - Limit simultaneous task execution
|
|
18
19
|
- **Completion delays** - Configurable delays between task completions
|
|
@@ -37,7 +38,14 @@ The library provides flexible import options for different use cases:
|
|
|
37
38
|
### Production (Default)
|
|
38
39
|
|
|
39
40
|
```javascript
|
|
41
|
+
// Named import
|
|
40
42
|
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
43
|
+
|
|
44
|
+
// Default import
|
|
45
|
+
import HoldMyTask from "@cldmv/holdmytask";
|
|
46
|
+
|
|
47
|
+
// Import everything
|
|
48
|
+
import * as HoldMyTaskLib from "@cldmv/holdmytask";
|
|
41
49
|
// Uses optimized distribution files
|
|
42
50
|
```
|
|
43
51
|
|
|
@@ -48,6 +56,27 @@ import { HoldMyTask } from "@cldmv/holdmytask/main";
|
|
|
48
56
|
// Conditional: uses source files in development, dist files in production
|
|
49
57
|
```
|
|
50
58
|
|
|
59
|
+
### Common Queue System Aliases
|
|
60
|
+
|
|
61
|
+
For familiarity with other queue systems, several aliases are available:
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
import {
|
|
65
|
+
HoldMyTask, // Original class name
|
|
66
|
+
queue, // Lower-case alias for common conventions
|
|
67
|
+
Queue, // Standard queue naming
|
|
68
|
+
TaskManager, // Task management systems
|
|
69
|
+
TaskQueue, // Task-specific queuing
|
|
70
|
+
QueueManager, // Queue management systems
|
|
71
|
+
TaskProcessor // Task processing systems
|
|
72
|
+
} from "@cldmv/holdmytask";
|
|
73
|
+
|
|
74
|
+
// All aliases are functionally identical
|
|
75
|
+
const myQueue = new queue({ concurrency: 5 });
|
|
76
|
+
const stdQueue = new Queue({ concurrency: 5 });
|
|
77
|
+
const manager = new TaskManager({ priorities: { high: { delay: 100 } } });
|
|
78
|
+
```
|
|
79
|
+
|
|
51
80
|
### Direct Source Import (Development Only)
|
|
52
81
|
|
|
53
82
|
```javascript
|
|
@@ -57,14 +86,16 @@ import { HoldMyTask } from "@cldmv/holdmytask/src";
|
|
|
57
86
|
|
|
58
87
|
**Note:** The main import automatically runs environment checks in development mode to ensure proper configuration.
|
|
59
88
|
|
|
60
|
-
##
|
|
89
|
+
## 🚀 Quick Start
|
|
61
90
|
|
|
62
91
|
```javascript
|
|
63
92
|
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
64
93
|
|
|
65
94
|
const queue = new HoldMyTask({
|
|
66
95
|
concurrency: 2,
|
|
67
|
-
delays: { 1: 100, 2: 200 } // 100ms delay after priority 1 tasks, 200ms after priority 2
|
|
96
|
+
delays: { 1: 100, 2: 200 }, // 100ms delay after priority 1 tasks, 200ms after priority 2
|
|
97
|
+
coalescingWindowDuration: 200, // Group similar tasks within 200ms
|
|
98
|
+
coalescingMaxDelay: 1000 // Force execution after 1000ms max
|
|
68
99
|
});
|
|
69
100
|
|
|
70
101
|
// Enqueue a task
|
|
@@ -82,6 +113,14 @@ queue.enqueue(
|
|
|
82
113
|
},
|
|
83
114
|
{ priority: 1, timeout: 5000 }
|
|
84
115
|
);
|
|
116
|
+
|
|
117
|
+
// Coalescing example - multiple similar tasks become one
|
|
118
|
+
const results = await Promise.all([
|
|
119
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" }),
|
|
120
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" }),
|
|
121
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" })
|
|
122
|
+
]);
|
|
123
|
+
// Only one updateUI() call executes, all three promises resolve with the same result
|
|
85
124
|
```
|
|
86
125
|
|
|
87
126
|
## 🔄 Promise API
|
|
@@ -126,6 +165,67 @@ queue.enqueue(task1, callback, options);
|
|
|
126
165
|
const result = await queue.enqueue(task2, options);
|
|
127
166
|
```
|
|
128
167
|
|
|
168
|
+
## 🏗️ Async Constructor Pattern
|
|
169
|
+
|
|
170
|
+
HoldMyTask works excellently with async constructor patterns for classes that need initialization:
|
|
171
|
+
|
|
172
|
+
```javascript
|
|
173
|
+
class AsyncService {
|
|
174
|
+
constructor(options = {}) {
|
|
175
|
+
this.queue = new HoldMyTask({
|
|
176
|
+
concurrency: options.concurrency || 2,
|
|
177
|
+
maxQueue: -1 // Unlimited queue for initialization tasks
|
|
178
|
+
});
|
|
179
|
+
this.ready = this.initialize();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async initialize() {
|
|
183
|
+
// Initialization tasks that need to complete before the service is ready
|
|
184
|
+
await this.queue.enqueue(async () => {
|
|
185
|
+
this.config = await this.loadConfiguration();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
await this.queue.enqueue(async () => {
|
|
189
|
+
this.database = await this.connectToDatabase();
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
await this.queue.enqueue(async () => {
|
|
193
|
+
this.cache = await this.initializeCache();
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
return this;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async processData(data) {
|
|
200
|
+
// Ensure service is initialized before processing
|
|
201
|
+
await this.ready;
|
|
202
|
+
|
|
203
|
+
return this.queue.enqueue(async () => {
|
|
204
|
+
// Process data using initialized resources
|
|
205
|
+
return this.database.save(await this.transformData(data));
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Clean shutdown
|
|
210
|
+
async shutdown() {
|
|
211
|
+
await this.queue.drain(); // Wait for all tasks to complete
|
|
212
|
+
await this.database.close();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Usage
|
|
217
|
+
const service = new AsyncService({ concurrency: 5 });
|
|
218
|
+
await service.ready; // Wait for initialization
|
|
219
|
+
const result = await service.processData(someData);
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
This pattern is particularly useful for:
|
|
223
|
+
|
|
224
|
+
- **Database connections**: Initialize connections before accepting work
|
|
225
|
+
- **Configuration loading**: Load settings before processing tasks
|
|
226
|
+
- **Resource acquisition**: Set up required resources in a controlled manner
|
|
227
|
+
- **Dependency injection**: Initialize dependencies in the correct order
|
|
228
|
+
|
|
129
229
|
## 📚 API Reference
|
|
130
230
|
|
|
131
231
|
### Constructor
|
|
@@ -134,6 +234,28 @@ const result = await queue.enqueue(task2, options);
|
|
|
134
234
|
const queue = new HoldMyTask(options?)
|
|
135
235
|
```
|
|
136
236
|
|
|
237
|
+
### Async Initialization Pattern
|
|
238
|
+
|
|
239
|
+
For async initialization that allows event listeners to be attached before any initialization events can fire, use `sync: false`:
|
|
240
|
+
|
|
241
|
+
```javascript
|
|
242
|
+
// Create instance with async initialization
|
|
243
|
+
const queuePromise = new HoldMyTask({
|
|
244
|
+
concurrency: 5,
|
|
245
|
+
maxQueue: 100,
|
|
246
|
+
sync: false // Enable async initialization
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// Attach event listeners before initialization completes
|
|
250
|
+
queuePromise.on("error", (err) => console.error("Queue error:", err));
|
|
251
|
+
queuePromise.on("warning", (warning) => console.warn("Warning:", warning.message));
|
|
252
|
+
|
|
253
|
+
// Wait for initialization to complete
|
|
254
|
+
const queue = await queuePromise;
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
This pattern is particularly useful when you need to handle initialization errors or warnings through event listeners rather than try/catch blocks.
|
|
258
|
+
|
|
137
259
|
**Options:**
|
|
138
260
|
|
|
139
261
|
- `concurrency` (number, default: 1) - Maximum concurrent tasks
|
|
@@ -141,8 +263,21 @@ const queue = new HoldMyTask(options?)
|
|
|
141
263
|
- `tick` (number, default: 25) - Scheduler tick interval in milliseconds (used when smartScheduling is false)
|
|
142
264
|
- `autoStart` (boolean, default: true) - Whether to start processing immediately
|
|
143
265
|
- `defaultPriority` (number, default: 0) - Default task priority
|
|
144
|
-
- `maxQueue` (number, default: Infinity) - Maximum queued tasks
|
|
145
|
-
- `delays` (object, default: {}) - Priority-to-delay mapping for completion delays
|
|
266
|
+
- `maxQueue` (number, default: Infinity) - Maximum queued tasks. Use `-1` for unlimited queue capacity (equivalent to `Infinity`)
|
|
267
|
+
- `delays` (object, default: {}) - **DEPRECATED:** Priority-to-delay mapping for completion delays (use `priorities` instead)
|
|
268
|
+
- `priorities` (object, default: {}) - Priority-specific configuration: `{ [priority]: { delay, start } }`
|
|
269
|
+
- `coalescing` (object) - Enhanced coalescing configuration
|
|
270
|
+
- `defaults` (object) - Default settings for all coalescing keys
|
|
271
|
+
- `windowDuration` (number, default: 200) - Window duration in milliseconds
|
|
272
|
+
- `maxDelay` (number, default: 1000) - Maximum delay before forcing execution
|
|
273
|
+
- `delay` (number) - Default completion delay for coalescing tasks
|
|
274
|
+
- `start` (number) - Default start delay for coalescing tasks
|
|
275
|
+
- `resolveAllPromises` (boolean, default: true) - Whether all promises resolve with result
|
|
276
|
+
- `multipleCallbacks` (boolean, default: false) - Whether to call multiple callbacks
|
|
277
|
+
- `keys` (object) - Per-key configuration overrides: `{ [key]: { windowDuration, maxDelay, delay, start, ... } }`
|
|
278
|
+
- `coalescingWindowDuration` (number, default: 200) - **DEPRECATED:** Use `coalescing.defaults.windowDuration`
|
|
279
|
+
- `coalescingMaxDelay` (number, default: 1000) - **DEPRECATED:** Use `coalescing.defaults.maxDelay`
|
|
280
|
+
- `coalescingResolveAllPromises` (boolean, default: true) - **DEPRECATED:** Use `coalescing.defaults.resolveAllPromises`
|
|
146
281
|
- `onError` (function) - Global error handler
|
|
147
282
|
- `now` (function) - Injectable clock for testing
|
|
148
283
|
|
|
@@ -166,6 +301,9 @@ Adds a task to the queue.
|
|
|
166
301
|
- `timeout` (number) - Timeout in milliseconds
|
|
167
302
|
- `signal` (AbortSignal) - External abort signal
|
|
168
303
|
- `timestamp` (number) - Absolute execution timestamp
|
|
304
|
+
- `start` (number) - Milliseconds from now when the task should be ready to run (convenience for timestamp calculation)
|
|
305
|
+
- `coalescingKey` (string) - Tasks with the same coalescing key can be merged for efficiency
|
|
306
|
+
- `mustRunBy` (number) - Absolute timestamp by which the task must execute (overrides coalescing delays)
|
|
169
307
|
- `metadata` (any) - Custom metadata
|
|
170
308
|
|
|
171
309
|
**Returns:** TaskHandle object with:
|
|
@@ -180,14 +318,75 @@ Adds a task to the queue.
|
|
|
180
318
|
|
|
181
319
|
When `callback` is omitted, returns a Promise that resolves with the task result or rejects with an error.
|
|
182
320
|
|
|
321
|
+
#### Method Aliases
|
|
322
|
+
|
|
323
|
+
For compatibility with common queue system naming conventions, the following aliases are available:
|
|
324
|
+
|
|
325
|
+
- `schedule(task, callback?, options?)` - Alias for `enqueue()`
|
|
326
|
+
- `add(task, callback?, options?)` - Alias for `enqueue()`
|
|
327
|
+
|
|
328
|
+
```javascript
|
|
329
|
+
// These are all equivalent:
|
|
330
|
+
queue.enqueue(task, options);
|
|
331
|
+
queue.schedule(task, options);
|
|
332
|
+
queue.add(task, options);
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
#### Custom Task IDs
|
|
336
|
+
|
|
337
|
+
Tasks can be assigned custom IDs for easier tracking and management:
|
|
338
|
+
|
|
339
|
+
```javascript
|
|
340
|
+
// Assign custom ID
|
|
341
|
+
const task = queue.enqueue(myTask, { id: "user-action-123" });
|
|
342
|
+
console.log(task.id); // 'user-action-123'
|
|
343
|
+
|
|
344
|
+
// Task management by ID
|
|
345
|
+
queue.has("user-action-123"); // true
|
|
346
|
+
const task = queue.get("user-action-123"); // task object or null
|
|
347
|
+
queue.cancel("user-action-123", "User cancelled"); // returns true if cancelled
|
|
348
|
+
|
|
349
|
+
// Uniqueness is enforced
|
|
350
|
+
queue.enqueue(task1, { id: "duplicate" });
|
|
351
|
+
queue.enqueue(task2, { id: "duplicate" }); // throws: Task ID "duplicate" already exists
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
**ID Management Methods:**
|
|
355
|
+
|
|
356
|
+
- `has(id)` - Check if a task with the given ID exists
|
|
357
|
+
- `get(id)` - Get task object by ID (returns null if not found)
|
|
358
|
+
- `cancel(id, reason?)` - Cancel task by ID (returns boolean success)
|
|
359
|
+
|
|
360
|
+
**Method Aliases (for backward compatibility):**
|
|
361
|
+
|
|
362
|
+
- `hasTask(id)` - Alias for `has(id)`
|
|
363
|
+
- `getTask(id)` - Alias for `get(id)`
|
|
364
|
+
- `cancelTask(id, reason?)` - Alias for `cancel(id, reason?)`
|
|
365
|
+
|
|
183
366
|
#### Control Methods
|
|
184
367
|
|
|
185
368
|
- `pause()` - Pause task execution
|
|
186
369
|
- `resume()` - Resume task execution
|
|
187
370
|
- `clear()` - Cancel all pending tasks
|
|
188
371
|
- `size()` - Get total queued tasks
|
|
372
|
+
- `length()` - Alias for `size()` - get total queued tasks
|
|
189
373
|
- `inflight()` - Get currently running tasks
|
|
190
374
|
- `destroy()` - Destroy the queue and cancel all tasks
|
|
375
|
+
- `shutdown()` - Alias for `destroy()` - convenient for common queue system naming
|
|
376
|
+
- `now()` - Get current timestamp (useful for testing with custom clocks)
|
|
377
|
+
|
|
378
|
+
#### Configuration Methods
|
|
379
|
+
|
|
380
|
+
- `configurePriority(priority, config)` - Configure or update priority-specific settings
|
|
381
|
+
- `priority` (string|number) - Priority level to configure
|
|
382
|
+
- `config` (object) - Configuration: `{ delay?, maxDelay?, start? }`
|
|
383
|
+
- `configureCoalescingKey(key, config)` - Configure or update coalescing key settings
|
|
384
|
+
- `key` (string) - Coalescing key to configure
|
|
385
|
+
- `config` (object) - Configuration: `{ windowDuration?, maxDelay?, delay?, start?, multipleCallbacks?, resolveAllPromises? }`
|
|
386
|
+
- `getPriorityConfig(priority, taskOptions?)` - Get effective configuration for a specific priority
|
|
387
|
+
- `getPriorityConfigurations()` - Get all configured priorities and their settings
|
|
388
|
+
- `getCoalescingConfig(coalescingKey, taskOptions?)` - Get effective configuration for a specific coalescing key
|
|
389
|
+
- `getCoalescingConfigurations()` - Get all configured coalescing keys and their settings
|
|
191
390
|
|
|
192
391
|
### Events
|
|
193
392
|
|
|
@@ -207,6 +406,31 @@ queue.on("cancel", (task, reason) => {
|
|
|
207
406
|
queue.on("drain", () => {
|
|
208
407
|
/* all tasks completed */
|
|
209
408
|
});
|
|
409
|
+
queue.on("warning", (warning) => {
|
|
410
|
+
/* deprecation or configuration warning */
|
|
411
|
+
});
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### Deprecation Warning Events
|
|
415
|
+
|
|
416
|
+
When deprecated configuration options are used, HoldMyTask emits `warning` events to help with migration:
|
|
417
|
+
|
|
418
|
+
```javascript
|
|
419
|
+
const queue = new HoldMyTask({
|
|
420
|
+
delays: { 1: 100 }, // Deprecated option
|
|
421
|
+
coalescingWindowDuration: 200 // Deprecated option
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
queue.on("warning", (warning) => {
|
|
425
|
+
console.warn(`Deprecation Warning: ${warning.message}`);
|
|
426
|
+
console.warn(`Use: ${warning.replacement}`);
|
|
427
|
+
console.warn(`In: ${warning.source}`);
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
// Output:
|
|
431
|
+
// Deprecation Warning: Option 'delays' is deprecated
|
|
432
|
+
// Use: priorities: { 1: { delay: 100 } }
|
|
433
|
+
// In: constructor options
|
|
210
434
|
```
|
|
211
435
|
|
|
212
436
|
## ⚙️ Concurrency & Delays Interaction
|
|
@@ -283,6 +507,33 @@ This architecture enables handling thousands of tasks with precise timing contro
|
|
|
283
507
|
|
|
284
508
|
[](https://www.npmjs.com/package/@cldmv/holdmytask) [](https://github.com/CLDMV/holdmytask)
|
|
285
509
|
|
|
510
|
+
### Unlimited Queue Capacity
|
|
511
|
+
|
|
512
|
+
For scenarios requiring unlimited task queuing, you can set `maxQueue` to `-1`:
|
|
513
|
+
|
|
514
|
+
```javascript
|
|
515
|
+
const queue = new HoldMyTask({
|
|
516
|
+
concurrency: 5,
|
|
517
|
+
maxQueue: -1 // Unlimited queue capacity (equivalent to Infinity)
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// Now you can enqueue unlimited tasks without hitting queue limits
|
|
521
|
+
for (let i = 0; i < 100000; i++) {
|
|
522
|
+
queue.enqueue(async () => processTask(i));
|
|
523
|
+
}
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
**Use Cases:**
|
|
527
|
+
|
|
528
|
+
- **Batch processing**: When processing large datasets where queue size is unpredictable
|
|
529
|
+
- **Event-driven systems**: Where task volume can spike dramatically
|
|
530
|
+
- **Data pipelines**: For ETL operations with variable input sizes
|
|
531
|
+
- **Development/testing**: When you need to stress-test with large task volumes
|
|
532
|
+
|
|
533
|
+
**Memory Considerations:**
|
|
534
|
+
|
|
535
|
+
While `-1` allows unlimited queuing, be mindful of memory usage with very large task sets. Each queued task consumes memory until executed.
|
|
536
|
+
|
|
286
537
|
## 🎯 Advanced Features
|
|
287
538
|
|
|
288
539
|
### Priority System
|
|
@@ -305,6 +556,78 @@ await queue.enqueue(task2, { priority: 10 }); // Runs first
|
|
|
305
556
|
await queue.enqueue(task3, { priority: 5 });
|
|
306
557
|
```
|
|
307
558
|
|
|
559
|
+
### Enhanced Priority & Coalescing Configuration
|
|
560
|
+
|
|
561
|
+
HoldMyTask supports comprehensive priority and coalescing configuration for sophisticated timing control:
|
|
562
|
+
|
|
563
|
+
```javascript
|
|
564
|
+
const queue = new HoldMyTask({
|
|
565
|
+
concurrency: 3,
|
|
566
|
+
// Priority-specific defaults (replaces legacy delays)
|
|
567
|
+
priorities: {
|
|
568
|
+
1: { delay: 200, start: 0 }, // High priority: 200ms delay, immediate start
|
|
569
|
+
2: { delay: 100, start: 25 }, // Medium priority: 100ms delay, 25ms start delay
|
|
570
|
+
3: { delay: 50, start: 50 } // Low priority: 50ms delay, 50ms start delay
|
|
571
|
+
},
|
|
572
|
+
// Enhanced coalescing with per-key settings
|
|
573
|
+
coalescing: {
|
|
574
|
+
defaults: {
|
|
575
|
+
windowDuration: 200,
|
|
576
|
+
maxDelay: 1000,
|
|
577
|
+
delay: 75, // Default completion delay for coalescing tasks
|
|
578
|
+
start: 25, // Default start delay for coalescing tasks
|
|
579
|
+
resolveAllPromises: true
|
|
580
|
+
},
|
|
581
|
+
keys: {
|
|
582
|
+
"ui.update": {
|
|
583
|
+
windowDuration: 100,
|
|
584
|
+
maxDelay: 500,
|
|
585
|
+
delay: 25, // Fast UI updates
|
|
586
|
+
start: 0
|
|
587
|
+
},
|
|
588
|
+
"api.batch": {
|
|
589
|
+
windowDuration: 1000,
|
|
590
|
+
maxDelay: 5000,
|
|
591
|
+
delay: 200, // Slower API operations
|
|
592
|
+
start: 100
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
// Dynamic configuration
|
|
599
|
+
queue.configurePriority(4, { delay: 300, start: 75 });
|
|
600
|
+
queue.configureCoalescingKey("data.sync", {
|
|
601
|
+
windowDuration: 800,
|
|
602
|
+
maxDelay: 3000,
|
|
603
|
+
delay: 150,
|
|
604
|
+
start: 50
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
// Get configuration information
|
|
608
|
+
const priority4Config = queue.getPriorityConfig(4);
|
|
609
|
+
console.log(`Priority 4: ${priority4Config.delay}ms delay, ${priority4Config.start}ms start delay`);
|
|
610
|
+
|
|
611
|
+
const dataSyncConfig = queue.getCoalescingConfig("data.sync");
|
|
612
|
+
console.log(`Data sync: ${dataSyncConfig.windowDuration}ms window, ${dataSyncConfig.maxDelay}ms max delay`);
|
|
613
|
+
|
|
614
|
+
// Get all configurations
|
|
615
|
+
const allPriorities = queue.getPriorityConfigurations();
|
|
616
|
+
const allCoalescingKeys = queue.getCoalescingConfigurations();
|
|
617
|
+
console.log("All priority configs:", allPriorities);
|
|
618
|
+
console.log("All coalescing configs:", allCoalescingKeys);
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
**Configuration Hierarchy:**
|
|
622
|
+
|
|
623
|
+
1. Task-level options (highest priority)
|
|
624
|
+
2. Coalescing key configuration
|
|
625
|
+
3. Priority defaults
|
|
626
|
+
4. Coalescing defaults
|
|
627
|
+
5. System defaults (lowest priority)
|
|
628
|
+
|
|
629
|
+
**Backward Compatibility:** Legacy `delays` options are automatically converted to the new `priorities` format.
|
|
630
|
+
|
|
308
631
|
### Smart Scheduling
|
|
309
632
|
|
|
310
633
|
By default, HoldMyTask uses intelligent dynamic scheduling that calculates optimal timeout intervals based on when tasks should become ready. This provides significant performance improvements over traditional polling.
|
|
@@ -383,13 +706,13 @@ const queue = new HoldMyTask({
|
|
|
383
706
|
// Timeline example:
|
|
384
707
|
// 10:00:00 - Task A (priority 1) completes → 1000ms delay starts
|
|
385
708
|
// 10:00:00.1 - Normal task B enqueued → must wait until 10:01:00
|
|
386
|
-
// 10:00:00.2 - Urgent task C enqueued with bypass →
|
|
709
|
+
// 10:00:00.2 - Urgent task C enqueued with bypass → can start now (bypasses delay)
|
|
387
710
|
|
|
388
711
|
queue.enqueue(normalTaskB, callback, { priority: 1 }); // Waits for delay
|
|
389
712
|
|
|
390
713
|
queue.enqueue(urgentTaskC, callback, {
|
|
391
714
|
priority: 1,
|
|
392
|
-
bypassDelay: true // Skips the 1000ms delay,
|
|
715
|
+
bypassDelay: true // Skips the 1000ms delay, can start now
|
|
393
716
|
});
|
|
394
717
|
|
|
395
718
|
// Alternative bypass syntax
|
|
@@ -410,7 +733,7 @@ const queue = new HoldMyTask({
|
|
|
410
733
|
// Multiple tasks with different bypass behavior
|
|
411
734
|
queue.enqueue(taskA, callback, { priority: 1 }); // Completes, starts 800ms delay
|
|
412
735
|
queue.enqueue(taskB, callback, { priority: 2 }); // Waits for 800ms delay
|
|
413
|
-
queue.enqueue(taskC, callback, { priority: 2, bypassDelay: true }); //
|
|
736
|
+
queue.enqueue(taskC, callback, { priority: 2, bypassDelay: true }); // Bypasses delay, can start now
|
|
414
737
|
queue.enqueue(taskD, callback, { priority: 1 }); // Waits for taskC's completion delay
|
|
415
738
|
|
|
416
739
|
// Execution order: taskA → taskC (bypass) → taskB → taskD
|
|
@@ -424,6 +747,423 @@ queue.enqueue(taskD, callback, { priority: 1 }); // Waits for taskC's completion
|
|
|
424
747
|
- ✅ **Concurrency aware** - works correctly with multiple concurrent execution slots
|
|
425
748
|
- ⚠️ **Use sparingly** - frequent bypassing defeats the purpose of delay-based rate limiting
|
|
426
749
|
|
|
750
|
+
## 🔄 Task Coalescing System
|
|
751
|
+
|
|
752
|
+
The coalescing system allows multiple similar tasks to be intelligently merged, reducing redundant operations while ensuring all promises resolve with accurate results. This is perfect for scenarios like UI updates, API calls, or device commands where only the final result matters.
|
|
753
|
+
|
|
754
|
+
### How Coalescing Works
|
|
755
|
+
|
|
756
|
+
When tasks with the same `coalescingKey` are enqueued within a time window, they get merged into groups:
|
|
757
|
+
|
|
758
|
+
1. **First task** creates a new coalescing group with a time window
|
|
759
|
+
2. **Subsequent tasks** with the same key join the existing group (if within the window)
|
|
760
|
+
3. **One representative task** executes for the entire group
|
|
761
|
+
4. **All promises** in the group resolve with the same result
|
|
762
|
+
|
|
763
|
+
⚠️ **Critical Timing Consideration**: Real-world tasks take time to execute (100ms-2000ms+). If your coalescing tasks need to see the final state from other operations, ensure proper timing with `start` delays or `timestamp` scheduling. Tasks that start too early may see intermediate states rather than final results.
|
|
764
|
+
|
|
765
|
+
### 🎯 Correct Coalescing Pattern: Fire-and-Forget with Embedded Updates
|
|
766
|
+
|
|
767
|
+
The most reliable pattern for coalescing with state consistency is the **"fire-and-forget with embedded updates"** approach:
|
|
768
|
+
|
|
769
|
+
**❌ WRONG - Parallel Enqueueing:**
|
|
770
|
+
|
|
771
|
+
```javascript
|
|
772
|
+
// DON'T DO THIS - creates race conditions
|
|
773
|
+
function volumeUp() {
|
|
774
|
+
const volumePromise = queue.enqueue(changeVolume, { priority: 1 });
|
|
775
|
+
const updatePromise = queue.enqueue(updateUI, { coalescingKey: "ui" }); // May see stale state
|
|
776
|
+
return Promise.all([volumePromise, updatePromise]);
|
|
777
|
+
}
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
**✅ CORRECT - Embedded Update Pattern:**
|
|
781
|
+
|
|
782
|
+
```javascript
|
|
783
|
+
// DO THIS - guarantees state consistency
|
|
784
|
+
function volumeUp() {
|
|
785
|
+
return queue.enqueue(
|
|
786
|
+
async () => {
|
|
787
|
+
// 1. Perform the main operation
|
|
788
|
+
const result = await changeVolume();
|
|
789
|
+
|
|
790
|
+
// 2. AFTER main operation completes, enqueue the update FROM WITHIN
|
|
791
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui" }); // Always sees final state
|
|
792
|
+
|
|
793
|
+
return result; // Consumer gets immediate response
|
|
794
|
+
},
|
|
795
|
+
{ priority: 1 }
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
**Key Benefits:**
|
|
801
|
+
|
|
802
|
+
- ✅ **100% State Accuracy**: Updates only trigger after main operations complete
|
|
803
|
+
- ✅ **Fire-and-Forget**: Consumers get immediate responses, no waiting
|
|
804
|
+
- ✅ **Optimal Coalescing**: Multiple updates coalesce naturally when triggered close together
|
|
805
|
+
- ✅ **No Race Conditions**: Sequential execution guarantees consistent state
|
|
806
|
+
|
|
807
|
+
### Basic Coalescing Configuration
|
|
808
|
+
|
|
809
|
+
```javascript
|
|
810
|
+
const queue = new HoldMyTask({
|
|
811
|
+
concurrency: 1,
|
|
812
|
+
coalescingWindowDuration: 200, // 200ms window for grouping tasks
|
|
813
|
+
coalescingMaxDelay: 1000, // Maximum 1000ms delay before forcing execution
|
|
814
|
+
coalescingResolveAllPromises: true // All promises get the result (default: true)
|
|
815
|
+
});
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
### Simple Coalescing Example
|
|
819
|
+
|
|
820
|
+
```javascript
|
|
821
|
+
// Device volume control scenario
|
|
822
|
+
async function updateVolume(change) {
|
|
823
|
+
return queue.enqueue(
|
|
824
|
+
async () => {
|
|
825
|
+
// Realistic device operations take time
|
|
826
|
+
const currentVolume = await device.getVolume(); // ~50-200ms
|
|
827
|
+
const newVolume = Math.max(0, Math.min(100, currentVolume + change));
|
|
828
|
+
await device.setVolume(newVolume); // ~100-500ms
|
|
829
|
+
return newVolume;
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
coalescingKey: "volume.update", // Tasks with same key get grouped
|
|
833
|
+
priority: 1,
|
|
834
|
+
delay: 100 // 100ms delay after completion
|
|
835
|
+
}
|
|
836
|
+
);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// User rapidly presses volume up 5 times within coalescing window
|
|
840
|
+
const results = await Promise.all([
|
|
841
|
+
updateVolume(1), // Creates new group
|
|
842
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
843
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
844
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
845
|
+
updateVolume(1) // Joins existing group (if within 200ms window)
|
|
846
|
+
]);
|
|
847
|
+
|
|
848
|
+
// If all tasks coalesce: ONE device.setVolume() call with final state
|
|
849
|
+
// If timing spreads them: Multiple groups, each sees state at execution time
|
|
850
|
+
console.log(results); // Could be [55, 55, 55, 55, 55] or [51, 53, 55, 55, 55] depending on timing
|
|
851
|
+
```
|
|
852
|
+
|
|
853
|
+
### Advanced Coalescing with Fire-and-Forget Pattern
|
|
854
|
+
|
|
855
|
+
The correct pattern for coalescing with updates is to enqueue update tasks **from within** the main tasks after they complete. This ensures 100% accuracy and proper state consistency:
|
|
856
|
+
|
|
857
|
+
```javascript
|
|
858
|
+
const queue = new HoldMyTask({
|
|
859
|
+
concurrency: 2, // Allow volume and update tasks to run concurrently
|
|
860
|
+
coalescingWindowDuration: 200,
|
|
861
|
+
coalescingMaxDelay: 1000
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
// Volume commands using fire-and-forget pattern
|
|
865
|
+
function volumeUp(amount = 1) {
|
|
866
|
+
const commandId = Date.now();
|
|
867
|
+
|
|
868
|
+
// Fire-and-forget: return promise but consumer doesn't await it
|
|
869
|
+
return queue.enqueue(
|
|
870
|
+
async () => {
|
|
871
|
+
console.log(`Executing volume command ${commandId}`);
|
|
872
|
+
// Realistic device operation takes time
|
|
873
|
+
const result = await device.increaseVolume(amount); // 200-1000ms
|
|
874
|
+
|
|
875
|
+
// AFTER volume completes, enqueue update task FROM WITHIN
|
|
876
|
+
console.log(`Volume complete, triggering UI update`);
|
|
877
|
+
queue.enqueue(
|
|
878
|
+
async () => {
|
|
879
|
+
console.log(`Updating UI for final volume`);
|
|
880
|
+
// UI operation sees accurate final state
|
|
881
|
+
const volume = await device.getVolume(); // ~50ms
|
|
882
|
+
updateVolumeDisplay(volume); // ~10-100ms
|
|
883
|
+
return volume;
|
|
884
|
+
},
|
|
885
|
+
{
|
|
886
|
+
coalescingKey: "volume.ui.update", // UI updates get coalesced
|
|
887
|
+
priority: 5, // Lower priority than volume commands
|
|
888
|
+
delay: 100 // Brief delay after UI updates
|
|
889
|
+
}
|
|
890
|
+
);
|
|
891
|
+
|
|
892
|
+
return result;
|
|
893
|
+
},
|
|
894
|
+
{
|
|
895
|
+
priority: 1, // High priority for user actions
|
|
896
|
+
delay: 100 // Brief delay after volume operations
|
|
897
|
+
}
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// Consumer usage - fire and forget
|
|
902
|
+
volumeUp(1); // Optimistic: assume it will work, don't wait
|
|
903
|
+
volumeUp(1); // Multiple rapid calls
|
|
904
|
+
volumeUp(1); // Each triggers its own update after completing
|
|
905
|
+
volumeUp(1); // Updates get coalesced if close together
|
|
906
|
+
volumeUp(1); // Final state is always accurate
|
|
907
|
+
|
|
908
|
+
// Result: 5 volume commands execute sequentially
|
|
909
|
+
// Update commands coalesce (e.g., 5 → 3 actual updates)
|
|
910
|
+
// UI always shows accurate final state because updates only trigger after volume changes
|
|
911
|
+
// Consumer gets immediate response, no waiting for completion
|
|
912
|
+
```
|
|
913
|
+
|
|
914
|
+
### Multi-Group Coalescing
|
|
915
|
+
|
|
916
|
+
The same `coalescingKey` can have multiple active groups based on timing windows:
|
|
917
|
+
|
|
918
|
+
```javascript
|
|
919
|
+
// API batch processing
|
|
920
|
+
async function processDataBatch(data) {
|
|
921
|
+
return queue.enqueue(
|
|
922
|
+
async () => {
|
|
923
|
+
console.log(`Processing batch with ${data.length} items`);
|
|
924
|
+
return await api.processBatch(data);
|
|
925
|
+
},
|
|
926
|
+
{
|
|
927
|
+
coalescingKey: "api.batch.process",
|
|
928
|
+
priority: 2,
|
|
929
|
+
start: 100 // 100ms delay allows grouping
|
|
930
|
+
}
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// Timeline:
|
|
935
|
+
// 0ms: processDataBatch(data1) → creates Group A (window: 0-200ms)
|
|
936
|
+
// 50ms: processDataBatch(data2) → joins Group A
|
|
937
|
+
// 250ms: processDataBatch(data3) → creates Group B (window: 250-450ms)
|
|
938
|
+
// 300ms: processDataBatch(data4) → joins Group B
|
|
939
|
+
// 500ms: processDataBatch(data5) → creates Group C (window: 500-700ms)
|
|
940
|
+
|
|
941
|
+
// Result: 3 separate API calls, each processing coalesced batches
|
|
942
|
+
```
|
|
943
|
+
|
|
944
|
+
### Coalescing with Explicit Timestamps
|
|
945
|
+
|
|
946
|
+
For precise scheduling, use `timestamp` instead of `start`:
|
|
947
|
+
|
|
948
|
+
```javascript
|
|
949
|
+
const queue = new HoldMyTask({
|
|
950
|
+
coalescingWindowDuration: 300,
|
|
951
|
+
coalescingMaxDelay: 2000
|
|
952
|
+
});
|
|
953
|
+
|
|
954
|
+
// Schedule all updates for the same exact time
|
|
955
|
+
const scheduleTime = Date.now() + 1000; // 1 second from now
|
|
956
|
+
|
|
957
|
+
const promises = [];
|
|
958
|
+
for (let i = 0; i < 10; i++) {
|
|
959
|
+
promises.push(
|
|
960
|
+
queue.enqueue(
|
|
961
|
+
async () => {
|
|
962
|
+
console.log("Executing coalesced batch update");
|
|
963
|
+
return await performBatchUpdate();
|
|
964
|
+
},
|
|
965
|
+
{
|
|
966
|
+
coalescingKey: "batch.update",
|
|
967
|
+
timestamp: scheduleTime, // All scheduled for same time
|
|
968
|
+
priority: 3
|
|
969
|
+
}
|
|
970
|
+
)
|
|
971
|
+
);
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// All 10 tasks coalesce into 1 execution at exactly scheduleTime
|
|
975
|
+
const results = await Promise.all(promises);
|
|
976
|
+
console.log(`10 tasks became 1 execution, all got result:`, results[0]);
|
|
977
|
+
```
|
|
978
|
+
|
|
979
|
+
### Must-Run-By Deadlines
|
|
980
|
+
|
|
981
|
+
Control maximum delay with `mustRunBy` to ensure tasks don't wait too long:
|
|
982
|
+
|
|
983
|
+
```javascript
|
|
984
|
+
const queue = new HoldMyTask({
|
|
985
|
+
coalescingWindowDuration: 500, // Try to group for 500ms
|
|
986
|
+
coalescingMaxDelay: 2000 // But never wait more than 2 seconds
|
|
987
|
+
});
|
|
988
|
+
|
|
989
|
+
// Critical system updates
|
|
990
|
+
async function criticalSystemUpdate(updateData) {
|
|
991
|
+
return queue.enqueue(
|
|
992
|
+
async () => {
|
|
993
|
+
console.log("Executing critical system update");
|
|
994
|
+
return await applySystemUpdate(updateData);
|
|
995
|
+
},
|
|
996
|
+
{
|
|
997
|
+
coalescingKey: "system.critical.update",
|
|
998
|
+
priority: 1,
|
|
999
|
+
timestamp: Date.now() + 300, // Prefer 300ms delay
|
|
1000
|
+
mustRunBy: Date.now() + 1500 // Must run within 1.5 seconds
|
|
1001
|
+
}
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// Even if coalescing window suggests waiting longer,
|
|
1006
|
+
// the task will execute by the mustRunBy deadline
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
### Promise Resolution Modes
|
|
1010
|
+
|
|
1011
|
+
Control how promises resolve within coalescing groups:
|
|
1012
|
+
|
|
1013
|
+
```javascript
|
|
1014
|
+
const queue = new HoldMyTask({
|
|
1015
|
+
coalescingResolveAllPromises: true, // Default: all promises get the result
|
|
1016
|
+
coalescingWindowDuration: 200
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
// Mode 1: All promises resolve (default behavior)
|
|
1020
|
+
const results1 = await Promise.all([
|
|
1021
|
+
queue.enqueue(task, { coalescingKey: "test" }),
|
|
1022
|
+
queue.enqueue(task, { coalescingKey: "test" }),
|
|
1023
|
+
queue.enqueue(task, { coalescingKey: "test" })
|
|
1024
|
+
]);
|
|
1025
|
+
// All three promises resolve with the same result
|
|
1026
|
+
|
|
1027
|
+
// Mode 2: Only representative promise resolves
|
|
1028
|
+
const queue2 = new HoldMyTask({
|
|
1029
|
+
coalescingResolveAllPromises: false,
|
|
1030
|
+
coalescingWindowDuration: 200
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
const [result1, result2, result3] = await Promise.all([
|
|
1034
|
+
queue2.enqueue(task, { coalescingKey: "test" }), // Resolves with result
|
|
1035
|
+
queue2.enqueue(task, { coalescingKey: "test" }), // Resolves with undefined
|
|
1036
|
+
queue2.enqueue(task, { coalescingKey: "test" }) // Resolves with undefined
|
|
1037
|
+
]);
|
|
1038
|
+
// Only the first (representative) promise gets the actual result
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
### Real-World Coalescing Patterns
|
|
1042
|
+
|
|
1043
|
+
#### Device Control Pattern
|
|
1044
|
+
|
|
1045
|
+
```javascript
|
|
1046
|
+
class VolumeController {
|
|
1047
|
+
constructor() {
|
|
1048
|
+
this.queue = new HoldMyTask({
|
|
1049
|
+
concurrency: 2, // Allow volume and update tasks concurrently
|
|
1050
|
+
coalescingWindowDuration: 200,
|
|
1051
|
+
coalescingMaxDelay: 1000
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
volumeUp(amount = 1) {
|
|
1056
|
+
// Fire-and-forget pattern: consumer gets immediate response
|
|
1057
|
+
return this.queue.enqueue(
|
|
1058
|
+
async () => {
|
|
1059
|
+
// Realistic device operations take time
|
|
1060
|
+
const currentVolume = await this.device.getVolume(); // ~50-200ms
|
|
1061
|
+
const newVolume = Math.min(100, currentVolume + amount);
|
|
1062
|
+
await this.device.setVolume(newVolume); // ~100-500ms
|
|
1063
|
+
|
|
1064
|
+
// AFTER volume change completes, enqueue UI update FROM WITHIN
|
|
1065
|
+
this.queue.enqueue(
|
|
1066
|
+
async () => {
|
|
1067
|
+
const volume = await this.device.getVolume(); // ~50ms
|
|
1068
|
+
this.ui.updateVolumeDisplay(volume); // ~10-100ms
|
|
1069
|
+
return volume;
|
|
1070
|
+
},
|
|
1071
|
+
{
|
|
1072
|
+
coalescingKey: "volume.ui.update", // Updates coalesce together
|
|
1073
|
+
priority: 3, // Lower priority than volume changes
|
|
1074
|
+
delay: 100 // Brief delay after UI updates
|
|
1075
|
+
}
|
|
1076
|
+
);
|
|
1077
|
+
|
|
1078
|
+
return newVolume;
|
|
1079
|
+
},
|
|
1080
|
+
{
|
|
1081
|
+
priority: 1, // High priority for user actions
|
|
1082
|
+
delay: 50 // Brief delay between volume operations
|
|
1083
|
+
}
|
|
1084
|
+
);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
```
|
|
1088
|
+
|
|
1089
|
+
#### API Batch Processing Pattern
|
|
1090
|
+
|
|
1091
|
+
```javascript
|
|
1092
|
+
class APIBatcher {
|
|
1093
|
+
constructor() {
|
|
1094
|
+
this.queue = new HoldMyTask({
|
|
1095
|
+
concurrency: 2,
|
|
1096
|
+
coalescingWindowDuration: 300,
|
|
1097
|
+
coalescingMaxDelay: 1500
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
async submitData(data) {
|
|
1102
|
+
return this.queue.enqueue(
|
|
1103
|
+
async () => {
|
|
1104
|
+
// All data submissions in the time window get batched
|
|
1105
|
+
const batchData = this.collectBatchData(); // Implementation detail
|
|
1106
|
+
const result = await this.api.submitBatch(batchData);
|
|
1107
|
+
return result.find((item) => item.id === data.id);
|
|
1108
|
+
},
|
|
1109
|
+
{
|
|
1110
|
+
coalescingKey: `batch.${data.category}`, // Batch by category
|
|
1111
|
+
priority: 2,
|
|
1112
|
+
metadata: { data, category: data.category }
|
|
1113
|
+
}
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
### Coalescing Performance Benefits
|
|
1120
|
+
|
|
1121
|
+
Real-world performance improvements with the embedded update pattern:
|
|
1122
|
+
|
|
1123
|
+
```javascript
|
|
1124
|
+
// Fire-and-forget pattern with embedded coalescing updates
|
|
1125
|
+
const queue = new HoldMyTask({
|
|
1126
|
+
concurrency: 2,
|
|
1127
|
+
coalescingWindowDuration: 200,
|
|
1128
|
+
coalescingMaxDelay: 1000
|
|
1129
|
+
});
|
|
1130
|
+
|
|
1131
|
+
// Volume control example - realistic embedded pattern
|
|
1132
|
+
function processVolumeCommands() {
|
|
1133
|
+
// Consumer fires 100 rapid volume commands (fire-and-forget)
|
|
1134
|
+
const promises = [];
|
|
1135
|
+
for (let i = 0; i < 100; i++) {
|
|
1136
|
+
promises.push(
|
|
1137
|
+
queue.enqueue(
|
|
1138
|
+
async () => {
|
|
1139
|
+
// Main operation: change volume (200-500ms each)
|
|
1140
|
+
const result = await device.changeVolume(1);
|
|
1141
|
+
|
|
1142
|
+
// Embedded update: triggered AFTER volume change (coalesces automatically)
|
|
1143
|
+
queue.enqueue(
|
|
1144
|
+
async () => updateVolumeDisplay(), // 50-100ms each
|
|
1145
|
+
{ coalescingKey: "volume.display" }
|
|
1146
|
+
);
|
|
1147
|
+
|
|
1148
|
+
return result; // Immediate response to consumer
|
|
1149
|
+
},
|
|
1150
|
+
{ priority: 1 }
|
|
1151
|
+
)
|
|
1152
|
+
);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// Consumer gets immediate responses, doesn't wait for display updates
|
|
1156
|
+
return promises; // All resolve quickly with volume results
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// Results with embedded coalescing:
|
|
1160
|
+
// - 100 volume operations execute (necessary work)
|
|
1161
|
+
// - ~5-15 display updates execute (95-85% coalescing efficiency)
|
|
1162
|
+
// - 100% accuracy: displays always show final state
|
|
1163
|
+
// - Fire-and-forget: consumers get immediate responses
|
|
1164
|
+
// - Total time: ~25-30 seconds (vs 50+ seconds without coalescing)
|
|
1165
|
+
```
|
|
1166
|
+
|
|
427
1167
|
### Timeouts
|
|
428
1168
|
|
|
429
1169
|
Tasks automatically timeout and either call the callback with an error or reject the promise:
|
|
@@ -782,10 +1522,23 @@ npm run build
|
|
|
782
1522
|
|
|
783
1523
|
### Testing with Injectable Clock
|
|
784
1524
|
|
|
1525
|
+
For testing, you can inject a custom clock function and use the `now()` method to get the current time according to your queue:
|
|
1526
|
+
|
|
785
1527
|
```javascript
|
|
1528
|
+
let mockTime = Date.now();
|
|
786
1529
|
const queue = new HoldMyTask({
|
|
787
1530
|
now: () => mockTime // Control time in tests
|
|
788
1531
|
});
|
|
1532
|
+
|
|
1533
|
+
// In tests, you can advance time
|
|
1534
|
+
mockTime += 1000; // Advance by 1 second
|
|
1535
|
+
|
|
1536
|
+
// The queue's now() method respects your custom clock
|
|
1537
|
+
console.log(queue.now()); // Returns mockTime value
|
|
1538
|
+
console.log(Date.now()); // Returns actual system time
|
|
1539
|
+
|
|
1540
|
+
// Useful for testing time-based behavior
|
|
1541
|
+
queue.enqueue(task, { timestamp: queue.now() + 5000 }); // 5 seconds from mock time
|
|
789
1542
|
```
|
|
790
1543
|
|
|
791
1544
|
## 📄 License
|