@cldmv/holdmytask 1.2.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 CHANGED
@@ -38,7 +38,14 @@ The library provides flexible import options for different use cases:
38
38
  ### Production (Default)
39
39
 
40
40
  ```javascript
41
+ // Named import
41
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";
42
49
  // Uses optimized distribution files
43
50
  ```
44
51
 
@@ -49,6 +56,27 @@ import { HoldMyTask } from "@cldmv/holdmytask/main";
49
56
  // Conditional: uses source files in development, dist files in production
50
57
  ```
51
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
+
52
80
  ### Direct Source Import (Development Only)
53
81
 
54
82
  ```javascript
@@ -137,6 +165,67 @@ queue.enqueue(task1, callback, options);
137
165
  const result = await queue.enqueue(task2, options);
138
166
  ```
139
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
+
140
229
  ## 📚 API Reference
141
230
 
142
231
  ### Constructor
@@ -145,6 +234,28 @@ const result = await queue.enqueue(task2, options);
145
234
  const queue = new HoldMyTask(options?)
146
235
  ```
147
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
+
148
259
  **Options:**
149
260
 
150
261
  - `concurrency` (number, default: 1) - Maximum concurrent tasks
@@ -152,11 +263,21 @@ const queue = new HoldMyTask(options?)
152
263
  - `tick` (number, default: 25) - Scheduler tick interval in milliseconds (used when smartScheduling is false)
153
264
  - `autoStart` (boolean, default: true) - Whether to start processing immediately
154
265
  - `defaultPriority` (number, default: 0) - Default task priority
155
- - `maxQueue` (number, default: Infinity) - Maximum queued tasks
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
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`
160
281
  - `onError` (function) - Global error handler
161
282
  - `now` (function) - Injectable clock for testing
162
283
 
@@ -197,14 +318,75 @@ Adds a task to the queue.
197
318
 
198
319
  When `callback` is omitted, returns a Promise that resolves with the task result or rejects with an error.
199
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
+
200
366
  #### Control Methods
201
367
 
202
368
  - `pause()` - Pause task execution
203
369
  - `resume()` - Resume task execution
204
370
  - `clear()` - Cancel all pending tasks
205
371
  - `size()` - Get total queued tasks
372
+ - `length()` - Alias for `size()` - get total queued tasks
206
373
  - `inflight()` - Get currently running tasks
207
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
208
390
 
209
391
  ### Events
210
392
 
@@ -224,6 +406,31 @@ queue.on("cancel", (task, reason) => {
224
406
  queue.on("drain", () => {
225
407
  /* all tasks completed */
226
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
227
434
  ```
228
435
 
229
436
  ## ⚙️ Concurrency & Delays Interaction
@@ -300,6 +507,33 @@ This architecture enables handling thousands of tasks with precise timing contro
300
507
 
301
508
  [![npm unpacked size](https://img.shields.io/npm/unpacked-size/%40cldmv%2Fholdmytask.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837)](https://www.npmjs.com/package/@cldmv/holdmytask) [![Repo size](https://img.shields.io/github/repo-size/CLDMV/holdmytask?style=for-the-badge&logo=github&logoColor=white&labelColor=181717)](https://github.com/CLDMV/holdmytask)
302
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
+
303
537
  ## 🎯 Advanced Features
304
538
 
305
539
  ### Priority System
@@ -322,6 +556,78 @@ await queue.enqueue(task2, { priority: 10 }); // Runs first
322
556
  await queue.enqueue(task3, { priority: 5 });
323
557
  ```
324
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
+
325
631
  ### Smart Scheduling
326
632
 
327
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.
@@ -1216,10 +1522,23 @@ npm run build
1216
1522
 
1217
1523
  ### Testing with Injectable Clock
1218
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
+
1219
1527
  ```javascript
1528
+ let mockTime = Date.now();
1220
1529
  const queue = new HoldMyTask({
1221
1530
  now: () => mockTime // Control time in tests
1222
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
1223
1542
  ```
1224
1543
 
1225
1544
  ## 📄 License