@cldmv/holdmytask 1.1.0 → 1.2.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 +439 -5
- package/package.json +3 -3
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
|
|
@@ -57,14 +58,16 @@ import { HoldMyTask } from "@cldmv/holdmytask/src";
|
|
|
57
58
|
|
|
58
59
|
**Note:** The main import automatically runs environment checks in development mode to ensure proper configuration.
|
|
59
60
|
|
|
60
|
-
##
|
|
61
|
+
## 🚀 Quick Start
|
|
61
62
|
|
|
62
63
|
```javascript
|
|
63
64
|
import { HoldMyTask } from "@cldmv/holdmytask";
|
|
64
65
|
|
|
65
66
|
const queue = new HoldMyTask({
|
|
66
67
|
concurrency: 2,
|
|
67
|
-
delays: { 1: 100, 2: 200 } // 100ms delay after priority 1 tasks, 200ms after priority 2
|
|
68
|
+
delays: { 1: 100, 2: 200 }, // 100ms delay after priority 1 tasks, 200ms after priority 2
|
|
69
|
+
coalescingWindowDuration: 200, // Group similar tasks within 200ms
|
|
70
|
+
coalescingMaxDelay: 1000 // Force execution after 1000ms max
|
|
68
71
|
});
|
|
69
72
|
|
|
70
73
|
// Enqueue a task
|
|
@@ -82,6 +85,14 @@ queue.enqueue(
|
|
|
82
85
|
},
|
|
83
86
|
{ priority: 1, timeout: 5000 }
|
|
84
87
|
);
|
|
88
|
+
|
|
89
|
+
// Coalescing example - multiple similar tasks become one
|
|
90
|
+
const results = await Promise.all([
|
|
91
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" }),
|
|
92
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" }),
|
|
93
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui.update" })
|
|
94
|
+
]);
|
|
95
|
+
// Only one updateUI() call executes, all three promises resolve with the same result
|
|
85
96
|
```
|
|
86
97
|
|
|
87
98
|
## 🔄 Promise API
|
|
@@ -143,6 +154,9 @@ const queue = new HoldMyTask(options?)
|
|
|
143
154
|
- `defaultPriority` (number, default: 0) - Default task priority
|
|
144
155
|
- `maxQueue` (number, default: Infinity) - Maximum queued tasks
|
|
145
156
|
- `delays` (object, default: {}) - Priority-to-delay mapping for completion delays
|
|
157
|
+
- `coalescingWindowDuration` (number, default: 200) - Time window in milliseconds for grouping coalescing tasks
|
|
158
|
+
- `coalescingMaxDelay` (number, default: 1000) - Maximum delay in milliseconds before forcing coalescing group execution
|
|
159
|
+
- `coalescingResolveAllPromises` (boolean, default: true) - Whether all promises in a coalescing group resolve with the result
|
|
146
160
|
- `onError` (function) - Global error handler
|
|
147
161
|
- `now` (function) - Injectable clock for testing
|
|
148
162
|
|
|
@@ -166,6 +180,9 @@ Adds a task to the queue.
|
|
|
166
180
|
- `timeout` (number) - Timeout in milliseconds
|
|
167
181
|
- `signal` (AbortSignal) - External abort signal
|
|
168
182
|
- `timestamp` (number) - Absolute execution timestamp
|
|
183
|
+
- `start` (number) - Milliseconds from now when the task should be ready to run (convenience for timestamp calculation)
|
|
184
|
+
- `coalescingKey` (string) - Tasks with the same coalescing key can be merged for efficiency
|
|
185
|
+
- `mustRunBy` (number) - Absolute timestamp by which the task must execute (overrides coalescing delays)
|
|
169
186
|
- `metadata` (any) - Custom metadata
|
|
170
187
|
|
|
171
188
|
**Returns:** TaskHandle object with:
|
|
@@ -383,13 +400,13 @@ const queue = new HoldMyTask({
|
|
|
383
400
|
// Timeline example:
|
|
384
401
|
// 10:00:00 - Task A (priority 1) completes → 1000ms delay starts
|
|
385
402
|
// 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 →
|
|
403
|
+
// 10:00:00.2 - Urgent task C enqueued with bypass → can start now (bypasses delay)
|
|
387
404
|
|
|
388
405
|
queue.enqueue(normalTaskB, callback, { priority: 1 }); // Waits for delay
|
|
389
406
|
|
|
390
407
|
queue.enqueue(urgentTaskC, callback, {
|
|
391
408
|
priority: 1,
|
|
392
|
-
bypassDelay: true // Skips the 1000ms delay,
|
|
409
|
+
bypassDelay: true // Skips the 1000ms delay, can start now
|
|
393
410
|
});
|
|
394
411
|
|
|
395
412
|
// Alternative bypass syntax
|
|
@@ -410,7 +427,7 @@ const queue = new HoldMyTask({
|
|
|
410
427
|
// Multiple tasks with different bypass behavior
|
|
411
428
|
queue.enqueue(taskA, callback, { priority: 1 }); // Completes, starts 800ms delay
|
|
412
429
|
queue.enqueue(taskB, callback, { priority: 2 }); // Waits for 800ms delay
|
|
413
|
-
queue.enqueue(taskC, callback, { priority: 2, bypassDelay: true }); //
|
|
430
|
+
queue.enqueue(taskC, callback, { priority: 2, bypassDelay: true }); // Bypasses delay, can start now
|
|
414
431
|
queue.enqueue(taskD, callback, { priority: 1 }); // Waits for taskC's completion delay
|
|
415
432
|
|
|
416
433
|
// Execution order: taskA → taskC (bypass) → taskB → taskD
|
|
@@ -424,6 +441,423 @@ queue.enqueue(taskD, callback, { priority: 1 }); // Waits for taskC's completion
|
|
|
424
441
|
- ✅ **Concurrency aware** - works correctly with multiple concurrent execution slots
|
|
425
442
|
- ⚠️ **Use sparingly** - frequent bypassing defeats the purpose of delay-based rate limiting
|
|
426
443
|
|
|
444
|
+
## 🔄 Task Coalescing System
|
|
445
|
+
|
|
446
|
+
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.
|
|
447
|
+
|
|
448
|
+
### How Coalescing Works
|
|
449
|
+
|
|
450
|
+
When tasks with the same `coalescingKey` are enqueued within a time window, they get merged into groups:
|
|
451
|
+
|
|
452
|
+
1. **First task** creates a new coalescing group with a time window
|
|
453
|
+
2. **Subsequent tasks** with the same key join the existing group (if within the window)
|
|
454
|
+
3. **One representative task** executes for the entire group
|
|
455
|
+
4. **All promises** in the group resolve with the same result
|
|
456
|
+
|
|
457
|
+
⚠️ **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.
|
|
458
|
+
|
|
459
|
+
### 🎯 Correct Coalescing Pattern: Fire-and-Forget with Embedded Updates
|
|
460
|
+
|
|
461
|
+
The most reliable pattern for coalescing with state consistency is the **"fire-and-forget with embedded updates"** approach:
|
|
462
|
+
|
|
463
|
+
**❌ WRONG - Parallel Enqueueing:**
|
|
464
|
+
|
|
465
|
+
```javascript
|
|
466
|
+
// DON'T DO THIS - creates race conditions
|
|
467
|
+
function volumeUp() {
|
|
468
|
+
const volumePromise = queue.enqueue(changeVolume, { priority: 1 });
|
|
469
|
+
const updatePromise = queue.enqueue(updateUI, { coalescingKey: "ui" }); // May see stale state
|
|
470
|
+
return Promise.all([volumePromise, updatePromise]);
|
|
471
|
+
}
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
**✅ CORRECT - Embedded Update Pattern:**
|
|
475
|
+
|
|
476
|
+
```javascript
|
|
477
|
+
// DO THIS - guarantees state consistency
|
|
478
|
+
function volumeUp() {
|
|
479
|
+
return queue.enqueue(
|
|
480
|
+
async () => {
|
|
481
|
+
// 1. Perform the main operation
|
|
482
|
+
const result = await changeVolume();
|
|
483
|
+
|
|
484
|
+
// 2. AFTER main operation completes, enqueue the update FROM WITHIN
|
|
485
|
+
queue.enqueue(async () => updateUI(), { coalescingKey: "ui" }); // Always sees final state
|
|
486
|
+
|
|
487
|
+
return result; // Consumer gets immediate response
|
|
488
|
+
},
|
|
489
|
+
{ priority: 1 }
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
**Key Benefits:**
|
|
495
|
+
|
|
496
|
+
- ✅ **100% State Accuracy**: Updates only trigger after main operations complete
|
|
497
|
+
- ✅ **Fire-and-Forget**: Consumers get immediate responses, no waiting
|
|
498
|
+
- ✅ **Optimal Coalescing**: Multiple updates coalesce naturally when triggered close together
|
|
499
|
+
- ✅ **No Race Conditions**: Sequential execution guarantees consistent state
|
|
500
|
+
|
|
501
|
+
### Basic Coalescing Configuration
|
|
502
|
+
|
|
503
|
+
```javascript
|
|
504
|
+
const queue = new HoldMyTask({
|
|
505
|
+
concurrency: 1,
|
|
506
|
+
coalescingWindowDuration: 200, // 200ms window for grouping tasks
|
|
507
|
+
coalescingMaxDelay: 1000, // Maximum 1000ms delay before forcing execution
|
|
508
|
+
coalescingResolveAllPromises: true // All promises get the result (default: true)
|
|
509
|
+
});
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
### Simple Coalescing Example
|
|
513
|
+
|
|
514
|
+
```javascript
|
|
515
|
+
// Device volume control scenario
|
|
516
|
+
async function updateVolume(change) {
|
|
517
|
+
return queue.enqueue(
|
|
518
|
+
async () => {
|
|
519
|
+
// Realistic device operations take time
|
|
520
|
+
const currentVolume = await device.getVolume(); // ~50-200ms
|
|
521
|
+
const newVolume = Math.max(0, Math.min(100, currentVolume + change));
|
|
522
|
+
await device.setVolume(newVolume); // ~100-500ms
|
|
523
|
+
return newVolume;
|
|
524
|
+
},
|
|
525
|
+
{
|
|
526
|
+
coalescingKey: "volume.update", // Tasks with same key get grouped
|
|
527
|
+
priority: 1,
|
|
528
|
+
delay: 100 // 100ms delay after completion
|
|
529
|
+
}
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// User rapidly presses volume up 5 times within coalescing window
|
|
534
|
+
const results = await Promise.all([
|
|
535
|
+
updateVolume(1), // Creates new group
|
|
536
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
537
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
538
|
+
updateVolume(1), // Joins existing group (if within 200ms window)
|
|
539
|
+
updateVolume(1) // Joins existing group (if within 200ms window)
|
|
540
|
+
]);
|
|
541
|
+
|
|
542
|
+
// If all tasks coalesce: ONE device.setVolume() call with final state
|
|
543
|
+
// If timing spreads them: Multiple groups, each sees state at execution time
|
|
544
|
+
console.log(results); // Could be [55, 55, 55, 55, 55] or [51, 53, 55, 55, 55] depending on timing
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
### Advanced Coalescing with Fire-and-Forget Pattern
|
|
548
|
+
|
|
549
|
+
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:
|
|
550
|
+
|
|
551
|
+
```javascript
|
|
552
|
+
const queue = new HoldMyTask({
|
|
553
|
+
concurrency: 2, // Allow volume and update tasks to run concurrently
|
|
554
|
+
coalescingWindowDuration: 200,
|
|
555
|
+
coalescingMaxDelay: 1000
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
// Volume commands using fire-and-forget pattern
|
|
559
|
+
function volumeUp(amount = 1) {
|
|
560
|
+
const commandId = Date.now();
|
|
561
|
+
|
|
562
|
+
// Fire-and-forget: return promise but consumer doesn't await it
|
|
563
|
+
return queue.enqueue(
|
|
564
|
+
async () => {
|
|
565
|
+
console.log(`Executing volume command ${commandId}`);
|
|
566
|
+
// Realistic device operation takes time
|
|
567
|
+
const result = await device.increaseVolume(amount); // 200-1000ms
|
|
568
|
+
|
|
569
|
+
// AFTER volume completes, enqueue update task FROM WITHIN
|
|
570
|
+
console.log(`Volume complete, triggering UI update`);
|
|
571
|
+
queue.enqueue(
|
|
572
|
+
async () => {
|
|
573
|
+
console.log(`Updating UI for final volume`);
|
|
574
|
+
// UI operation sees accurate final state
|
|
575
|
+
const volume = await device.getVolume(); // ~50ms
|
|
576
|
+
updateVolumeDisplay(volume); // ~10-100ms
|
|
577
|
+
return volume;
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
coalescingKey: "volume.ui.update", // UI updates get coalesced
|
|
581
|
+
priority: 5, // Lower priority than volume commands
|
|
582
|
+
delay: 100 // Brief delay after UI updates
|
|
583
|
+
}
|
|
584
|
+
);
|
|
585
|
+
|
|
586
|
+
return result;
|
|
587
|
+
},
|
|
588
|
+
{
|
|
589
|
+
priority: 1, // High priority for user actions
|
|
590
|
+
delay: 100 // Brief delay after volume operations
|
|
591
|
+
}
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Consumer usage - fire and forget
|
|
596
|
+
volumeUp(1); // Optimistic: assume it will work, don't wait
|
|
597
|
+
volumeUp(1); // Multiple rapid calls
|
|
598
|
+
volumeUp(1); // Each triggers its own update after completing
|
|
599
|
+
volumeUp(1); // Updates get coalesced if close together
|
|
600
|
+
volumeUp(1); // Final state is always accurate
|
|
601
|
+
|
|
602
|
+
// Result: 5 volume commands execute sequentially
|
|
603
|
+
// Update commands coalesce (e.g., 5 → 3 actual updates)
|
|
604
|
+
// UI always shows accurate final state because updates only trigger after volume changes
|
|
605
|
+
// Consumer gets immediate response, no waiting for completion
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
### Multi-Group Coalescing
|
|
609
|
+
|
|
610
|
+
The same `coalescingKey` can have multiple active groups based on timing windows:
|
|
611
|
+
|
|
612
|
+
```javascript
|
|
613
|
+
// API batch processing
|
|
614
|
+
async function processDataBatch(data) {
|
|
615
|
+
return queue.enqueue(
|
|
616
|
+
async () => {
|
|
617
|
+
console.log(`Processing batch with ${data.length} items`);
|
|
618
|
+
return await api.processBatch(data);
|
|
619
|
+
},
|
|
620
|
+
{
|
|
621
|
+
coalescingKey: "api.batch.process",
|
|
622
|
+
priority: 2,
|
|
623
|
+
start: 100 // 100ms delay allows grouping
|
|
624
|
+
}
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// Timeline:
|
|
629
|
+
// 0ms: processDataBatch(data1) → creates Group A (window: 0-200ms)
|
|
630
|
+
// 50ms: processDataBatch(data2) → joins Group A
|
|
631
|
+
// 250ms: processDataBatch(data3) → creates Group B (window: 250-450ms)
|
|
632
|
+
// 300ms: processDataBatch(data4) → joins Group B
|
|
633
|
+
// 500ms: processDataBatch(data5) → creates Group C (window: 500-700ms)
|
|
634
|
+
|
|
635
|
+
// Result: 3 separate API calls, each processing coalesced batches
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
### Coalescing with Explicit Timestamps
|
|
639
|
+
|
|
640
|
+
For precise scheduling, use `timestamp` instead of `start`:
|
|
641
|
+
|
|
642
|
+
```javascript
|
|
643
|
+
const queue = new HoldMyTask({
|
|
644
|
+
coalescingWindowDuration: 300,
|
|
645
|
+
coalescingMaxDelay: 2000
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
// Schedule all updates for the same exact time
|
|
649
|
+
const scheduleTime = Date.now() + 1000; // 1 second from now
|
|
650
|
+
|
|
651
|
+
const promises = [];
|
|
652
|
+
for (let i = 0; i < 10; i++) {
|
|
653
|
+
promises.push(
|
|
654
|
+
queue.enqueue(
|
|
655
|
+
async () => {
|
|
656
|
+
console.log("Executing coalesced batch update");
|
|
657
|
+
return await performBatchUpdate();
|
|
658
|
+
},
|
|
659
|
+
{
|
|
660
|
+
coalescingKey: "batch.update",
|
|
661
|
+
timestamp: scheduleTime, // All scheduled for same time
|
|
662
|
+
priority: 3
|
|
663
|
+
}
|
|
664
|
+
)
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// All 10 tasks coalesce into 1 execution at exactly scheduleTime
|
|
669
|
+
const results = await Promise.all(promises);
|
|
670
|
+
console.log(`10 tasks became 1 execution, all got result:`, results[0]);
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
### Must-Run-By Deadlines
|
|
674
|
+
|
|
675
|
+
Control maximum delay with `mustRunBy` to ensure tasks don't wait too long:
|
|
676
|
+
|
|
677
|
+
```javascript
|
|
678
|
+
const queue = new HoldMyTask({
|
|
679
|
+
coalescingWindowDuration: 500, // Try to group for 500ms
|
|
680
|
+
coalescingMaxDelay: 2000 // But never wait more than 2 seconds
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
// Critical system updates
|
|
684
|
+
async function criticalSystemUpdate(updateData) {
|
|
685
|
+
return queue.enqueue(
|
|
686
|
+
async () => {
|
|
687
|
+
console.log("Executing critical system update");
|
|
688
|
+
return await applySystemUpdate(updateData);
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
coalescingKey: "system.critical.update",
|
|
692
|
+
priority: 1,
|
|
693
|
+
timestamp: Date.now() + 300, // Prefer 300ms delay
|
|
694
|
+
mustRunBy: Date.now() + 1500 // Must run within 1.5 seconds
|
|
695
|
+
}
|
|
696
|
+
);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// Even if coalescing window suggests waiting longer,
|
|
700
|
+
// the task will execute by the mustRunBy deadline
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### Promise Resolution Modes
|
|
704
|
+
|
|
705
|
+
Control how promises resolve within coalescing groups:
|
|
706
|
+
|
|
707
|
+
```javascript
|
|
708
|
+
const queue = new HoldMyTask({
|
|
709
|
+
coalescingResolveAllPromises: true, // Default: all promises get the result
|
|
710
|
+
coalescingWindowDuration: 200
|
|
711
|
+
});
|
|
712
|
+
|
|
713
|
+
// Mode 1: All promises resolve (default behavior)
|
|
714
|
+
const results1 = await Promise.all([
|
|
715
|
+
queue.enqueue(task, { coalescingKey: "test" }),
|
|
716
|
+
queue.enqueue(task, { coalescingKey: "test" }),
|
|
717
|
+
queue.enqueue(task, { coalescingKey: "test" })
|
|
718
|
+
]);
|
|
719
|
+
// All three promises resolve with the same result
|
|
720
|
+
|
|
721
|
+
// Mode 2: Only representative promise resolves
|
|
722
|
+
const queue2 = new HoldMyTask({
|
|
723
|
+
coalescingResolveAllPromises: false,
|
|
724
|
+
coalescingWindowDuration: 200
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
const [result1, result2, result3] = await Promise.all([
|
|
728
|
+
queue2.enqueue(task, { coalescingKey: "test" }), // Resolves with result
|
|
729
|
+
queue2.enqueue(task, { coalescingKey: "test" }), // Resolves with undefined
|
|
730
|
+
queue2.enqueue(task, { coalescingKey: "test" }) // Resolves with undefined
|
|
731
|
+
]);
|
|
732
|
+
// Only the first (representative) promise gets the actual result
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
### Real-World Coalescing Patterns
|
|
736
|
+
|
|
737
|
+
#### Device Control Pattern
|
|
738
|
+
|
|
739
|
+
```javascript
|
|
740
|
+
class VolumeController {
|
|
741
|
+
constructor() {
|
|
742
|
+
this.queue = new HoldMyTask({
|
|
743
|
+
concurrency: 2, // Allow volume and update tasks concurrently
|
|
744
|
+
coalescingWindowDuration: 200,
|
|
745
|
+
coalescingMaxDelay: 1000
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
volumeUp(amount = 1) {
|
|
750
|
+
// Fire-and-forget pattern: consumer gets immediate response
|
|
751
|
+
return this.queue.enqueue(
|
|
752
|
+
async () => {
|
|
753
|
+
// Realistic device operations take time
|
|
754
|
+
const currentVolume = await this.device.getVolume(); // ~50-200ms
|
|
755
|
+
const newVolume = Math.min(100, currentVolume + amount);
|
|
756
|
+
await this.device.setVolume(newVolume); // ~100-500ms
|
|
757
|
+
|
|
758
|
+
// AFTER volume change completes, enqueue UI update FROM WITHIN
|
|
759
|
+
this.queue.enqueue(
|
|
760
|
+
async () => {
|
|
761
|
+
const volume = await this.device.getVolume(); // ~50ms
|
|
762
|
+
this.ui.updateVolumeDisplay(volume); // ~10-100ms
|
|
763
|
+
return volume;
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
coalescingKey: "volume.ui.update", // Updates coalesce together
|
|
767
|
+
priority: 3, // Lower priority than volume changes
|
|
768
|
+
delay: 100 // Brief delay after UI updates
|
|
769
|
+
}
|
|
770
|
+
);
|
|
771
|
+
|
|
772
|
+
return newVolume;
|
|
773
|
+
},
|
|
774
|
+
{
|
|
775
|
+
priority: 1, // High priority for user actions
|
|
776
|
+
delay: 50 // Brief delay between volume operations
|
|
777
|
+
}
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
#### API Batch Processing Pattern
|
|
784
|
+
|
|
785
|
+
```javascript
|
|
786
|
+
class APIBatcher {
|
|
787
|
+
constructor() {
|
|
788
|
+
this.queue = new HoldMyTask({
|
|
789
|
+
concurrency: 2,
|
|
790
|
+
coalescingWindowDuration: 300,
|
|
791
|
+
coalescingMaxDelay: 1500
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
async submitData(data) {
|
|
796
|
+
return this.queue.enqueue(
|
|
797
|
+
async () => {
|
|
798
|
+
// All data submissions in the time window get batched
|
|
799
|
+
const batchData = this.collectBatchData(); // Implementation detail
|
|
800
|
+
const result = await this.api.submitBatch(batchData);
|
|
801
|
+
return result.find((item) => item.id === data.id);
|
|
802
|
+
},
|
|
803
|
+
{
|
|
804
|
+
coalescingKey: `batch.${data.category}`, // Batch by category
|
|
805
|
+
priority: 2,
|
|
806
|
+
metadata: { data, category: data.category }
|
|
807
|
+
}
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
```
|
|
812
|
+
|
|
813
|
+
### Coalescing Performance Benefits
|
|
814
|
+
|
|
815
|
+
Real-world performance improvements with the embedded update pattern:
|
|
816
|
+
|
|
817
|
+
```javascript
|
|
818
|
+
// Fire-and-forget pattern with embedded coalescing updates
|
|
819
|
+
const queue = new HoldMyTask({
|
|
820
|
+
concurrency: 2,
|
|
821
|
+
coalescingWindowDuration: 200,
|
|
822
|
+
coalescingMaxDelay: 1000
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
// Volume control example - realistic embedded pattern
|
|
826
|
+
function processVolumeCommands() {
|
|
827
|
+
// Consumer fires 100 rapid volume commands (fire-and-forget)
|
|
828
|
+
const promises = [];
|
|
829
|
+
for (let i = 0; i < 100; i++) {
|
|
830
|
+
promises.push(
|
|
831
|
+
queue.enqueue(
|
|
832
|
+
async () => {
|
|
833
|
+
// Main operation: change volume (200-500ms each)
|
|
834
|
+
const result = await device.changeVolume(1);
|
|
835
|
+
|
|
836
|
+
// Embedded update: triggered AFTER volume change (coalesces automatically)
|
|
837
|
+
queue.enqueue(
|
|
838
|
+
async () => updateVolumeDisplay(), // 50-100ms each
|
|
839
|
+
{ coalescingKey: "volume.display" }
|
|
840
|
+
);
|
|
841
|
+
|
|
842
|
+
return result; // Immediate response to consumer
|
|
843
|
+
},
|
|
844
|
+
{ priority: 1 }
|
|
845
|
+
)
|
|
846
|
+
);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// Consumer gets immediate responses, doesn't wait for display updates
|
|
850
|
+
return promises; // All resolve quickly with volume results
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Results with embedded coalescing:
|
|
854
|
+
// - 100 volume operations execute (necessary work)
|
|
855
|
+
// - ~5-15 display updates execute (95-85% coalescing efficiency)
|
|
856
|
+
// - 100% accuracy: displays always show final state
|
|
857
|
+
// - Fire-and-forget: consumers get immediate responses
|
|
858
|
+
// - Total time: ~25-30 seconds (vs 50+ seconds without coalescing)
|
|
859
|
+
```
|
|
860
|
+
|
|
427
861
|
### Timeouts
|
|
428
862
|
|
|
429
863
|
Tasks automatically timeout and either call the callback with an error or reject the promise:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/holdmytask",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "A tiny task queue that waits until your task is ready",
|
|
5
5
|
"main": "./index.cjs",
|
|
6
6
|
"module": "./index.mjs",
|
|
@@ -85,12 +85,12 @@
|
|
|
85
85
|
"@html-eslint/eslint-plugin": "^0.48.0",
|
|
86
86
|
"@html-eslint/parser": "^0.48.0",
|
|
87
87
|
"@types/node": "^20.0.0",
|
|
88
|
-
"@vitest/ui": "^
|
|
88
|
+
"@vitest/ui": "^4.0.8",
|
|
89
89
|
"eslint": "^9.39.1",
|
|
90
90
|
"globals": "^16.5.0",
|
|
91
91
|
"prettier": "^3.0.0",
|
|
92
92
|
"typescript": "^5.0.0",
|
|
93
|
-
"vitest": "^
|
|
93
|
+
"vitest": "^4.0.8"
|
|
94
94
|
},
|
|
95
95
|
"repository": {
|
|
96
96
|
"type": "git",
|