@cldmv/holdmytask 1.6.1 → 2.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.
@@ -0,0 +1,2911 @@
1
+ /**
2
+ * @Project: @cldmv/holdmytask
3
+ * @Filename: /src/hold-my-task.mjs
4
+ * @Date: 2025-11-08 17:43:19 -08:00 (1762652599)
5
+ * @Author: Nate Hyson <CLDMV>
6
+ * @Email: <Shinrai@users.noreply.github.com>
7
+ * -----
8
+ * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
+ * @Last modified time: 2025-11-10 22:14:06 -08:00 (1762841646)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ import { EventEmitter } from "events";
15
+ import { MinHeap } from "./utils.mjs";
16
+
17
+ /**
18
+ * A sophisticated task queue that manages task execution with priorities, delays, and concurrency control.
19
+ * Tasks can be scheduled with timestamps, priorities, and completion delays between tasks of the same priority.
20
+ * Supports both callback and promise-based APIs with comprehensive lifecycle management.
21
+ * @extends EventEmitter
22
+ */
23
+ export class HoldMyTask extends EventEmitter {
24
+ /**
25
+ * Creates a new HoldMyTask queue instance.
26
+ * @param {Object} [options={}] - Configuration options for the task queue
27
+ * @param {number} [options.concurrency=1] - Maximum number of tasks to run concurrently
28
+ * @param {number} [options.tick=25] - Scheduler tick interval in milliseconds
29
+ * @param {boolean} [options.autoStart=true] - Whether to automatically start the scheduler
30
+ * @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
31
+ * @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
32
+ * @param {Object} [options.delays={}] - DEPRECATED: Use priorities[priority].delay instead. Legacy priority-to-delay mapping (auto-converted to priorities)
33
+ * @param {boolean} [options.smartScheduling=true] - Use dynamic timeouts instead of constant polling for better performance
34
+ * @param {number} [options.tick=25] - Polling interval in milliseconds when smartScheduling is disabled
35
+ * @param {number} [options.healingInterval=5000] - Self-healing check interval in milliseconds (smart scheduling only)
36
+ * @param {Object} [options.priorities={}] - Priority-specific default configurations
37
+ * @param {number} [options.priorities[priority].concurrency] - Maximum concurrent tasks for this priority (defaults to global concurrency limit)
38
+ * @param {number} [options.priorities[priority].postDelay] - Delay after task completion before next task of same priority
39
+ * @param {number} [options.priorities[priority].startDelay] - Delay before task execution (pre-execution delay)
40
+ * @param {Object} [options.coalescing] - Enhanced coalescing configuration (preferred over flat options)
41
+ * @param {Object} [options.coalescing.defaults] - Default coalescing settings for all keys
42
+ * @param {number} [options.coalescing.defaults.windowDuration=200] - Default window duration in milliseconds
43
+ * @param {number} [options.coalescing.defaults.maxDelay=1000] - Default maximum delay in milliseconds
44
+ * @param {number} [options.coalescing.defaults.postDelay] - Default post-completion delay in milliseconds
45
+ * @param {number} [options.coalescing.defaults.startDelay] - Default pre-execution delay in milliseconds
46
+ * @param {number} [options.coalescing.defaults.delay] - DEPRECATED: Use postDelay instead
47
+ * @param {number} [options.coalescing.defaults.start] - DEPRECATED: Use startDelay instead
48
+ * @param {boolean} [options.coalescing.defaults.resolveAllPromises=true] - Default promise resolution behavior
49
+ * @param {boolean} [options.coalescing.defaults.multipleCallbacks=false] - Default callback execution behavior
50
+ * @param {Object} [options.coalescing.keys] - Per-coalescingKey configuration overrides (windowDuration, maxDelay, postDelay, startDelay, etc.)
51
+ * @param {number} [options.coalescingWindowDuration=200] - DEPRECATED: Use coalescing.defaults.windowDuration instead
52
+ * @param {number} [options.coalescingMaxDelay=1000] - DEPRECATED: Use coalescing.defaults.maxDelay instead
53
+ * @param {boolean} [options.coalescingMultipleCallbacks=false] - DEPRECATED: Use coalescing.defaults.multipleCallbacks instead
54
+ * @param {boolean} [options.coalescingResolveAllPromises=true] - DEPRECATED: Use coalescing.defaults.resolveAllPromises instead
55
+ * @example
56
+ * // Enhanced configuration with priority defaults and extended coalescing
57
+ * const queue = new HoldMyTask({
58
+ * concurrency: 8, // Global maximum: 8 total tasks across all priorities
59
+ * delays: { 0: 1000, 1: 500 },
60
+ * priorities: {
61
+ * 1: { concurrency: 1, postDelay: 100, startDelay: 0 }, // Critical: Only 1 at a time, 100ms post-delay
62
+ * 2: { concurrency: 3, postDelay: 200, startDelay: 50 }, // Important: Up to 3 at a time, 200ms post-delay
63
+ * 3: { concurrency: 5, postDelay: 0, startDelay: 100 } // Background: Up to 5 at a time, 100ms pre-delay
64
+ * },
65
+ * coalescing: {
66
+ * defaults: {
67
+ * windowDuration: 200,
68
+ * maxDelay: 1000,
69
+ * postDelay: 50,
70
+ * startDelay: 25,
71
+ * resolveAllPromises: true
72
+ * },
73
+ * keys: {
74
+ * 'ui.update': { windowDuration: 100, maxDelay: 500, postDelay: 25, startDelay: 0 },
75
+ * 'api.batch': { windowDuration: 1000, maxDelay: 5000, postDelay: 100, startDelay: 200 },
76
+ * 'device.control': { windowDuration: 50, maxDelay: 200, delay: 10, start: 5 }
77
+ * }
78
+ * }
79
+ * });
80
+ *
81
+ * @example
82
+ * // Backward compatible (deprecated but still supported)
83
+ * const legacyQueue = new HoldMyTask({
84
+ * coalescingWindowDuration: 1500,
85
+ * coalescingMaxDelay: 3000,
86
+ * coalescingResolveAllPromises: true
87
+ * });
88
+ */
89
+
90
+ /**
91
+ * Transforms delay properties for backwards compatibility.
92
+ * Converts 'start' -> 'startDelay' and 'delay' -> 'postDelay' while preserving new names.
93
+ * @param {Object} config - Configuration object that may contain old or new property names
94
+ * @param {HoldMyTask} [instance] - Optional instance to emit deprecation warnings on
95
+ * @returns {Object} Transformed configuration with new property names
96
+ * @private
97
+ * @internal
98
+ */
99
+ static _transformDelayProperties(config, instance = null) {
100
+ if (!config || typeof config !== "object") {
101
+ return config;
102
+ }
103
+
104
+ const transformed = { ...config };
105
+
106
+ // Transform old names to new names (backwards compatibility)
107
+ // New names take precedence if both are provided
108
+ if ("start" in config && !("startDelay" in config)) {
109
+ transformed.startDelay = config.start;
110
+ if (instance) {
111
+ setImmediate(() =>
112
+ instance.emit("warning", {
113
+ type: "deprecation",
114
+ message: "Property 'start' is deprecated. Use 'startDelay' instead.",
115
+ deprecated: "start",
116
+ replacement: "startDelay"
117
+ })
118
+ );
119
+ }
120
+ }
121
+ delete transformed.start; // Always remove old property
122
+
123
+ if ("delay" in config && !("postDelay" in config)) {
124
+ transformed.postDelay = config.delay;
125
+ if (instance) {
126
+ setImmediate(() =>
127
+ instance.emit("warning", {
128
+ type: "deprecation",
129
+ message: "Property 'delay' is deprecated. Use 'postDelay' instead.",
130
+ deprecated: "delay",
131
+ replacement: "postDelay"
132
+ })
133
+ );
134
+ }
135
+ }
136
+ delete transformed.delay; // Always remove old property
137
+
138
+ return transformed;
139
+ }
140
+
141
+ constructor(options = {}) {
142
+ super();
143
+
144
+ // Sync mode is default for backwards compatibility
145
+ const syncMode = options.sync !== false;
146
+
147
+ if (syncMode) {
148
+ // Synchronous initialization - backwards compatible
149
+ this._initializeSync(options);
150
+ } else {
151
+ // Asynchronous initialization - modern usage
152
+ return this._initializeAsync(options);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Synchronous initialization for backwards compatibility
158
+ * @private
159
+ * @param {Object} options - Configuration options
160
+ */
161
+ _initializeSync(options) {
162
+ this._syncMode = true;
163
+ this._initializeCommon(options);
164
+ }
165
+
166
+ /**
167
+ * Asynchronous initialization for modern usage
168
+ * @private
169
+ * @param {Object} options - Configuration options
170
+ * @returns {Promise<HoldMyTask>} Promise that resolves to this instance
171
+ */
172
+ async _initializeAsync(options) {
173
+ this._syncMode = false;
174
+
175
+ // Return promise for async initialization
176
+ return new Promise((resolve) => {
177
+ setImmediate(() => {
178
+ this._initializeCommon(options);
179
+ resolve(this);
180
+ });
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Common initialization logic used by both sync and async modes
186
+ * @private
187
+ * @param {Object} options - Configuration options
188
+ */
189
+ _initializeCommon(options) {
190
+ // Remove internal options before processing
191
+ const cleanOptions = { ...options };
192
+ delete cleanOptions.sync;
193
+ delete cleanOptions.async;
194
+
195
+ // Backward compatibility: support old flat coalescing options
196
+ const legacyCoalescingDefaults = {
197
+ windowDuration: cleanOptions.coalescingWindowDuration ?? 200,
198
+ maxDelay: cleanOptions.coalescingMaxDelay ?? 1000,
199
+ multipleCallbacks: cleanOptions.coalescingMultipleCallbacks ?? false,
200
+ resolveAllPromises: cleanOptions.coalescingResolveAllPromises ?? true
201
+ };
202
+
203
+ // Emit deprecation warnings for legacy coalescing options
204
+ const deprecatedCoalescingOptions = [
205
+ { old: "coalescingWindowDuration", new: "coalescing.defaults.windowDuration" },
206
+ { old: "coalescingMaxDelay", new: "coalescing.defaults.maxDelay" },
207
+ { old: "coalescingMultipleCallbacks", new: "coalescing.defaults.multipleCallbacks" },
208
+ { old: "coalescingResolveAllPromises", new: "coalescing.defaults.resolveAllPromises" }
209
+ ];
210
+
211
+ deprecatedCoalescingOptions.forEach(({ old, new: replacement }) => {
212
+ if (cleanOptions[old] !== undefined) {
213
+ setImmediate(() =>
214
+ this.emit("warning", {
215
+ type: "deprecation",
216
+ message: `Option '${old}' is deprecated. Use '${replacement}' instead.`,
217
+ deprecated: old,
218
+ replacement: replacement
219
+ })
220
+ );
221
+ }
222
+ });
223
+
224
+ // Enhanced coalescing configuration
225
+ const coalescingConfig = cleanOptions.coalescing || {};
226
+ const coalescingDefaults = HoldMyTask._transformDelayProperties(
227
+ {
228
+ ...legacyCoalescingDefaults,
229
+ ...coalescingConfig.defaults
230
+ },
231
+ this
232
+ );
233
+
234
+ // Transform coalescing keys configurations
235
+ const transformedCoalescingKeys = {};
236
+ if (coalescingConfig.keys && typeof coalescingConfig.keys === "object") {
237
+ for (const [key, config] of Object.entries(coalescingConfig.keys)) {
238
+ if (config != null) {
239
+ transformedCoalescingKeys[key] = HoldMyTask._transformDelayProperties(config, this);
240
+ }
241
+ }
242
+ }
243
+
244
+ // Transform legacy delays to new priorities format for backward compatibility
245
+ const transformedPriorities = {};
246
+
247
+ // First, transform any existing priority configurations to use new property names
248
+ if (cleanOptions.priorities && typeof cleanOptions.priorities === "object") {
249
+ for (const [priority, config] of Object.entries(cleanOptions.priorities)) {
250
+ const priorityNum = parseInt(priority);
251
+ if (!isNaN(priorityNum) && config != null) {
252
+ transformedPriorities[priorityNum] = HoldMyTask._transformDelayProperties(config, this);
253
+ }
254
+ }
255
+ }
256
+
257
+ // Then, handle legacy delays option (very old backwards compatibility)
258
+ if (cleanOptions.delays && typeof cleanOptions.delays === "object") {
259
+ // Emit deprecation warning for legacy delays option
260
+ setImmediate(() =>
261
+ this.emit("warning", {
262
+ type: "deprecation",
263
+ message:
264
+ "Option 'delays' is deprecated. Use 'priorities' instead with { [priority]: { postDelay: value, startDelay: 0 } } format.",
265
+ deprecated: "delays",
266
+ replacement: "priorities"
267
+ })
268
+ );
269
+
270
+ for (const [priority, delay] of Object.entries(cleanOptions.delays)) {
271
+ const priorityNum = parseInt(priority);
272
+ if (!isNaN(priorityNum) && delay != null) {
273
+ transformedPriorities[priorityNum] = {
274
+ postDelay: delay, // Use new property name
275
+ startDelay: 0, // Use new property name
276
+ ...(transformedPriorities[priorityNum] || {}) // Don't override explicit priority config
277
+ };
278
+ }
279
+ }
280
+ }
281
+
282
+ // Extract properties that have been transformed or handled specially
283
+ const remainingOptions = { ...cleanOptions };
284
+ delete remainingOptions.priorities;
285
+ delete remainingOptions.delays;
286
+ delete remainingOptions.coalescing;
287
+
288
+ // Handle special maxQueue values (-1 means unlimited)
289
+ let maxQueue = remainingOptions.maxQueue;
290
+ if (maxQueue === -1) {
291
+ maxQueue = Infinity;
292
+ }
293
+ delete remainingOptions.maxQueue;
294
+
295
+ this.options = {
296
+ concurrency: 1,
297
+ tick: 25,
298
+ autoStart: true,
299
+ defaultPriority: 0,
300
+ maxQueue: maxQueue !== undefined ? maxQueue : Infinity,
301
+ priorities: transformedPriorities, // Unified priority configuration system
302
+ smartScheduling: true, // Use smart timeouts instead of polling by default
303
+ healingInterval: 5000, // Self-healing check interval (smart scheduling only)
304
+
305
+ // Enhanced coalescing configuration
306
+ coalescing: {
307
+ defaults: coalescingDefaults,
308
+ keys: transformedCoalescingKeys
309
+ },
310
+
311
+ // Legacy coalescing options (kept for backward compatibility but deprecated)
312
+ coalescingWindowDuration: legacyCoalescingDefaults.windowDuration,
313
+ coalescingMaxDelay: legacyCoalescingDefaults.maxDelay,
314
+ coalescingMultipleCallbacks: legacyCoalescingDefaults.multipleCallbacks,
315
+ coalescingResolveAllPromises: legacyCoalescingDefaults.resolveAllPromises,
316
+
317
+ ...remainingOptions
318
+ };
319
+
320
+ // Initialize heaps
321
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
322
+ this.readyHeap = new MinHeap((a, b) => {
323
+ if (a.priority !== b.priority) return b.priority - a.priority; // Higher priority first
324
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt; // Earlier ready first
325
+ return a.enqueueSeq - b.enqueueSeq; // Earlier enqueue first
326
+ });
327
+
328
+ this.running = new Set();
329
+ this.runningByPriority = new Map(); // Track running tasks per priority for concurrency limits
330
+ this.tasks = new Map();
331
+ this.nextId = 1;
332
+ this.enqueueSeq = 1;
333
+ this.isActive = false;
334
+ this.destroyed = false;
335
+ this.lastCompletedPriority = null;
336
+ this.nextAvailableTime = 0; // For delays after task completion
337
+
338
+ // Smart scheduling state (used when smartScheduling is enabled)
339
+ this.schedulerTimeout = null;
340
+ this.healingInterval = null;
341
+ this.lastSchedulerRun = 0;
342
+
343
+ // Traditional polling state (used when smartScheduling is disabled)
344
+ this.intervalId = null;
345
+
346
+ // Coalescing system - separate from main queue
347
+ this.coalescingGroups = new Map(); // coalescingKey -> Array<CoalescingGroup>
348
+ this.coalescingRepresentatives = new Map(); // representativeTaskId -> { coalescingKey, groupId }
349
+ this.nextGroupId = 1;
350
+
351
+ if (this.options.autoStart) {
352
+ this.resume();
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Internal convenience method to create a new HoldMyTask instance with async initialization.
358
+ * This enables event listeners to be attached before validation errors can occur.
359
+ * @param {Object} [options={}] - Configuration options
360
+ * @returns {Promise<HoldMyTask>} Promise that resolves to the initialized instance
361
+ * @private
362
+ * @example
363
+ * // Internal usage - prefer new HoldMyTask({ sync: false }) for public API
364
+ * const queue = await HoldMyTask._create({ maxQueue: 100 });
365
+ */
366
+ static async _create(options = {}) {
367
+ // Create instance with async mode
368
+ return new HoldMyTask({ ...options, sync: false });
369
+ }
370
+
371
+ /**
372
+ * Adds a task to the queue for execution. Supports both callback and promise-based APIs.
373
+ * @param {Function} task - The task function to execute. Can be sync or async.
374
+ * @param {Function|Object} [optionsOrCallback] - Either a callback function or options object
375
+ * @param {Object} [options={}] - Additional options (if callback was provided as second parameter)
376
+ * @param {string|number} [options.id] - Custom task ID for identification and later reference (must be unique)
377
+ * @param {number} [options.priority] - Task priority (higher numbers run first)
378
+ * @param {number} [options.timestamp] - When the task should be ready to run (milliseconds since epoch)
379
+ * @param {number} [options.start] - Milliseconds from now when the task should be ready to run (convenience for timestamp calculation)
380
+ * @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
381
+ * @param {number} [options.timeout] - Task timeout in milliseconds (for execution time limit)
382
+ * @param {number} [options.expire] - Task expiration timestamp or milliseconds from now (for queue waiting time limit)
383
+ * @param {number} [options.delay] - DEPRECATED: Use postDelay instead. Delay after task completion before next task of same priority
384
+ * @param {boolean} [options.bypassDelay] - If true, skip any active delay period and start immediately
385
+ * @param {string} [options.coalescingKey] - Key for task coalescing - tasks with same key will be coalesced within windows
386
+ * @param {number} [options.coalescingWindowDuration] - Override coalescing window duration (task-level override of key-level and defaults)
387
+ * @param {number} [options.coalescingMaxDelay] - Override coalescing max delay (task-level override of key-level and defaults)
388
+ * @param {boolean} [options.coalescingMultipleCallbacks] - Override callback behavior (task-level override of key-level and defaults)
389
+ * @param {boolean} [options.coalescingResolveAllPromises] - Override promise resolution behavior (task-level override of key-level and defaults)
390
+ * @param {*} [options.metadata] - Arbitrary metadata to attach to the task
391
+ * @returns {Promise|Object} Promise (if no callback) or task control object with id, cancel, status methods
392
+ * @throws {Error} If queue is destroyed or full
393
+ * @example
394
+ * // Promise API
395
+ * const result = await queue.enqueue(async () => fetchData());
396
+ *
397
+ * // Callback API
398
+ * queue.enqueue(() => processData(), (err, result) => {
399
+ * if (err) console.error(err);
400
+ * else console.log(result);
401
+ * });
402
+ *
403
+ * // With options
404
+ * const task = queue.enqueue(myTask, { priority: 5, timeout: 30000, expire: 10000 });
405
+ *
406
+ * // Bypass current delay for urgent task
407
+ * const urgent = queue.enqueue(urgentTask, { priority: 10, bypassDelay: true });
408
+ *
409
+ * // Alternative: use delay: -1 to bypass
410
+ * const urgent2 = queue.enqueue(urgentTask, { priority: 10, delay: -1 });
411
+ *
412
+ * // Coalescing tasks - multiple device status checks become one
413
+ * queue.enqueue(checkDeviceStatus, callback1, { coalescingKey: "device-123", coalescingWindowDuration: 1000 });
414
+ * queue.enqueue(checkDeviceStatus, callback2, { coalescingKey: "device-123" }); // Gets coalesced with first
415
+ */
416
+ enqueue(task, optionsOrCallback, options = {}) {
417
+ if (this.destroyed) {
418
+ const error = new Error("Queue is destroyed");
419
+ setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
420
+ return Promise.reject(error);
421
+ }
422
+
423
+ if (this.tasks.size >= this.options.maxQueue) {
424
+ const error = new Error("Queue is full");
425
+ setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
426
+ return Promise.reject(error);
427
+ }
428
+
429
+ // Handle dual API: callback can be second or third parameter
430
+ let callback = null;
431
+ let finalOptions = options;
432
+
433
+ if (typeof optionsOrCallback === "function") {
434
+ callback = optionsOrCallback;
435
+ } else if (optionsOrCallback && typeof optionsOrCallback === "object") {
436
+ finalOptions = { ...optionsOrCallback, ...options };
437
+ }
438
+
439
+ // Generate ID - use custom ID if provided, otherwise auto-generate
440
+ const id = finalOptions.id ? String(finalOptions.id) : String(this.nextId++);
441
+
442
+ // Check if custom ID already exists
443
+ if (finalOptions.id && this.tasks.has(id)) {
444
+ const error = new Error(`Task with ID '${id}' already exists`);
445
+ setImmediate(() => this.emit("error", { error, task, options: finalOptions }));
446
+ return Promise.reject(error);
447
+ }
448
+ const now = this.now();
449
+
450
+ // Handle coalescing tasks separately
451
+ if (finalOptions.coalescingKey) {
452
+ return this._handleCoalescingTask(id, task, callback, finalOptions, now);
453
+ }
454
+
455
+ // Regular task handling - apply priority defaults for start delay
456
+ const priority = finalOptions.priority ?? this.options.defaultPriority;
457
+ const priorityConfig = this.getPriorityConfig(priority, finalOptions);
458
+ const effectiveStart = finalOptions.start ?? priorityConfig.startDelay ?? 0;
459
+ const readyAt = finalOptions.timestamp ?? (effectiveStart ? now + effectiveStart : now);
460
+
461
+ // Calculate expiration timestamp
462
+ let expireAt = null;
463
+ if (finalOptions.expire !== undefined) {
464
+ // If expire === -1, never expire (useful with coalescing)
465
+ if (finalOptions.expire === -1) {
466
+ expireAt = null;
467
+ } else if (finalOptions.expire > now) {
468
+ expireAt = finalOptions.expire;
469
+ } else {
470
+ expireAt = now + finalOptions.expire;
471
+ }
472
+ }
473
+
474
+ const item = {
475
+ id,
476
+ task,
477
+ callback,
478
+ priority,
479
+ readyAt,
480
+ expireAt,
481
+ enqueueSeq: this.enqueueSeq++,
482
+ status: "pending",
483
+ signal: finalOptions.signal,
484
+ timeout: finalOptions.timeout,
485
+ delay: finalOptions.delay, // completion delay
486
+ bypassDelay: finalOptions.bypassDelay || finalOptions.delay === -1, // bypass current delay period
487
+ metadata: finalOptions.metadata
488
+ };
489
+
490
+ this.tasks.set(id, item);
491
+ this.pendingHeap.push(item);
492
+
493
+ // Check if signal is already aborted
494
+ if (finalOptions.signal?.aborted) {
495
+ this.cancel(id, "Task was aborted");
496
+ } else if (finalOptions.signal) {
497
+ // For both callback and promise API, the queue handles signal abortion
498
+ finalOptions.signal.addEventListener("abort", () => {
499
+ this.cancel(id, "Task was aborted");
500
+ });
501
+ }
502
+
503
+ if (this.isActive) {
504
+ if (this.options.smartScheduling) {
505
+ this.scheduleSmartTimeout();
506
+ } else {
507
+ this._scheduleNextTick();
508
+ }
509
+ }
510
+ const tasks = this.tasks; // Capture reference
511
+ const taskHandle = {
512
+ id,
513
+ cancel: (reason) => this.cancel(id, reason),
514
+ status: () => tasks.get(id)?.status ?? "canceled",
515
+ get startedAt() {
516
+ return tasks.get(id)?.startedAt;
517
+ },
518
+ get finishedAt() {
519
+ return tasks.get(id)?.finishedAt;
520
+ },
521
+ get result() {
522
+ return tasks.get(id)?.result;
523
+ },
524
+ get error() {
525
+ return tasks.get(id)?.error;
526
+ },
527
+ get metadata() {
528
+ return tasks.get(id)?.metadata;
529
+ },
530
+ get coalescingInfo() {
531
+ return null; // Regular tasks don't have coalescing info
532
+ }
533
+ };
534
+
535
+ // Return Promise if no callback provided
536
+ if (!callback) {
537
+ const promise = new Promise((resolve, reject) => {
538
+ item.resolve = resolve;
539
+ item.reject = reject;
540
+ });
541
+
542
+ // Store promise reference on item so we can update properties when task completes
543
+ item.promise = promise;
544
+
545
+ // Attach task handle properties to the promise with cached fallback getters
546
+ Object.defineProperty(promise, "id", { value: id, enumerable: true });
547
+ Object.defineProperty(promise, "cancel", { value: (reason) => this.cancel(id, reason), enumerable: true });
548
+ Object.defineProperty(promise, "status", {
549
+ value: () => {
550
+ const currentItem = this.tasks.get(id);
551
+ return currentItem ? currentItem.status : (promise._status ?? "canceled");
552
+ },
553
+ enumerable: true
554
+ });
555
+ Object.defineProperty(promise, "startedAt", {
556
+ get: () => {
557
+ const currentItem = this.tasks.get(id);
558
+ return currentItem ? currentItem.startedAt : promise._startedAt;
559
+ },
560
+ enumerable: true
561
+ });
562
+ Object.defineProperty(promise, "finishedAt", {
563
+ get: () => {
564
+ const currentItem = this.tasks.get(id);
565
+ return currentItem ? currentItem.finishedAt : promise._finishedAt;
566
+ },
567
+ enumerable: true
568
+ });
569
+ Object.defineProperty(promise, "result", {
570
+ get: () => {
571
+ const currentItem = this.tasks.get(id);
572
+ return currentItem ? currentItem.result : promise._result;
573
+ },
574
+ enumerable: true
575
+ });
576
+ Object.defineProperty(promise, "error", {
577
+ get: () => {
578
+ const currentItem = this.tasks.get(id);
579
+ return currentItem ? currentItem.error : promise._error;
580
+ },
581
+ enumerable: true
582
+ });
583
+ Object.defineProperty(promise, "metadata", {
584
+ get: () => {
585
+ const currentItem = this.tasks.get(id);
586
+ return currentItem ? currentItem.metadata : undefined;
587
+ },
588
+ enumerable: true
589
+ });
590
+ Object.defineProperty(promise, "coalescingInfo", {
591
+ get: () => null, // Regular tasks don't have coalescing info
592
+ enumerable: true
593
+ });
594
+
595
+ return promise;
596
+ }
597
+
598
+ return taskHandle;
599
+ }
600
+
601
+ /**
602
+ * Handles tasks with coalescingKey through the coalescing system.
603
+ * @private
604
+ * @internal
605
+ * @param {string} id - Task ID
606
+ * @param {Function} task - Task function
607
+ * @param {Function|null} callback - Callback function (null for promise API)
608
+ * @param {Object} options - Task options
609
+ * @param {number} now - Current timestamp
610
+ * @returns {Promise|Object} Promise or task handle
611
+ */
612
+ _handleCoalescingTask(id, task, callback, options, now) {
613
+ const { coalescingKey } = options;
614
+
615
+ // Get effective coalescing configuration including new delay and start options
616
+ const coalescingConfig = this.getCoalescingConfig(coalescingKey, options);
617
+ const priority = options.priority ?? this.options.defaultPriority;
618
+ const priorityConfig = this.getPriorityConfig(priority, options);
619
+
620
+ // Apply configuration priority: task options > coalescing key config > priority defaults > coalescing defaults
621
+ const effectiveStart = options.start ?? coalescingConfig.startDelay ?? priorityConfig.startDelay ?? 0;
622
+
623
+ const readyAt = options.timestamp ?? (effectiveStart ? now + effectiveStart : now);
624
+ const windowEnd = now + coalescingConfig.windowDuration;
625
+ const mustRunBy = now + coalescingConfig.maxDelay;
626
+
627
+ // Apply effective delay configuration
628
+ const effectiveDelay = options.delay ?? coalescingConfig.postDelay ?? priorityConfig.postDelay;
629
+
630
+ // Create task item (not added to main queue directly)
631
+ const taskItem = {
632
+ id,
633
+ task,
634
+ callback,
635
+ priority,
636
+ readyAt,
637
+ status: "coalescing",
638
+ signal: options.signal,
639
+ timeout: options.timeout,
640
+ delay: effectiveDelay,
641
+ bypassDelay: options.bypassDelay || options.delay === -1,
642
+ metadata: options.metadata,
643
+ coalescingKey,
644
+ enqueueSeq: this.enqueueSeq++
645
+ };
646
+
647
+ // Handle signal abortion for coalescing tasks
648
+ if (options.signal?.aborted) {
649
+ taskItem.status = "canceled";
650
+ if (callback) {
651
+ try {
652
+ callback(new Error("Task was aborted"), null);
653
+ } catch (callbackError) {
654
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
655
+ }
656
+ }
657
+ return this._createTaskHandle(taskItem, callback);
658
+ }
659
+
660
+ // Add abort listener
661
+ options.signal?.addEventListener("abort", () => {
662
+ this._cancelCoalescingTask(id, coalescingKey, "Task was aborted");
663
+ });
664
+
665
+ // Find compatible coalescing group or create new one
666
+ const compatibleGroup = this._findCompatibleCoalescingGroup(coalescingKey, now);
667
+
668
+ if (compatibleGroup) {
669
+ // Add to existing group
670
+ this._addToCoalescingGroup(compatibleGroup, taskItem, windowEnd, mustRunBy);
671
+ } else {
672
+ // Create new coalescing group using coalescingConfig
673
+ this._createCoalescingGroup(
674
+ coalescingKey,
675
+ taskItem,
676
+ windowEnd,
677
+ mustRunBy,
678
+ coalescingConfig.multipleCallbacks,
679
+ coalescingConfig.resolveAllPromises
680
+ );
681
+ }
682
+
683
+ return this._createTaskHandle(taskItem, callback);
684
+ }
685
+
686
+ /**
687
+ * Finds a compatible coalescing group for a new task.
688
+ * @private
689
+ * @internal
690
+ * @param {string} coalescingKey - The coalescing key
691
+ * @param {number} now - Current timestamp
692
+ * @param {number} windowEnd - End of new task's coalescing window
693
+ * @param {number} mustRunBy - New task's mustRunBy deadline
694
+ * @returns {Object|null} Compatible coalescing group or null
695
+ */
696
+ _findCompatibleCoalescingGroup(coalescingKey, now) {
697
+ const groups = this.coalescingGroups.get(coalescingKey);
698
+ if (!groups) return null;
699
+
700
+ // Find a group that is within both coalescing window and mustRunBy deadline
701
+ for (const group of groups) {
702
+ if (now <= group.windowEnd && now <= group.mustRunBy) {
703
+ return group;
704
+ }
705
+ }
706
+
707
+ return null;
708
+ }
709
+
710
+ /**
711
+ * Creates a new coalescing group with a representative task in the main queue.
712
+ * @private
713
+ * @internal
714
+ * @param {string} coalescingKey - The coalescing key
715
+ * @param {Object} taskItem - The first task item for this group
716
+ * @param {number} windowEnd - End of coalescing window
717
+ * @param {number} mustRunBy - Latest execution deadline
718
+ * @param {boolean} multipleCallbacks - Whether to call multiple callbacks
719
+ * @param {boolean} resolveAllPromises - Whether to resolve all promises with same result
720
+ * @returns {Object} The created coalescing group
721
+ */
722
+ _createCoalescingGroup(coalescingKey, taskItem, windowEnd, mustRunBy, multipleCallbacks, resolveAllPromises) {
723
+ const representativeId = String(this.nextId++);
724
+ const groupId = String(this.nextGroupId++);
725
+
726
+ // Create representative task that will actually run
727
+ const representative = {
728
+ id: representativeId,
729
+ task: this._createCoalescingRepresentativeTask(coalescingKey, groupId),
730
+ callback: null, // Representative handles its own completion
731
+ priority: taskItem.priority,
732
+ readyAt: taskItem.readyAt,
733
+ expireAt: null, // Use mustRunBy logic instead
734
+ enqueueSeq: this.enqueueSeq++,
735
+ status: "pending",
736
+ signal: null, // Individual tasks handle their own signals
737
+ timeout: taskItem.timeout,
738
+ delay: taskItem.delay || 0,
739
+ bypassDelay: taskItem.bypassDelay || false,
740
+ metadata: { coalescingKey, groupId, representative: true },
741
+ isCoalescingRepresentative: true
742
+ };
743
+
744
+ // Create coalescing group
745
+ const group = {
746
+ coalescingKey,
747
+ groupId,
748
+ tasks: new Map([[taskItem.id, taskItem]]),
749
+ representativeId,
750
+ windowEnd,
751
+ mustRunBy,
752
+ multipleCallbacks,
753
+ resolveAllPromises,
754
+ latestTask: taskItem,
755
+ originalTask: taskItem.task // Store the actual task function
756
+ };
757
+
758
+ // Store group and representative mapping
759
+ if (!this.coalescingGroups.has(coalescingKey)) {
760
+ this.coalescingGroups.set(coalescingKey, []);
761
+ }
762
+ this.coalescingGroups.get(coalescingKey).push(group);
763
+ this.coalescingRepresentatives.set(representativeId, { coalescingKey, groupId });
764
+
765
+ // Add representative to main queue
766
+ this.tasks.set(representativeId, representative);
767
+ this.pendingHeap.push(representative);
768
+
769
+ if (this.isActive) {
770
+ if (this.options.smartScheduling) {
771
+ this.scheduleSmartTimeout();
772
+ } else {
773
+ this._scheduleNextTick();
774
+ }
775
+ }
776
+ return group;
777
+ }
778
+
779
+ /**
780
+ * Adds a task to an existing coalescing group, updating the representative if needed.
781
+ * @private
782
+ * @internal
783
+ * @param {Object} group - The existing coalescing group
784
+ * @param {Object} taskItem - The new task item to add
785
+ * @param {number} windowEnd - End of coalescing window
786
+ * @param {number} mustRunBy - Latest execution deadline
787
+ * @param {number} now - Current timestamp
788
+ * @returns {void}
789
+ */
790
+ _addToCoalescingGroup(group, taskItem, windowEnd, mustRunBy) {
791
+ // Add task to group
792
+ group.tasks.set(taskItem.id, taskItem);
793
+
794
+ // Update group timing - keep original window but preserve earliest mustRunBy
795
+ // NOTE: Don't extend windowEnd - coalescing window should be fixed from first task
796
+ group.mustRunBy = Math.min(group.mustRunBy, mustRunBy);
797
+
798
+ // Update latest task (this will be the task function that actually runs)
799
+ group.latestTask = taskItem;
800
+ group.originalTask = taskItem.task;
801
+
802
+ // Update representative task in queue if needed
803
+ const representative = this.tasks.get(group.representativeId);
804
+ if (representative) {
805
+ // Update timing - use latest task's timing
806
+ representative.readyAt = taskItem.readyAt;
807
+ representative.priority = taskItem.priority;
808
+ representative.timeout = taskItem.timeout;
809
+ representative.delay = taskItem.delay || representative.delay;
810
+ representative.bypassDelay = taskItem.bypassDelay || representative.bypassDelay;
811
+
812
+ // Rebuild heaps to reflect updated representative
813
+ this._rebuildHeaps();
814
+
815
+ if (this.isActive) {
816
+ if (this.options.smartScheduling) {
817
+ this.scheduleSmartTimeout();
818
+ } else {
819
+ this._scheduleNextTick();
820
+ }
821
+ }
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Creates the representative task function that manages coalesced task execution.
827
+ * @private
828
+ * @internal
829
+ * @param {string} coalescingKey - The coalescing key
830
+ * @param {string} groupId - The group ID
831
+ * @returns {Function} The representative task function
832
+ */
833
+ _createCoalescingRepresentativeTask(coalescingKey, groupId) {
834
+ return async (signal) => {
835
+ const groups = this.coalescingGroups.get(coalescingKey);
836
+ const group = groups?.find((g) => g.groupId === groupId);
837
+
838
+ if (!group) {
839
+ throw new Error(`Coalescing group ${coalescingKey}:${groupId} not found`);
840
+ }
841
+
842
+ try {
843
+ // Execute the actual task (using latest task's function)
844
+ const result = await group.originalTask(signal);
845
+
846
+ // Handle callbacks/promises
847
+ this._resolveCoalescingGroup(group, null, result);
848
+
849
+ return result;
850
+ } catch (error) {
851
+ // Handle errors for all tasks in group
852
+ this._resolveCoalescingGroup(group, error, null);
853
+ throw error;
854
+ } finally {
855
+ // Clean up coalescing group
856
+ this._cleanupCoalescingGroup(coalescingKey, groupId);
857
+ }
858
+ };
859
+ }
860
+
861
+ /**
862
+ * Resolves all callbacks/promises in a coalescing group.
863
+ * @private
864
+ * @internal
865
+ * @param {Object} group - The coalescing group
866
+ * @param {Error|null} error - Error if task failed
867
+ * @param {*} result - Result if task succeeded
868
+ * @returns {void}
869
+ */
870
+ _resolveCoalescingGroup(group, error, result) {
871
+ if (group.multipleCallbacks) {
872
+ // Multiple callback mode - resolve all non-canceled tasks
873
+ for (const taskItem of group.tasks.values()) {
874
+ if (taskItem.status === "canceled") continue;
875
+
876
+ taskItem.status = error ? "error" : "completed";
877
+ taskItem.finishedAt = this.now();
878
+
879
+ if (error) {
880
+ taskItem.error = error;
881
+ } else {
882
+ taskItem.result = result;
883
+ }
884
+
885
+ if (taskItem.callback) {
886
+ try {
887
+ if (error) {
888
+ taskItem.callback(error, null);
889
+ } else {
890
+ taskItem.callback(null, result);
891
+ }
892
+ } catch (callbackError) {
893
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
894
+ }
895
+ } else if (taskItem.resolve) {
896
+ if (error) {
897
+ taskItem.reject(error);
898
+ } else {
899
+ taskItem.resolve(result);
900
+ }
901
+ }
902
+ }
903
+
904
+ // Clean up canceled tasks that didn't get resolved
905
+ for (const taskItem of group.tasks.values()) {
906
+ if (taskItem.status === "canceled" && taskItem.reject) {
907
+ taskItem.reject(new Error("Task was canceled"));
908
+ }
909
+ }
910
+ } else {
911
+ // Single callback mode - resolve latest only or all based on resolveAllPromises option
912
+ for (const taskItem of group.tasks.values()) {
913
+ if (taskItem.status === "canceled") continue;
914
+
915
+ if (taskItem === group.latestTask) {
916
+ // Always resolve the latest task
917
+ taskItem.status = error ? "error" : "completed";
918
+ taskItem.finishedAt = this.now();
919
+
920
+ if (error) {
921
+ taskItem.error = error;
922
+ } else {
923
+ taskItem.result = result;
924
+ }
925
+
926
+ if (taskItem.callback) {
927
+ try {
928
+ if (error) {
929
+ taskItem.callback(error, null);
930
+ } else {
931
+ taskItem.callback(null, result);
932
+ }
933
+ } catch (callbackError) {
934
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
935
+ }
936
+ } else if (taskItem.resolve) {
937
+ if (error) {
938
+ taskItem.reject(error);
939
+ } else {
940
+ taskItem.resolve(result);
941
+ }
942
+ }
943
+ } else {
944
+ // Handle other tasks based on resolveAllPromises setting
945
+ if (group.resolveAllPromises) {
946
+ // Resolve with same result as latest task
947
+ taskItem.status = error ? "error" : "coalesced";
948
+ taskItem.finishedAt = this.now();
949
+
950
+ if (error) {
951
+ taskItem.error = error;
952
+ } else {
953
+ taskItem.result = result;
954
+ }
955
+
956
+ if (taskItem.callback) {
957
+ try {
958
+ if (error) {
959
+ taskItem.callback(error, null);
960
+ } else {
961
+ taskItem.callback(null, result);
962
+ }
963
+ } catch (callbackError) {
964
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
965
+ }
966
+ } else if (taskItem.resolve) {
967
+ if (error) {
968
+ taskItem.reject(error);
969
+ } else {
970
+ taskItem.resolve(result);
971
+ }
972
+ }
973
+ } else {
974
+ // Reject other tasks (original behavior)
975
+ taskItem.status = "coalesced";
976
+ taskItem.finishedAt = this.now();
977
+
978
+ if (taskItem.callback) {
979
+ try {
980
+ taskItem.callback(new Error("Task was coalesced with a newer task"), null);
981
+ } catch (callbackError) {
982
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
983
+ }
984
+ } else if (taskItem.reject) {
985
+ taskItem.reject(new Error("Task was coalesced with a newer task"));
986
+ }
987
+ }
988
+ }
989
+ }
990
+
991
+ // Clean up canceled tasks
992
+ for (const taskItem of group.tasks.values()) {
993
+ if (taskItem.status === "canceled" && taskItem.reject) {
994
+ taskItem.reject(new Error("Task was canceled"));
995
+ }
996
+ }
997
+ }
998
+ }
999
+
1000
+ /**
1001
+ * Cancels a specific task within a coalescing group.
1002
+ * @private
1003
+ * @internal
1004
+ * @param {string} taskId - ID of task to cancel
1005
+ * @param {string} coalescingKey - The coalescing key
1006
+ * @param {string} reason - Cancellation reason
1007
+ * @returns {void}
1008
+ */
1009
+ _cancelCoalescingTask(taskId, coalescingKey, reason) {
1010
+ const groups = this.coalescingGroups.get(coalescingKey) || [];
1011
+
1012
+ for (const group of groups) {
1013
+ const taskItem = group.tasks.get(taskId);
1014
+ if (!taskItem) continue;
1015
+
1016
+ taskItem.status = "canceled";
1017
+ taskItem.finishedAt = this.now();
1018
+
1019
+ // Handle callback/promise
1020
+ if (taskItem.callback) {
1021
+ try {
1022
+ taskItem.callback(new Error(reason), null);
1023
+ } catch (callbackError) {
1024
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
1025
+ }
1026
+ } else if (taskItem.reject) {
1027
+ taskItem.reject(new Error(reason));
1028
+ }
1029
+
1030
+ // Remove from group
1031
+ group.tasks.delete(taskId);
1032
+
1033
+ // If group is empty, clean up representative task
1034
+ if (group.tasks.size === 0) {
1035
+ const representative = this.tasks.get(group.representativeId);
1036
+ if (representative) {
1037
+ this.cancel(group.representativeId, "All coalesced tasks canceled");
1038
+ }
1039
+ this._cleanupCoalescingGroup(coalescingKey, group.groupId);
1040
+ } else {
1041
+ // Update latest task if needed
1042
+ const remainingTasks = Array.from(group.tasks.values());
1043
+ group.latestTask = remainingTasks[remainingTasks.length - 1];
1044
+ group.originalTask = group.latestTask.task;
1045
+ }
1046
+
1047
+ return; // Found and handled the task
1048
+ }
1049
+ }
1050
+
1051
+ /**
1052
+ * Cleans up a coalescing group after completion or cancellation.
1053
+ * @private
1054
+ * @internal
1055
+ * @param {string} coalescingKey - The coalescing key
1056
+ * @param {string} groupId - The group ID to clean up
1057
+ * @returns {void}
1058
+ */
1059
+ _cleanupCoalescingGroup(coalescingKey, groupId) {
1060
+ const groups = this.coalescingGroups.get(coalescingKey);
1061
+ if (!groups) return;
1062
+
1063
+ const groupIndex = groups.findIndex((g) => g.groupId === groupId);
1064
+ if (groupIndex >= 0) {
1065
+ const group = groups[groupIndex];
1066
+ groups.splice(groupIndex, 1);
1067
+
1068
+ // Remove representative mapping
1069
+ this.coalescingRepresentatives.delete(group.representativeId);
1070
+
1071
+ // If no more groups for this key, remove the key entirely
1072
+ if (groups.length === 0) {
1073
+ this.coalescingGroups.delete(coalescingKey);
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ /**
1079
+ * Rebuilds the heap structures to reflect updated priorities/timing.
1080
+ * @private
1081
+ * @internal
1082
+ * @returns {void}
1083
+ */
1084
+ _rebuildHeaps() {
1085
+ // Rebuild pending heap
1086
+ const pendingTasks = [...this.pendingHeap.heap];
1087
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
1088
+ for (const task of pendingTasks) {
1089
+ this.pendingHeap.push(task);
1090
+ }
1091
+
1092
+ // Rebuild ready heap
1093
+ const readyTasks = [...this.readyHeap.heap];
1094
+ this.readyHeap = new MinHeap((a, b) => {
1095
+ if (a.priority !== b.priority) return b.priority - a.priority;
1096
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt;
1097
+ return a.enqueueSeq - b.enqueueSeq;
1098
+ });
1099
+ for (const task of readyTasks) {
1100
+ this.readyHeap.push(task);
1101
+ }
1102
+ }
1103
+
1104
+ /**
1105
+ * Creates a task handle for both regular and coalescing tasks.
1106
+ * @private
1107
+ * @internal
1108
+ * @param {Object} item - The task item
1109
+ * @param {Function|null} callback - Callback function
1110
+ * @returns {Promise|Object} Promise or task control object
1111
+ */
1112
+ _createTaskHandle(item, callback) {
1113
+ const taskHandle = {
1114
+ id: item.id,
1115
+ cancel: (reason) => {
1116
+ if (item.coalescingKey) {
1117
+ this._cancelCoalescingTask(item.id, item.coalescingKey, reason || "Task canceled");
1118
+ } else {
1119
+ this.cancel(item.id, reason || "Task canceled");
1120
+ }
1121
+ },
1122
+ status: () => item.status,
1123
+ get startedAt() {
1124
+ return item.startedAt;
1125
+ },
1126
+ get finishedAt() {
1127
+ return item.finishedAt;
1128
+ },
1129
+ get result() {
1130
+ return item.result;
1131
+ },
1132
+ get error() {
1133
+ return item.error;
1134
+ },
1135
+ get metadata() {
1136
+ // For coalescing tasks, get metadata from coalescing group
1137
+ if (item.coalescingKey) {
1138
+ const groupInfo = this.findCoalescingGroupByTaskId(item.id);
1139
+ return groupInfo ? groupInfo.task.metadata : item.metadata;
1140
+ }
1141
+ return item.metadata;
1142
+ },
1143
+ get coalescingInfo() {
1144
+ if (!item.coalescingKey) {
1145
+ return null;
1146
+ }
1147
+ const groupInfo = this.findCoalescingGroupByTaskId(item.id);
1148
+ return groupInfo
1149
+ ? {
1150
+ coalescingKey: groupInfo.coalescingKey,
1151
+ groupId: groupInfo.groupId,
1152
+ representativeId: groupInfo.representativeId,
1153
+ taskCount: groupInfo.groupTasks.length,
1154
+ allTaskMetadata: groupInfo.groupTasks.map((t) => ({ id: t.id, metadata: t.metadata }))
1155
+ }
1156
+ : null;
1157
+ }
1158
+ };
1159
+
1160
+ // Return Promise if no callback provided
1161
+ if (!callback) {
1162
+ const promise = new Promise((resolve, reject) => {
1163
+ item.resolve = resolve;
1164
+ item.reject = reject;
1165
+ });
1166
+
1167
+ // Store promise reference on item so we can update properties when task completes
1168
+ item.promise = promise;
1169
+
1170
+ // Attach task handle properties to the promise
1171
+ Object.defineProperty(promise, "id", { value: item.id, enumerable: true });
1172
+ Object.defineProperty(promise, "cancel", { value: taskHandle.cancel, enumerable: true });
1173
+ Object.defineProperty(promise, "status", { value: taskHandle.status, enumerable: true });
1174
+ Object.defineProperty(promise, "startedAt", {
1175
+ get: () => (promise._startedAt !== undefined ? promise._startedAt : item.startedAt),
1176
+ enumerable: true
1177
+ });
1178
+ Object.defineProperty(promise, "finishedAt", {
1179
+ get: () => (promise._finishedAt !== undefined ? promise._finishedAt : item.finishedAt),
1180
+ enumerable: true
1181
+ });
1182
+ Object.defineProperty(promise, "result", {
1183
+ get: () => (promise._result !== undefined ? promise._result : item.result),
1184
+ enumerable: true
1185
+ });
1186
+ Object.defineProperty(promise, "error", {
1187
+ get: () => (promise._error !== undefined ? promise._error : item.error),
1188
+ enumerable: true
1189
+ });
1190
+ Object.defineProperty(promise, "metadata", {
1191
+ get: () => {
1192
+ // For coalescing tasks, get metadata from coalescing group
1193
+ if (item.coalescingKey) {
1194
+ const groupInfo = this.findCoalescingGroupByTaskId(item.id);
1195
+ return groupInfo ? groupInfo.task.metadata : item.metadata;
1196
+ }
1197
+ return item.metadata;
1198
+ },
1199
+ enumerable: true
1200
+ });
1201
+ Object.defineProperty(promise, "coalescingInfo", {
1202
+ get: () => {
1203
+ if (!item.coalescingKey) {
1204
+ return null;
1205
+ }
1206
+ const groupInfo = this.findCoalescingGroupByTaskId(item.id);
1207
+ return groupInfo
1208
+ ? {
1209
+ coalescingKey: groupInfo.coalescingKey,
1210
+ groupId: groupInfo.groupId,
1211
+ representativeId: groupInfo.representativeId,
1212
+ taskCount: groupInfo.groupTasks.length,
1213
+ allTaskMetadata: groupInfo.groupTasks.map((t) => ({ id: t.id, metadata: t.metadata }))
1214
+ }
1215
+ : null;
1216
+ },
1217
+ enumerable: true
1218
+ });
1219
+
1220
+ return promise;
1221
+ }
1222
+
1223
+ return taskHandle;
1224
+ }
1225
+
1226
+ /**
1227
+ * Cancels a pending task by ID.
1228
+ * @param {string} id - The task ID to cancel
1229
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
1230
+ * @returns {boolean} True if task was found and cancelled, false otherwise
1231
+ * @example
1232
+ * const task = queue.enqueue(() => longRunningTask());
1233
+ * const cancelled = queue.cancel(task.id, "User requested cancellation");
1234
+ */
1235
+ cancel(id, reason) {
1236
+ const item = this.tasks.get(id);
1237
+ if (!item || item.status !== "pending") return false;
1238
+
1239
+ item.status = "canceled";
1240
+ item.finishedAt = this.now();
1241
+ this.tasks.delete(id);
1242
+ this.emit("cancel", item, reason);
1243
+
1244
+ // Reject promise if no callback
1245
+ if (!item.callback && item.reject) {
1246
+ item.reject(new Error(reason || "Task canceled"));
1247
+ }
1248
+
1249
+ return true;
1250
+ }
1251
+
1252
+ /**
1253
+ * Alias for cancel() method for backward compatibility.
1254
+ * @param {string|number} id - The task ID to cancel
1255
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
1256
+ * @returns {boolean} True if task was found and cancelled, false otherwise
1257
+ */
1258
+ cancelTask(id, reason) {
1259
+ return this.cancel(id, reason);
1260
+ }
1261
+
1262
+ /**
1263
+ * Pauses the task queue, stopping execution of new tasks.
1264
+ * Currently running tasks will continue to completion.
1265
+ * @returns {void}
1266
+ * @example
1267
+ * queue.pause();
1268
+ * // Queue stops processing new tasks
1269
+ */
1270
+ pause() {
1271
+ this.isActive = false;
1272
+ if (this.options.smartScheduling) {
1273
+ this.clearSchedulerTimers();
1274
+ } else {
1275
+ this.clearTimers();
1276
+ }
1277
+ }
1278
+
1279
+ /**
1280
+ * Resumes the task queue after being paused.
1281
+ * @returns {void}
1282
+ * @example
1283
+ * queue.resume();
1284
+ * // Queue resumes processing tasks
1285
+ */
1286
+ resume() {
1287
+ if (this.destroyed) return;
1288
+ this.isActive = true;
1289
+
1290
+ if (this.options.smartScheduling) {
1291
+ // Start healing interval for smart scheduling
1292
+ this.startHealingInterval();
1293
+
1294
+ // If there are pending tasks, run scheduler immediately
1295
+ if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
1296
+ this.runScheduler();
1297
+ } else {
1298
+ this.scheduleSmartTimeout();
1299
+ }
1300
+ } else {
1301
+ // Traditional polling mode
1302
+ // If there are pending tasks, run scheduler immediately
1303
+ if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
1304
+ this.schedulerTick();
1305
+ }
1306
+ this._scheduleNextTick();
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * Clears all pending and ready tasks from the queue.
1312
+ * Currently running tasks will continue to completion.
1313
+ * @returns {void}
1314
+ * @example
1315
+ * queue.clear();
1316
+ * // All queued tasks are removed
1317
+ */
1318
+ clear() {
1319
+ // Cancel all pending tasks
1320
+ const pendingTasks = [];
1321
+ while (this.pendingHeap.size() > 0) {
1322
+ const item = this.pendingHeap.pop();
1323
+ if (item && item.status === "pending") {
1324
+ pendingTasks.push(item);
1325
+ }
1326
+ }
1327
+ for (const item of pendingTasks) {
1328
+ item.status = "canceled";
1329
+ this.emit("cancel", item);
1330
+ }
1331
+
1332
+ // Clear coalescing groups
1333
+ for (const [_, groups] of this.coalescingGroups) {
1334
+ for (const group of groups) {
1335
+ for (const taskItem of group.tasks.values()) {
1336
+ taskItem.status = "canceled";
1337
+ if (taskItem.callback) {
1338
+ try {
1339
+ taskItem.callback(new Error("Queue cleared"), null);
1340
+ } catch (callbackError) {
1341
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
1342
+ }
1343
+ } else if (taskItem.reject) {
1344
+ taskItem.reject(new Error("Queue cleared"));
1345
+ }
1346
+ }
1347
+ }
1348
+ }
1349
+
1350
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
1351
+ this.readyHeap = new MinHeap((a, b) => {
1352
+ if (a.priority !== b.priority) return b.priority - a.priority;
1353
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt;
1354
+ return a.enqueueSeq - b.enqueueSeq;
1355
+ });
1356
+ this.tasks.clear();
1357
+ this.coalescingGroups.clear();
1358
+ this.coalescingRepresentatives.clear();
1359
+
1360
+ // Reschedule since we may have no work
1361
+ if (this.isActive) {
1362
+ if (this.options.smartScheduling) {
1363
+ this.scheduleSmartTimeout();
1364
+ } else {
1365
+ // For traditional polling, no need to reschedule as interval will continue
1366
+ }
1367
+ }
1368
+ }
1369
+
1370
+ /**
1371
+ * Returns the number of tasks in the queue.
1372
+ * @returns {number} Number of tasks in the queue
1373
+ * @example
1374
+ * const totalTasks = queue.size(); // 5
1375
+ */
1376
+ size() {
1377
+ return this.tasks.size;
1378
+ }
1379
+
1380
+ /**
1381
+ * Returns the number of tasks in the queue (alias for size()).
1382
+ * @returns {number} Number of tasks in the queue
1383
+ * @example
1384
+ * const totalTasks = queue.length(); // 5
1385
+ */
1386
+ length() {
1387
+ return this.tasks.size;
1388
+ }
1389
+
1390
+ /**
1391
+ * Returns the number of currently running tasks.
1392
+ * @returns {number} Number of running tasks
1393
+ * @example
1394
+ * const runningTasks = queue.inflight(); // 2
1395
+ */
1396
+ inflight() {
1397
+ return this.running.size;
1398
+ }
1399
+
1400
+ /**
1401
+ * Gets information about a coalescing group by key and group ID.
1402
+ * @param {string} coalescingKey - The coalescing key
1403
+ * @param {string} [groupId] - Optional group ID. If omitted, returns all groups for the key
1404
+ * @returns {Object|Array|null} Group info object, array of groups, or null if not found
1405
+ * @example
1406
+ * // Get all groups for a coalescing key
1407
+ * const groups = queue.getCoalescingGroup('ui.update');
1408
+ *
1409
+ * // Get specific group by ID
1410
+ * const group = queue.getCoalescingGroup('ui.update', '1');
1411
+ * console.log(group.tasks.size); // Number of tasks in group
1412
+ *
1413
+ * // Access individual task metadata
1414
+ * for (const [taskId, task] of group.tasks) {
1415
+ * console.log(`Task ${taskId}:`, task.metadata);
1416
+ * }
1417
+ */
1418
+ getCoalescingGroup(coalescingKey, groupId = null) {
1419
+ const groups = this.coalescingGroups.get(coalescingKey);
1420
+ if (!groups || groups.length === 0) {
1421
+ return null;
1422
+ }
1423
+
1424
+ if (groupId === null) {
1425
+ // Return all groups for the key
1426
+ return groups.map((group) => ({
1427
+ coalescingKey: group.coalescingKey,
1428
+ groupId: group.groupId,
1429
+ representativeId: group.representativeId,
1430
+ windowEnd: group.windowEnd,
1431
+ mustRunBy: group.mustRunBy,
1432
+ taskCount: group.tasks.size,
1433
+ tasks: Array.from(group.tasks.entries()).map(([id, task]) => ({
1434
+ id,
1435
+ metadata: task.metadata,
1436
+ status: task.status,
1437
+ priority: task.priority,
1438
+ readyAt: task.readyAt,
1439
+ coalescingKey: task.coalescingKey
1440
+ }))
1441
+ }));
1442
+ }
1443
+
1444
+ // Find specific group by ID
1445
+ const group = groups.find((g) => g.groupId === groupId);
1446
+ if (!group) {
1447
+ return null;
1448
+ }
1449
+
1450
+ return {
1451
+ coalescingKey: group.coalescingKey,
1452
+ groupId: group.groupId,
1453
+ representativeId: group.representativeId,
1454
+ windowEnd: group.windowEnd,
1455
+ mustRunBy: group.mustRunBy,
1456
+ taskCount: group.tasks.size,
1457
+ tasks: Array.from(group.tasks.entries()).map(([id, task]) => ({
1458
+ id,
1459
+ metadata: task.metadata,
1460
+ status: task.status,
1461
+ priority: task.priority,
1462
+ readyAt: task.readyAt,
1463
+ coalescingKey: task.coalescingKey
1464
+ }))
1465
+ };
1466
+ }
1467
+
1468
+ /**
1469
+ * Gets metadata for all tasks in a coalescing group.
1470
+ * @param {string} coalescingKey - The coalescing key
1471
+ * @param {string} [groupId] - Optional group ID. If omitted, returns metadata from all groups for the key
1472
+ * @returns {Array} Array of metadata objects with task IDs
1473
+ * @example
1474
+ * // Get metadata from all groups for a key
1475
+ * const allMetadata = queue.getCoalescingGroupMetadata('ui.update');
1476
+ *
1477
+ * // Get metadata from specific group
1478
+ * const groupMetadata = queue.getCoalescingGroupMetadata('ui.update', '1');
1479
+ *
1480
+ * // Example output:
1481
+ * // [
1482
+ * // { taskId: '123', metadata: { userId: 100, action: 'save' } },
1483
+ * // { taskId: '124', metadata: { userId: 200, action: 'delete' } }
1484
+ * // ]
1485
+ */
1486
+ getCoalescingGroupMetadata(coalescingKey, groupId = null) {
1487
+ const groups = this.coalescingGroups.get(coalescingKey);
1488
+ if (!groups || groups.length === 0) {
1489
+ return [];
1490
+ }
1491
+
1492
+ const targetGroups = groupId ? groups.filter((g) => g.groupId === groupId) : groups;
1493
+ const metadata = [];
1494
+
1495
+ for (const group of targetGroups) {
1496
+ for (const [taskId, task] of group.tasks) {
1497
+ metadata.push({
1498
+ taskId,
1499
+ groupId: group.groupId,
1500
+ metadata: task.metadata
1501
+ });
1502
+ }
1503
+ }
1504
+
1505
+ return metadata;
1506
+ }
1507
+
1508
+ /**
1509
+ * Gets a summary of all active coalescing groups.
1510
+ * @returns {Object} Summary object with coalescing key stats
1511
+ * @example
1512
+ * const summary = queue.getCoalescingGroupsSummary();
1513
+ * console.log(summary);
1514
+ * // {
1515
+ * // 'ui.update': { groupCount: 2, totalTasks: 5 },
1516
+ * // 'api.batch': { groupCount: 1, totalTasks: 3 }
1517
+ * // }
1518
+ */
1519
+ getCoalescingGroupsSummary() {
1520
+ const summary = {};
1521
+
1522
+ for (const [coalescingKey, groups] of this.coalescingGroups) {
1523
+ const totalTasks = groups.reduce((sum, group) => sum + group.tasks.size, 0);
1524
+ summary[coalescingKey] = {
1525
+ groupCount: groups.length,
1526
+ totalTasks
1527
+ };
1528
+ }
1529
+
1530
+ return summary;
1531
+ }
1532
+
1533
+ /**
1534
+ * Finds the coalescing group that contains a specific task ID.
1535
+ * @param {string|number} taskId - The task ID to search for
1536
+ * @returns {Object|null} Group information including the task's metadata, or null if not found
1537
+ * @example
1538
+ * const groupInfo = queue.findCoalescingGroupByTaskId('123');
1539
+ * if (groupInfo) {
1540
+ * console.log('Task is in group:', groupInfo.groupId);
1541
+ * console.log('Task metadata:', groupInfo.task.metadata);
1542
+ * console.log('Other tasks in group:', groupInfo.groupTasks.length);
1543
+ * }
1544
+ */
1545
+ findCoalescingGroupByTaskId(taskId) {
1546
+ for (const [coalescingKey, groups] of this.coalescingGroups) {
1547
+ for (const group of groups) {
1548
+ const task = group.tasks.get(taskId);
1549
+ if (task) {
1550
+ return {
1551
+ coalescingKey,
1552
+ groupId: group.groupId,
1553
+ representativeId: group.representativeId,
1554
+ windowEnd: group.windowEnd,
1555
+ mustRunBy: group.mustRunBy,
1556
+ task: {
1557
+ id: taskId,
1558
+ metadata: task.metadata,
1559
+ status: task.status,
1560
+ priority: task.priority,
1561
+ readyAt: task.readyAt
1562
+ },
1563
+ groupTasks: Array.from(group.tasks.entries()).map(([id, t]) => ({
1564
+ id,
1565
+ metadata: t.metadata,
1566
+ status: t.status
1567
+ }))
1568
+ };
1569
+ }
1570
+ }
1571
+ }
1572
+ return null;
1573
+ }
1574
+
1575
+ /**
1576
+ * Destroys the queue, canceling all tasks and stopping the scheduler.
1577
+ * Once destroyed, the queue cannot be reused.
1578
+ * @returns {void}
1579
+ * @example
1580
+ * queue.destroy();
1581
+ * // Queue is permanently shut down
1582
+ */
1583
+ destroy() {
1584
+ this.destroyed = true;
1585
+ this.pause();
1586
+ this.clear();
1587
+ this.emit("drain");
1588
+ }
1589
+
1590
+ /**
1591
+ * Returns the current timestamp in milliseconds.
1592
+ * @returns {number} Current timestamp
1593
+ * @example
1594
+ * const timestamp = queue.now(); // 1699564800000
1595
+ */
1596
+ now() {
1597
+ return this.options.now?.() ?? Date.now();
1598
+ }
1599
+
1600
+ /**
1601
+ * Schedules the next scheduler tick based on when tasks become ready.
1602
+ * @returns {void}
1603
+ * @private
1604
+ * @internal
1605
+ */
1606
+ _scheduleNextTick() {
1607
+ if (!this.isActive || this.destroyed) return;
1608
+
1609
+ this.clearTimers();
1610
+
1611
+ const now = this.now();
1612
+ let nextTime = Infinity;
1613
+
1614
+ // Check pending heap for next ready time
1615
+ const nextPending = this.pendingHeap.peek();
1616
+ if (nextPending) {
1617
+ nextTime = nextPending.readyAt;
1618
+ }
1619
+
1620
+ // Check if we have a delay until next tasks can start
1621
+ if (this.nextAvailableTime > now) {
1622
+ nextTime = Math.min(nextTime, this.nextAvailableTime);
1623
+ }
1624
+
1625
+ // A task already sitting in the ready heap needs an imminent recheck if nothing
1626
+ // else would schedule one - otherwise nextTime falls through to Infinity and the
1627
+ // 24.8-day fallback below strands it. Only force this when nextTime would
1628
+ // otherwise stay Infinity (the stranded-task case); an active future delay
1629
+ // already set nextTime above and should keep its single efficient timeout
1630
+ // rather than degrade into a tick-interval poll loop until it expires.
1631
+ if (nextTime === Infinity && this.readyHeap.size() > 0) {
1632
+ nextTime = now;
1633
+ }
1634
+
1635
+ // If next event is imminent or past, run immediately
1636
+ if (nextTime <= now + this.options.tick) {
1637
+ this.intervalId = setInterval(() => this.schedulerTick(), this.options.tick);
1638
+ } else {
1639
+ // Use timeout for distant events
1640
+ const delay = Math.min(nextTime - now, 2147483647); // Max 32-bit int
1641
+ this.timeoutId = setTimeout(() => this.schedulerTick(), delay);
1642
+ }
1643
+ }
1644
+
1645
+ /**
1646
+ * Main scheduler tick that moves ready tasks and starts execution.
1647
+ * @returns {void}
1648
+ * @private
1649
+ */
1650
+ schedulerTick() {
1651
+ const now = this.now();
1652
+
1653
+ // Move ready tasks from pending to ready heap, checking for expiration
1654
+ let nextPending = this.pendingHeap.peek();
1655
+ while (nextPending && nextPending.readyAt <= now) {
1656
+ const task = this.pendingHeap.pop();
1657
+ if (task && task.status === "pending") {
1658
+ // Check if task has expired before making it ready
1659
+ if (task.expireAt && now >= task.expireAt) {
1660
+ this._expireTask(task);
1661
+ } else {
1662
+ task.status = "ready";
1663
+ this.readyHeap.push(task);
1664
+ }
1665
+ }
1666
+ nextPending = this.pendingHeap.peek();
1667
+ }
1668
+
1669
+ // Start tasks up to concurrency limits (both global and per-priority)
1670
+ let hasWaitingTasks = false;
1671
+ const currentTime = this.now();
1672
+ const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
1673
+ const delayActive = delay > 0 && currentTime < this.nextAvailableTime;
1674
+
1675
+ while (this.readyHeap.size() > 0) {
1676
+ const task = this.readyHeap.peek();
1677
+ if (!task) break;
1678
+
1679
+ // Check if task has expired before starting it
1680
+ if (task.expireAt && currentTime >= task.expireAt) {
1681
+ this.readyHeap.pop(); // Remove expired task from heap
1682
+ this._expireTask(task);
1683
+ continue; // Check next task
1684
+ }
1685
+
1686
+ // Check concurrency limits (both global and per-priority)
1687
+ const canStartConcurrency = this._canStartTask(task);
1688
+ const canStartDelay = task.bypassDelay || !delayActive;
1689
+ const canStart = canStartConcurrency && canStartDelay;
1690
+
1691
+ if (canStart) {
1692
+ this.readyHeap.pop(); // Remove it from heap
1693
+ this._startTask(task);
1694
+ } else if (!canStartConcurrency) {
1695
+ // Can't start due to concurrency limits - look for other priorities that can run
1696
+ const heapArray = this.readyHeap.heap.slice(); // Copy heap array
1697
+ let foundStartableTask = false;
1698
+
1699
+ for (let i = 0; i < heapArray.length; i++) {
1700
+ const candidateTask = heapArray[i];
1701
+
1702
+ // Check if candidate task has expired
1703
+ if (candidateTask.expireAt && currentTime >= candidateTask.expireAt) {
1704
+ // Remove expired task and continue searching
1705
+ const remainingTasks = heapArray.filter((t) => t.id !== candidateTask.id);
1706
+ this.readyHeap.heap = [];
1707
+ for (const t of remainingTasks) {
1708
+ this.readyHeap.push(t);
1709
+ }
1710
+ this._expireTask(candidateTask);
1711
+ // Update heapArray for next iteration
1712
+ heapArray.splice(i, 1);
1713
+ i--; // Adjust index since we removed an item
1714
+ continue;
1715
+ }
1716
+
1717
+ // Check if this task can start (considering both concurrency and delay limits)
1718
+ const candidateCanStartConcurrency = this._canStartTask(candidateTask);
1719
+ const candidateCanStartDelay = candidateTask.bypassDelay || !delayActive;
1720
+
1721
+ if (candidateCanStartConcurrency && candidateCanStartDelay) {
1722
+ foundStartableTask = true;
1723
+ // Remove the task from heap and start it
1724
+ const remainingTasks = heapArray.filter((t) => t.id !== candidateTask.id);
1725
+ this.readyHeap.heap = [];
1726
+ for (const t of remainingTasks) {
1727
+ this.readyHeap.push(t);
1728
+ }
1729
+ this._startTask(candidateTask);
1730
+ break;
1731
+ }
1732
+ }
1733
+
1734
+ if (!foundStartableTask) {
1735
+ // No tasks can start due to concurrency limits
1736
+ hasWaitingTasks = true;
1737
+ break;
1738
+ }
1739
+ } else {
1740
+ // Can't start due to delay - check if there are any bypass tasks in the heap
1741
+ const heapArray = this.readyHeap.heap.slice(); // Copy heap array
1742
+ let foundBypassTask = false;
1743
+
1744
+ for (let i = 0; i < heapArray.length; i++) {
1745
+ const bypassTask = heapArray[i];
1746
+
1747
+ // Check if bypass task has expired
1748
+ if (bypassTask.expireAt && currentTime >= bypassTask.expireAt) {
1749
+ // Remove expired task and continue searching
1750
+ const remainingTasks = heapArray.filter((t) => t.id !== bypassTask.id);
1751
+ this.readyHeap.heap = [];
1752
+ for (const t of remainingTasks) {
1753
+ this.readyHeap.push(t);
1754
+ }
1755
+ this._expireTask(bypassTask);
1756
+ // Update heapArray for next iteration
1757
+ heapArray.splice(i, 1);
1758
+ i--; // Adjust index since we removed an item
1759
+ continue;
1760
+ }
1761
+
1762
+ if (bypassTask.bypassDelay) {
1763
+ foundBypassTask = true;
1764
+ // Remove the bypass task from heap and start it
1765
+ // We need to rebuild the heap without this task
1766
+ const remainingTasks = heapArray.filter((t) => t.id !== bypassTask.id);
1767
+ this.readyHeap.heap = [];
1768
+ for (const t of remainingTasks) {
1769
+ this.readyHeap.push(t);
1770
+ }
1771
+ this._startTask(bypassTask);
1772
+ break;
1773
+ }
1774
+ }
1775
+
1776
+ if (!foundBypassTask) {
1777
+ // No bypass tasks available, mark that we have waiting tasks
1778
+ hasWaitingTasks = true;
1779
+ break;
1780
+ }
1781
+ }
1782
+ }
1783
+
1784
+ // Schedule next tick if there are pending tasks or tasks that might become available
1785
+ // Note: For smart scheduling, this is handled by runScheduler calling scheduleSmartTimeout
1786
+ if (!this.options.smartScheduling && (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0 || hasWaitingTasks)) {
1787
+ this._scheduleNextTick();
1788
+ }
1789
+ }
1790
+
1791
+ /**
1792
+ * Checks if a task can start based on both global and per-priority concurrency limits.
1793
+ * @param {Object} task - The task to check
1794
+ * @returns {boolean} True if the task can start, false if concurrency limits prevent it
1795
+ * @private
1796
+ */
1797
+ _canStartTask(task) {
1798
+ // Check global concurrency limit
1799
+ if (this.running.size >= this.options.concurrency) {
1800
+ return false;
1801
+ }
1802
+
1803
+ // Check per-priority concurrency limit if configured
1804
+ const priorityConfig = this.options.priorities[task.priority];
1805
+ if (priorityConfig && typeof priorityConfig.concurrency === "number") {
1806
+ const runningForPriority = this.runningByPriority.get(task.priority) || 0;
1807
+ if (runningForPriority >= priorityConfig.concurrency) {
1808
+ return false;
1809
+ }
1810
+ }
1811
+
1812
+ return true;
1813
+ }
1814
+
1815
+ /**
1816
+ * Handles an expired task by removing it and calling appropriate error handling.
1817
+ * @param {Object} item - The expired task item
1818
+ * @returns {void}
1819
+ * @private
1820
+ * @internal
1821
+ */
1822
+ _expireTask(item) {
1823
+ if (item.status === "expired" || item.status === "canceled" || item.status === "completed") {
1824
+ return; // Already handled
1825
+ }
1826
+
1827
+ item.status = "expired";
1828
+ this.tasks.delete(item.id);
1829
+ this.running.delete(item);
1830
+
1831
+ const error = new Error(`Task expired after waiting ${this.now() - (item.readyAt || this.now())}ms in queue`);
1832
+ error.type = "expire";
1833
+ error.taskId = item.id;
1834
+
1835
+ if (item.callback) {
1836
+ // Callback API - emit error event
1837
+ try {
1838
+ item.callback(error, null);
1839
+ } catch (err) {
1840
+ this.emit("error", { error: err, task: item });
1841
+ }
1842
+ // Emit error event for callback API
1843
+ this.emit("error", { error, task: item });
1844
+ } else if (item.reject) {
1845
+ // Promise API - just reject, don't emit error event (handled by promise)
1846
+ item.reject(error);
1847
+ }
1848
+ }
1849
+
1850
+ /**
1851
+ * Starts execution of a ready task.
1852
+ * @param {Object} item - The task item to execute
1853
+ * @returns {Promise<void>}
1854
+ * @private
1855
+ * @internal
1856
+ */
1857
+ async _startTask(item) {
1858
+ if (item.status !== "ready") return;
1859
+
1860
+ // For promise API, check if signal is already aborted
1861
+ if (!item.callback && item.signal?.aborted) {
1862
+ item.reject(new Error("Task was aborted"));
1863
+ return;
1864
+ }
1865
+
1866
+ item.status = "running";
1867
+ item.startedAt = this.now();
1868
+ this.running.add(item);
1869
+
1870
+ // Track per-priority running count
1871
+ const currentPriorityCount = this.runningByPriority.get(item.priority) || 0;
1872
+ this.runningByPriority.set(item.priority, currentPriorityCount + 1);
1873
+
1874
+ this.emit("start", item); // Create abort controller for timeout
1875
+ const abortController = new AbortController();
1876
+ let timeoutId;
1877
+
1878
+ try {
1879
+ // Set up timeout if specified
1880
+ let timeoutId;
1881
+ let timeoutPromise;
1882
+
1883
+ if (item.timeout) {
1884
+ timeoutPromise = new Promise((_, reject) => {
1885
+ timeoutId = setTimeout(() => {
1886
+ abortController.abort();
1887
+ reject(new Error(`Task timed out after ${item.timeout}ms`));
1888
+ }, item.timeout);
1889
+ });
1890
+ }
1891
+
1892
+ // Run the task
1893
+ const taskPromise = item.task(abortController.signal);
1894
+ const result = item.timeout ? await Promise.race([taskPromise, timeoutPromise]) : await taskPromise;
1895
+ item.result = result;
1896
+ item.status = "completed";
1897
+ item.finishedAt = this.now();
1898
+
1899
+ // Clear timeout if it was set
1900
+ if (timeoutId) {
1901
+ clearTimeout(timeoutId);
1902
+ }
1903
+
1904
+ this.emit("success", item);
1905
+
1906
+ // Store final values on promise handle before resolving (for promise API)
1907
+ if (item.promise) {
1908
+ // Store final values so getters can access them after task deletion
1909
+ item.promise._result = item.result;
1910
+ item.promise._error = item.error;
1911
+ item.promise._startedAt = item.startedAt;
1912
+ item.promise._finishedAt = item.finishedAt;
1913
+ item.promise._status = item.status;
1914
+ }
1915
+
1916
+ // Call completion callback or resolve promise
1917
+ if (item.callback) {
1918
+ try {
1919
+ item.callback(null, result);
1920
+ } catch (callbackError) {
1921
+ // Callback threw an error, but task succeeded
1922
+ this.emit("error", { ...item, error: callbackError, callbackError: true });
1923
+ }
1924
+ } else if (item.resolve) {
1925
+ item.resolve(result);
1926
+ }
1927
+ } catch (error) {
1928
+ item.error = error;
1929
+ item.status = error.message.includes("timed out")
1930
+ ? "timeout"
1931
+ : abortController.signal.aborted || error.name === "AbortError"
1932
+ ? "canceled"
1933
+ : "error";
1934
+ item.finishedAt = this.now();
1935
+
1936
+ // Emit error event only for callback API (promise API conveys error via rejection)
1937
+ if (item.callback) {
1938
+ this.emit("error", item);
1939
+ }
1940
+
1941
+ // Store final values on promise handle before rejecting (for promise API)
1942
+ if (item.promise) {
1943
+ // Store final values so getters can access them after task deletion
1944
+ item.promise._result = item.result;
1945
+ item.promise._error = item.error;
1946
+ item.promise._startedAt = item.startedAt;
1947
+ item.promise._finishedAt = item.finishedAt;
1948
+ item.promise._status = item.status;
1949
+ }
1950
+
1951
+ // Call completion callback or reject promise
1952
+ if (item.callback) {
1953
+ try {
1954
+ const errorPayload =
1955
+ item.status === "timeout"
1956
+ ? { type: "timeout", message: error.message }
1957
+ : abortController.signal.aborted || error.name === "AbortError"
1958
+ ? { type: "canceled", message: "Task was aborted" }
1959
+ : { type: "error", error };
1960
+ item.callback(errorPayload, null);
1961
+ } catch (callbackError) {
1962
+ // Callback threw an error
1963
+ this.emit("error", { ...item, error: callbackError, callbackError: true });
1964
+ }
1965
+ } else if (item.reject) {
1966
+ item.reject(error);
1967
+ }
1968
+ } finally {
1969
+ // Clear timeout
1970
+ if (timeoutId) {
1971
+ clearTimeout(timeoutId);
1972
+ }
1973
+
1974
+ this.running.delete(item);
1975
+
1976
+ // Update per-priority running count
1977
+ const currentPriorityCount = this.runningByPriority.get(item.priority) || 0;
1978
+ if (currentPriorityCount > 0) {
1979
+ this.runningByPriority.set(item.priority, currentPriorityCount - 1);
1980
+ }
1981
+
1982
+ // Clean up all finished tasks (completed, failed, canceled)
1983
+ this.tasks.delete(item.id); // Update delay tracking after task completion
1984
+ const completedPriority = item.priority;
1985
+ const taskDelay = item.delay;
1986
+ const priorityDelay = this.options.priorities[completedPriority]?.postDelay ?? 0;
1987
+ const delay = taskDelay !== undefined ? taskDelay : priorityDelay;
1988
+ if (delay > 0) {
1989
+ this.lastCompletedPriority = completedPriority;
1990
+ this.nextAvailableTime = this.now() + delay;
1991
+ } else {
1992
+ this.lastCompletedPriority = null;
1993
+ this.nextAvailableTime = 0;
1994
+ }
1995
+
1996
+ // Check for drain after a microtask tick to ensure event handlers complete
1997
+ setImmediate(() => {
1998
+ if (this.running.size === 0 && this.pendingHeap.size() === 0 && this.readyHeap.size() === 0) {
1999
+ this.emit("drain");
2000
+ } else if (this.isActive) {
2001
+ // More tasks to run, reschedule immediately
2002
+ if (this.options.smartScheduling) {
2003
+ this.scheduleSmartTimeout();
2004
+ } else {
2005
+ this.schedulerTick();
2006
+ }
2007
+ }
2008
+ });
2009
+ }
2010
+ }
2011
+
2012
+ /**
2013
+ * Clears all active timers (intervals and timeouts).
2014
+ * @returns {void}
2015
+ * @private
2016
+ */
2017
+ clearTimers() {
2018
+ if (this.intervalId) {
2019
+ clearInterval(this.intervalId);
2020
+ this.intervalId = undefined;
2021
+ }
2022
+ if (this.timeoutId) {
2023
+ clearTimeout(this.timeoutId);
2024
+ this.timeoutId = undefined;
2025
+ }
2026
+ }
2027
+
2028
+ /**
2029
+ * Calculates when the next scheduler run should happen and sets appropriate timeout.
2030
+ * @private
2031
+ * @returns {void}
2032
+ *
2033
+ * @description
2034
+ * Smart scheduling that calculates the optimal time for the next scheduler run based on:
2035
+ * - When the next pending task becomes ready
2036
+ * - When delay periods end
2037
+ * - Whether there are tasks that can run immediately
2038
+ *
2039
+ * Uses setTimeout for precise timing instead of constant polling intervals.
2040
+ */
2041
+ scheduleSmartTimeout() {
2042
+ if (!this.isActive || this.destroyed) return;
2043
+
2044
+ this.clearSchedulerTimers();
2045
+
2046
+ const now = this.now();
2047
+ let nextRunTime = Infinity;
2048
+ let shouldRunNow = false;
2049
+
2050
+ // Check if we have ready tasks that can run immediately
2051
+ if (this.readyHeap.size() > 0 && this.running.size < this.options.concurrency) {
2052
+ const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
2053
+ const delayActive = delay > 0 && now < this.nextAvailableTime;
2054
+
2055
+ if (!delayActive) {
2056
+ shouldRunNow = true;
2057
+ } else {
2058
+ // Check for bypass tasks
2059
+ const heapArray = this.readyHeap.heap.slice();
2060
+ for (const task of heapArray) {
2061
+ if (task.bypassDelay && (!task.expireAt || now < task.expireAt)) {
2062
+ shouldRunNow = true;
2063
+ break;
2064
+ }
2065
+ }
2066
+
2067
+ if (!shouldRunNow) {
2068
+ nextRunTime = Math.min(nextRunTime, this.nextAvailableTime);
2069
+ }
2070
+ }
2071
+ }
2072
+
2073
+ // Check when next pending task becomes ready
2074
+ const nextPending = this.pendingHeap.peek();
2075
+ if (nextPending) {
2076
+ nextRunTime = Math.min(nextRunTime, nextPending.readyAt);
2077
+ }
2078
+
2079
+ // If we should run now or very soon, do it immediately
2080
+ if (shouldRunNow || nextRunTime <= now + 1) {
2081
+ // Use setImmediate to allow abort signals to be processed
2082
+ setImmediate(() => this.runScheduler());
2083
+ return;
2084
+ }
2085
+
2086
+ // If we have a future time to schedule for
2087
+ if (nextRunTime < Infinity) {
2088
+ const delay = Math.min(nextRunTime - now, 2147483647); // Max 32-bit int for setTimeout
2089
+ this.schedulerTimeout = setTimeout(() => {
2090
+ this.runScheduler();
2091
+ }, delay);
2092
+ }
2093
+ }
2094
+
2095
+ /**
2096
+ * Runs the main scheduler logic and reschedules if needed.
2097
+ * @private
2098
+ * @returns {void}
2099
+ *
2100
+ * @description
2101
+ * Executes the scheduler tick logic and then determines if more scheduling is needed.
2102
+ * Tracks when scheduler last ran for healing mechanism.
2103
+ */
2104
+ runScheduler() {
2105
+ if (!this.isActive || this.destroyed) return;
2106
+
2107
+ this.lastSchedulerRun = this.now();
2108
+ this.schedulerTick();
2109
+
2110
+ // Schedule next run if there's still work to do
2111
+ this.scheduleSmartTimeout();
2112
+ }
2113
+
2114
+ /**
2115
+ * Starts the self-healing interval that ensures scheduler continues working.
2116
+ * @private
2117
+ * @returns {void}
2118
+ *
2119
+ * @description
2120
+ * Healing mechanism that periodically checks if the scheduler should be running
2121
+ * but isn't due to timeout failures or other issues. Runs every healingInterval milliseconds.
2122
+ */
2123
+ startHealingInterval() {
2124
+ if (this.healingInterval) {
2125
+ clearInterval(this.healingInterval);
2126
+ }
2127
+
2128
+ this.healingInterval = setInterval(() => {
2129
+ if (!this.isActive || this.destroyed) return;
2130
+
2131
+ const now = this.now();
2132
+ const hasWork = this.pendingHeap.size() > 0 || this.readyHeap.size() > 0;
2133
+ const timeSinceLastRun = now - this.lastSchedulerRun;
2134
+ const shouldHaveRun = hasWork && timeSinceLastRun > this.options.healingInterval;
2135
+
2136
+ // If we should have run but haven't, and we don't have an active timeout, heal
2137
+ if (shouldHaveRun && !this.schedulerTimeout) {
2138
+ console.warn(`HoldMyTask: Healing scheduler - ${timeSinceLastRun}ms since last run`);
2139
+ this.runScheduler();
2140
+ }
2141
+ }, this.options.healingInterval);
2142
+ }
2143
+
2144
+ /**
2145
+ * Clears all scheduler-related timers.
2146
+ * @private
2147
+ * @returns {void}
2148
+ *
2149
+ * @description
2150
+ * Cleans up both the main scheduler timeout and the healing interval timer.
2151
+ */
2152
+ clearSchedulerTimers() {
2153
+ if (this.schedulerTimeout) {
2154
+ clearTimeout(this.schedulerTimeout);
2155
+ this.schedulerTimeout = null;
2156
+ }
2157
+ if (this.healingInterval) {
2158
+ clearInterval(this.healingInterval);
2159
+ this.healingInterval = null;
2160
+ }
2161
+ }
2162
+
2163
+ /**
2164
+ * Configure coalescing settings for specific keys dynamically.
2165
+ * @param {string} coalescingKey - The coalescing key to configure
2166
+ * @param {Object} config - Configuration for this key
2167
+ * @param {number} [config.windowDuration] - Window duration in milliseconds for this key
2168
+ * @param {number} [config.maxDelay] - Maximum delay in milliseconds for this key
2169
+ * @param {number} [config.postDelay] - Post-completion delay in milliseconds for this key
2170
+ * @param {number} [config.startDelay] - Pre-execution delay in milliseconds for this key
2171
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
2172
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
2173
+ * @param {boolean} [config.multipleCallbacks] - Whether to call multiple callbacks for this key
2174
+ * @param {boolean} [config.resolveAllPromises] - Whether to resolve all promises for this key
2175
+ * @returns {void}
2176
+ *
2177
+ * @example
2178
+ * // Configure specific keys after queue creation
2179
+ * queue.configureCoalescingKey('ui.update', {
2180
+ * windowDuration: 100,
2181
+ * maxDelay: 500,
2182
+ * postDelay: 25,
2183
+ * startDelay: 0
2184
+ * });
2185
+ *
2186
+ * queue.configureCoalescingKey('api.batch', {
2187
+ * windowDuration: 1000,
2188
+ * maxDelay: 5000,
2189
+ * postDelay: 100,
2190
+ * startDelay: 200,
2191
+ * resolveAllPromises: false
2192
+ * });
2193
+ */
2194
+ configureCoalescingKey(coalescingKey, config) {
2195
+ if (typeof coalescingKey !== "string") {
2196
+ const error = new Error("coalescingKey must be a string");
2197
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
2198
+ return;
2199
+ }
2200
+ if (typeof config !== "object" || config === null) {
2201
+ const error = new Error("config must be an object");
2202
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
2203
+ return;
2204
+ }
2205
+
2206
+ // Validate configuration options (accept both old and new property names)
2207
+ const validKeys = [
2208
+ "windowDuration",
2209
+ "maxDelay",
2210
+ "delay",
2211
+ "start",
2212
+ "postDelay",
2213
+ "startDelay",
2214
+ "multipleCallbacks",
2215
+ "resolveAllPromises"
2216
+ ];
2217
+ const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
2218
+ if (invalidKeys.length > 0) {
2219
+ const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
2220
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config, invalidKeys }));
2221
+ return;
2222
+ }
2223
+
2224
+ // Transform old property names to new ones for backwards compatibility
2225
+ const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
2226
+
2227
+ // Merge with existing configuration for this key
2228
+ this.options.coalescing.keys[coalescingKey] = {
2229
+ ...this.options.coalescing.keys[coalescingKey],
2230
+ ...transformedConfig
2231
+ };
2232
+ }
2233
+
2234
+ /**
2235
+ * Get the effective coalescing configuration for a specific key.
2236
+ * @param {string} coalescingKey - The coalescing key to get configuration for
2237
+ * @param {Object} [taskOptions={}] - Task-level options that may override key configuration
2238
+ * @returns {Object} The effective configuration for this key
2239
+ *
2240
+ * @example
2241
+ * // Get effective configuration for a key
2242
+ * const config = queue.getCoalescingConfig('ui.update');
2243
+ * console.log(`UI updates coalesce within ${config.windowDuration}ms with ${config.postDelay}ms post-completion delay`);
2244
+ *
2245
+ * // Check with task-level overrides
2246
+ * const effectiveConfig = queue.getCoalescingConfig('ui.update', {
2247
+ * coalescingWindowDuration: 50,
2248
+ * delay: 30 // Still accepts old property names for backwards compatibility
2249
+ * });
2250
+ */
2251
+ getCoalescingConfig(coalescingKey, taskOptions = {}) {
2252
+ const keyConfig = (this.options.coalescing.keys && this.options.coalescing.keys[coalescingKey]) || {};
2253
+ const defaults = this.options.coalescing.defaults;
2254
+ const priorityConfig = this.getPriorityConfig(taskOptions.priority ?? this.options.defaultPriority);
2255
+
2256
+ const postDelay = taskOptions.delay ?? keyConfig.postDelay ?? priorityConfig.postDelay ?? defaults.postDelay;
2257
+ const startDelay = taskOptions.start ?? keyConfig.startDelay ?? priorityConfig.startDelay ?? defaults.startDelay;
2258
+
2259
+ return {
2260
+ windowDuration: taskOptions.coalescingWindowDuration ?? keyConfig.windowDuration ?? defaults.windowDuration,
2261
+ maxDelay: taskOptions.coalescingMaxDelay ?? keyConfig.maxDelay ?? defaults.maxDelay,
2262
+ // New clear property names
2263
+ postDelay,
2264
+ startDelay,
2265
+ // Old property names for backwards compatibility
2266
+ delay: postDelay,
2267
+ start: startDelay,
2268
+ multipleCallbacks: taskOptions.coalescingMultipleCallbacks ?? keyConfig.multipleCallbacks ?? defaults.multipleCallbacks,
2269
+ resolveAllPromises: taskOptions.coalescingResolveAllPromises ?? keyConfig.resolveAllPromises ?? defaults.resolveAllPromises
2270
+ };
2271
+ }
2272
+
2273
+ /**
2274
+ * Get all configured coalescing keys and their configurations.
2275
+ * @returns {Object} Map of coalescingKey to configuration
2276
+ *
2277
+ * @example
2278
+ * // See all configured coalescing keys
2279
+ * const allConfigs = queue.getCoalescingConfigurations();
2280
+ * Object.entries(allConfigs).forEach(([key, config]) => {
2281
+ * console.log(`${key}: ${config.windowDuration}ms window, ${config.maxDelay}ms max delay, ${config.postDelay}ms post-completion delay, ${config.startDelay}ms pre-execution delay`);
2282
+ * });
2283
+ */
2284
+ getCoalescingConfigurations() {
2285
+ const result = {};
2286
+ for (const key of Object.keys(this.options.coalescing.keys)) {
2287
+ result[key] = this.getCoalescingConfig(key);
2288
+ }
2289
+ return result;
2290
+ }
2291
+
2292
+ /**
2293
+ * Configure default settings for specific priorities dynamically.
2294
+ * @param {number} priority - The priority level to configure
2295
+ * @param {Object} config - Configuration for this priority
2296
+ * @param {number} [config.postDelay] - Default post-completion delay in milliseconds for this priority
2297
+ * @param {number} [config.startDelay] - Default pre-execution delay in milliseconds for this priority
2298
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
2299
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
2300
+ * @returns {void}
2301
+ *
2302
+ * @example
2303
+ * // Configure priority defaults after queue creation
2304
+ * queue.configurePriority(1, {
2305
+ * postDelay: 100, // High priority tasks have 100ms delay after completion
2306
+ * startDelay: 0 // High priority tasks start immediately
2307
+ * });
2308
+ *
2309
+ * queue.configurePriority(3, {
2310
+ * postDelay: 0, // Low priority tasks have no delay after completion
2311
+ * startDelay: 200 // Low priority tasks wait 200ms before starting
2312
+ * });
2313
+ */
2314
+ configurePriority(priority, config) {
2315
+ if (typeof priority !== "number") {
2316
+ const error = new Error("priority must be a number");
2317
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
2318
+ return;
2319
+ }
2320
+ if (typeof config !== "object" || config === null) {
2321
+ const error = new Error("config must be an object");
2322
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
2323
+ return;
2324
+ }
2325
+
2326
+ // Validate configuration options (accept both old and new property names)
2327
+ const validKeys = ["delay", "start", "postDelay", "startDelay"];
2328
+ const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
2329
+ if (invalidKeys.length > 0) {
2330
+ const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
2331
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config, invalidKeys }));
2332
+ return;
2333
+ }
2334
+
2335
+ // Transform old property names to new ones for backwards compatibility
2336
+ const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
2337
+
2338
+ // Merge with existing configuration for this priority
2339
+ this.options.priorities[priority] = {
2340
+ ...this.options.priorities[priority],
2341
+ ...transformedConfig
2342
+ };
2343
+ }
2344
+
2345
+ /**
2346
+ * Get the effective configuration for a specific priority.
2347
+ * @param {number} priority - The priority level to get configuration for
2348
+ * @param {Object} [taskOptions={}] - Task-level options that may override priority configuration
2349
+ * @returns {Object} The effective configuration for this priority
2350
+ *
2351
+ * @example
2352
+ * // Get effective configuration for a priority
2353
+ * const config = queue.getPriorityConfig(1);
2354
+ * console.log(`Priority 1 tasks: ${config.delay}ms delay, ${config.start}ms start delay`);
2355
+ *
2356
+ * // Check with task-level overrides
2357
+ * const effectiveConfig = queue.getPriorityConfig(1, {
2358
+ * delay: 50,
2359
+ * start: 10
2360
+ * });
2361
+ */
2362
+ getPriorityConfig(priority, taskOptions = {}) {
2363
+ const priorityConfig = this.options.priorities[priority] || {};
2364
+
2365
+ const postDelay = taskOptions.delay ?? priorityConfig.postDelay;
2366
+ const startDelay = taskOptions.start ?? priorityConfig.startDelay;
2367
+
2368
+ return {
2369
+ // New clear property names
2370
+ postDelay,
2371
+ startDelay,
2372
+ // Old property names for backwards compatibility
2373
+ delay: postDelay,
2374
+ start: startDelay
2375
+ };
2376
+ }
2377
+
2378
+ /**
2379
+ * Get all configured priorities and their configurations.
2380
+ * @returns {Object} Map of priority to configuration
2381
+ *
2382
+ * @example
2383
+ * // See all configured priorities
2384
+ * const allConfigs = queue.getPriorityConfigurations();
2385
+ * Object.entries(allConfigs).forEach(([priority, config]) => {
2386
+ * console.log(`Priority ${priority}: ${config.delay}ms delay, ${config.start}ms start delay`);
2387
+ * });
2388
+ */
2389
+ getPriorityConfigurations() {
2390
+ const result = {};
2391
+ for (const priority of Object.keys(this.options.priorities)) {
2392
+ result[priority] = this.getPriorityConfig(parseInt(priority));
2393
+ }
2394
+ return result;
2395
+ }
2396
+
2397
+ /**
2398
+ * Alias for destroy() method for common queue system naming.
2399
+ * @returns {void}
2400
+ */
2401
+ shutdown() {
2402
+ return this.destroy();
2403
+ }
2404
+
2405
+ /**
2406
+ * Alias for enqueue() method for common queue system naming.
2407
+ * @param {Function} task - The task function to execute
2408
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
2409
+ * @param {Object} options - Task options (if callback provided as second parameter)
2410
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
2411
+ */
2412
+ schedule(task, optionsOrCallback, options = {}) {
2413
+ return this.enqueue(task, optionsOrCallback, options);
2414
+ }
2415
+
2416
+ /**
2417
+ * Alias for enqueue() method for common queue system naming.
2418
+ * @param {Function} task - The task function to execute
2419
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
2420
+ * @param {Object} options - Task options (if callback provided as second parameter)
2421
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
2422
+ */
2423
+ add(task, optionsOrCallback, options = {}) {
2424
+ return this.enqueue(task, optionsOrCallback, options);
2425
+ }
2426
+
2427
+ /**
2428
+ * Find a task by its ID.
2429
+ * @param {string|number} id - The task ID to find
2430
+ * @returns {Object|null} Task object if found, null otherwise
2431
+ */
2432
+ get(id) {
2433
+ return this.tasks.get(String(id)) || null;
2434
+ }
2435
+
2436
+ /**
2437
+ * Check if a task with the given ID exists.
2438
+ * @param {string|number} id - The task ID to check
2439
+ * @returns {boolean} True if task exists, false otherwise
2440
+ */
2441
+ has(id) {
2442
+ return this.tasks.has(String(id));
2443
+ }
2444
+
2445
+ /**
2446
+ * Alias for get() method for backward compatibility.
2447
+ * @param {string|number} id - The task ID to find
2448
+ * @returns {Object|null} Task object if found, null otherwise
2449
+ */
2450
+ getTask(id) {
2451
+ return this.get(id);
2452
+ }
2453
+
2454
+ /**
2455
+ * Alias for has() method for backward compatibility.
2456
+ * @param {string|number} id - The task ID to check
2457
+ * @returns {boolean} True if task exists, false otherwise
2458
+ */
2459
+ hasTask(id) {
2460
+ return this.has(id);
2461
+ }
2462
+
2463
+ // ========================================================================================
2464
+ // DEBUG AND INSPECTION METHODS
2465
+ // ========================================================================================
2466
+
2467
+ /**
2468
+ * Get detailed information about the current queue state for debugging.
2469
+ * @returns {Object} Comprehensive queue state information
2470
+ */
2471
+ inspect() {
2472
+ const now = this.now();
2473
+
2474
+ // Get all tasks from different queues
2475
+ const pendingTasks = [...this.pendingHeap.heap].map((task) => ({
2476
+ id: task.id,
2477
+ priority: task.priority,
2478
+ readyAt: task.readyAt,
2479
+ readyIn: task.readyAt - now,
2480
+ coalescingKey: task.coalescingKey,
2481
+ metadata: task.metadata,
2482
+ status: "pending"
2483
+ }));
2484
+
2485
+ const readyTasks = [...this.readyHeap.heap].map((task) => ({
2486
+ id: task.id,
2487
+ priority: task.priority,
2488
+ coalescingKey: task.coalescingKey,
2489
+ metadata: task.metadata,
2490
+ status: "ready"
2491
+ }));
2492
+
2493
+ const runningTasks = Array.from(this.running).map((task) => ({
2494
+ id: task.id,
2495
+ priority: task.priority,
2496
+ coalescingKey: task.coalescingKey,
2497
+ metadata: task.metadata,
2498
+ startedAt: task.startedAt,
2499
+ runningFor: now - task.startedAt,
2500
+ status: "running"
2501
+ }));
2502
+
2503
+ // Get timer information
2504
+ const timerInfo = this.inspectTimers();
2505
+
2506
+ // Get scheduler state
2507
+ const schedulerState = {
2508
+ isActive: this.isActive,
2509
+ isPaused: !this.isActive,
2510
+ smartScheduling: this.options.smartScheduling,
2511
+ concurrency: this.options.concurrency,
2512
+ currentConcurrency: this.running.size,
2513
+ tick: this.options.tick,
2514
+ nextActiveDelay: this.nextAvailableTime > now ? this.nextAvailableTime - now : null,
2515
+ priorityConcurrency: {}
2516
+ };
2517
+
2518
+ // Add per-priority concurrency information
2519
+ for (const [priority, count] of this.runningByPriority.entries()) {
2520
+ if (count > 0) {
2521
+ const priorityConfig = this.options.priorities[priority];
2522
+ schedulerState.priorityConcurrency[priority] = {
2523
+ running: count,
2524
+ limit: priorityConfig?.concurrency || this.options.concurrency,
2525
+ available: (priorityConfig?.concurrency || this.options.concurrency) - count
2526
+ };
2527
+ }
2528
+ }
2529
+
2530
+ // Also show configured priority limits even if nothing is running
2531
+ for (const [priority, config] of Object.entries(this.options.priorities)) {
2532
+ if (config.concurrency && !schedulerState.priorityConcurrency[priority]) {
2533
+ schedulerState.priorityConcurrency[priority] = {
2534
+ running: 0,
2535
+ limit: config.concurrency,
2536
+ available: config.concurrency
2537
+ };
2538
+ }
2539
+ }
2540
+
2541
+ // Get coalescing information
2542
+ const coalescingInfo = {};
2543
+ for (const [key, groups] of this.coalescingGroups.entries()) {
2544
+ coalescingInfo[key] = {
2545
+ groupCount: groups.size,
2546
+ totalTasks: Array.from(groups.values()).reduce((sum, group) => sum + group.tasks.size, 0),
2547
+ groups: Array.from(groups.entries()).map(([groupId, group]) => ({
2548
+ groupId,
2549
+ taskCount: group.tasks.size,
2550
+ representativeId: group.representativeId,
2551
+ tasks: Array.from(group.tasks.entries()).map(([_, task]) => ({
2552
+ id: task.id,
2553
+ metadata: task.metadata
2554
+ }))
2555
+ }))
2556
+ };
2557
+ }
2558
+
2559
+ return {
2560
+ timestamp: now,
2561
+ scheduler: schedulerState,
2562
+ timers: timerInfo,
2563
+ queues: {
2564
+ pending: {
2565
+ count: pendingTasks.length,
2566
+ tasks: pendingTasks
2567
+ },
2568
+ ready: {
2569
+ count: readyTasks.length,
2570
+ tasks: readyTasks
2571
+ },
2572
+ running: {
2573
+ count: runningTasks.length,
2574
+ tasks: runningTasks
2575
+ }
2576
+ },
2577
+ totals: {
2578
+ totalTasks: pendingTasks.length + readyTasks.length + runningTasks.length,
2579
+ pendingTasks: pendingTasks.length,
2580
+ readyTasks: readyTasks.length,
2581
+ runningTasks: runningTasks.length
2582
+ },
2583
+ coalescing: coalescingInfo,
2584
+ delays: {
2585
+ activeDelays: this.nextAvailableTime > now ? 1 : 0,
2586
+ delayDetails:
2587
+ this.nextAvailableTime > now
2588
+ ? [
2589
+ {
2590
+ priority: this.lastCompletedPriority,
2591
+ expiresAt: this.nextAvailableTime,
2592
+ expiresIn: this.nextAvailableTime - now
2593
+ }
2594
+ ]
2595
+ : []
2596
+ }
2597
+ };
2598
+ }
2599
+
2600
+ /**
2601
+ * Get information about active timers and scheduler state.
2602
+ * @returns {Object} Timer and scheduler information
2603
+ */
2604
+ inspectTimers() {
2605
+ const now = this.now();
2606
+
2607
+ return {
2608
+ schedulerInterval: {
2609
+ id: this.schedulerInterval,
2610
+ active: this.schedulerInterval !== null,
2611
+ type: "interval"
2612
+ },
2613
+ schedulerTimeout: {
2614
+ id: this.schedulerTimeout,
2615
+ active: this.schedulerTimeout !== null,
2616
+ type: "timeout"
2617
+ },
2618
+ nextScheduledRun: this.nextScheduledRun,
2619
+ nextRunIn: this.nextScheduledRun ? this.nextScheduledRun - now : null,
2620
+ smartScheduling: this.options.smartScheduling,
2621
+ tickInterval: this.options.tick
2622
+ };
2623
+ }
2624
+
2625
+ /**
2626
+ * Get a summary of all queued tasks by status.
2627
+ * @returns {Object} Task summary by status
2628
+ */
2629
+ inspectTasks() {
2630
+ const now = this.now();
2631
+
2632
+ const summary = {
2633
+ pending: [],
2634
+ ready: [],
2635
+ running: [],
2636
+ byPriority: {},
2637
+ byCoalescingKey: {},
2638
+ total: 0
2639
+ };
2640
+
2641
+ // Process pending tasks
2642
+ [...this.pendingHeap.heap].forEach((task) => {
2643
+ const taskInfo = {
2644
+ id: task.id,
2645
+ priority: task.priority,
2646
+ readyAt: task.readyAt,
2647
+ readyIn: task.readyAt - now,
2648
+ coalescingKey: task.coalescingKey,
2649
+ metadata: task.metadata
2650
+ };
2651
+ summary.pending.push(taskInfo);
2652
+ summary.total++;
2653
+
2654
+ // Group by priority
2655
+ if (!summary.byPriority[task.priority]) {
2656
+ summary.byPriority[task.priority] = { pending: 0, ready: 0, running: 0 };
2657
+ }
2658
+ summary.byPriority[task.priority].pending++;
2659
+
2660
+ // Group by coalescing key
2661
+ if (task.coalescingKey) {
2662
+ if (!summary.byCoalescingKey[task.coalescingKey]) {
2663
+ summary.byCoalescingKey[task.coalescingKey] = { pending: 0, ready: 0, running: 0 };
2664
+ }
2665
+ summary.byCoalescingKey[task.coalescingKey].pending++;
2666
+ }
2667
+ });
2668
+
2669
+ // Process ready tasks
2670
+ [...this.readyHeap.heap].forEach((task) => {
2671
+ const taskInfo = {
2672
+ id: task.id,
2673
+ priority: task.priority,
2674
+ coalescingKey: task.coalescingKey,
2675
+ metadata: task.metadata
2676
+ };
2677
+ summary.ready.push(taskInfo);
2678
+ summary.total++;
2679
+
2680
+ // Group by priority
2681
+ if (!summary.byPriority[task.priority]) {
2682
+ summary.byPriority[task.priority] = { pending: 0, ready: 0, running: 0 };
2683
+ }
2684
+ summary.byPriority[task.priority].ready++;
2685
+
2686
+ // Group by coalescing key
2687
+ if (task.coalescingKey) {
2688
+ if (!summary.byCoalescingKey[task.coalescingKey]) {
2689
+ summary.byCoalescingKey[task.coalescingKey] = { pending: 0, ready: 0, running: 0 };
2690
+ }
2691
+ summary.byCoalescingKey[task.coalescingKey].ready++;
2692
+ }
2693
+ });
2694
+
2695
+ // Process running tasks
2696
+ Array.from(this.running).forEach((task) => {
2697
+ const taskInfo = {
2698
+ id: task.id,
2699
+ priority: task.priority,
2700
+ coalescingKey: task.coalescingKey,
2701
+ metadata: task.metadata,
2702
+ startedAt: task.startedAt,
2703
+ runningFor: now - task.startedAt
2704
+ };
2705
+ summary.running.push(taskInfo);
2706
+ summary.total++;
2707
+
2708
+ // Group by priority
2709
+ if (!summary.byPriority[task.priority]) {
2710
+ summary.byPriority[task.priority] = { pending: 0, ready: 0, running: 0 };
2711
+ }
2712
+ summary.byPriority[task.priority].running++;
2713
+
2714
+ // Group by coalescing key
2715
+ if (task.coalescingKey) {
2716
+ if (!summary.byCoalescingKey[task.coalescingKey]) {
2717
+ summary.byCoalescingKey[task.coalescingKey] = { pending: 0, ready: 0, running: 0 };
2718
+ }
2719
+ summary.byCoalescingKey[task.coalescingKey].running++;
2720
+ }
2721
+ });
2722
+
2723
+ return summary;
2724
+ }
2725
+
2726
+ /**
2727
+ * Get detailed information about the scheduler state and timing.
2728
+ * @returns {Object} Scheduler state information
2729
+ */
2730
+ inspectScheduler() {
2731
+ const now = this.now();
2732
+
2733
+ // Calculate next run time for different scenarios
2734
+ let nextTaskTime = Infinity;
2735
+ let nextTaskInfo = null;
2736
+
2737
+ // Check pending tasks
2738
+ if (this.pendingHeap.size() > 0) {
2739
+ const nextPending = this.pendingHeap.peek();
2740
+ if (nextPending && nextPending.readyAt < nextTaskTime) {
2741
+ nextTaskTime = nextPending.readyAt;
2742
+ nextTaskInfo = {
2743
+ id: nextPending.id,
2744
+ priority: nextPending.priority,
2745
+ readyAt: nextPending.readyAt,
2746
+ source: "pending"
2747
+ };
2748
+ }
2749
+ }
2750
+
2751
+ // Check ready tasks
2752
+ if (this.readyHeap.size() > 0) {
2753
+ const nextReady = this.readyHeap.peek();
2754
+ if (nextReady) {
2755
+ nextTaskTime = now;
2756
+ nextTaskInfo = {
2757
+ id: nextReady.id,
2758
+ priority: nextReady.priority,
2759
+ source: "ready"
2760
+ };
2761
+ }
2762
+ }
2763
+
2764
+ // Check active delays
2765
+ let delayInfo = null;
2766
+ if (this.nextAvailableTime > now) {
2767
+ delayInfo = {
2768
+ priority: this.lastCompletedPriority,
2769
+ expiresAt: this.nextAvailableTime
2770
+ };
2771
+ }
2772
+
2773
+ // Get per-priority concurrency information
2774
+ const priorityConcurrency = {};
2775
+ for (const [priority, count] of this.runningByPriority.entries()) {
2776
+ if (count > 0) {
2777
+ const priorityConfig = this.options.priorities[priority];
2778
+ priorityConcurrency[priority] = {
2779
+ running: count,
2780
+ limit: priorityConfig?.concurrency || this.options.concurrency,
2781
+ available: (priorityConfig?.concurrency || this.options.concurrency) - count
2782
+ };
2783
+ }
2784
+ }
2785
+
2786
+ // Also include configured priority limits even if nothing is running
2787
+ for (const [priority, config] of Object.entries(this.options.priorities)) {
2788
+ if (config.concurrency && !priorityConcurrency[priority]) {
2789
+ priorityConcurrency[priority] = {
2790
+ running: 0,
2791
+ limit: config.concurrency,
2792
+ available: config.concurrency
2793
+ };
2794
+ }
2795
+ }
2796
+
2797
+ return {
2798
+ timestamp: now,
2799
+ isActive: this.isActive,
2800
+ smartScheduling: this.options.smartScheduling,
2801
+ concurrency: this.options.concurrency,
2802
+ currentConcurrency: this.running.size,
2803
+ availableSlots: this.options.concurrency - this.running.size,
2804
+ priorityConcurrency: priorityConcurrency,
2805
+ timers: {
2806
+ schedulerInterval: this.schedulerInterval,
2807
+ schedulerTimeout: this.schedulerTimeout,
2808
+ nextScheduledRun: this.nextScheduledRun,
2809
+ nextRunIn: this.nextScheduledRun ? this.nextScheduledRun - now : null
2810
+ },
2811
+ nextTask: nextTaskInfo
2812
+ ? {
2813
+ ...nextTaskInfo,
2814
+ readyIn: nextTaskTime - now,
2815
+ canRunNow: nextTaskTime <= now && this.running.size < this.options.concurrency
2816
+ }
2817
+ : null,
2818
+ delays: {
2819
+ hasActiveDelays: this.nextAvailableTime > now,
2820
+ count: this.nextAvailableTime > now ? 1 : 0,
2821
+ nextExpiry: delayInfo
2822
+ ? {
2823
+ ...delayInfo,
2824
+ expiresIn: delayInfo.expiresAt - now
2825
+ }
2826
+ : null
2827
+ },
2828
+ queueCounts: {
2829
+ pending: this.pendingHeap.size(),
2830
+ ready: this.readyHeap.size(),
2831
+ running: this.running.size,
2832
+ total: this.pendingHeap.size() + this.readyHeap.size() + this.running.size
2833
+ }
2834
+ };
2835
+ }
2836
+
2837
+ /**
2838
+ * Log comprehensive queue state to console for debugging.
2839
+ * @param {boolean} [detailed=false] - Whether to include detailed task information
2840
+ */
2841
+ debugLog(detailed = false) {
2842
+ const inspection = this.inspect();
2843
+
2844
+ console.log("\n=== HoldMyTask Debug Information ===");
2845
+ console.log(`Timestamp: ${new Date(inspection.timestamp).toISOString()}`);
2846
+ console.log(`Status: ${inspection.scheduler.isActive ? "ACTIVE" : "PAUSED"}`);
2847
+ console.log(`Smart Scheduling: ${inspection.scheduler.smartScheduling ? "ON" : "OFF"}`);
2848
+ console.log(`Concurrency: ${inspection.scheduler.currentConcurrency}/${inspection.scheduler.concurrency}`);
2849
+
2850
+ console.log("\n--- Queue State ---");
2851
+ console.log(`Total Tasks: ${inspection.totals.totalTasks}`);
2852
+ console.log(` Pending: ${inspection.totals.pendingTasks}`);
2853
+ console.log(` Ready: ${inspection.totals.readyTasks}`);
2854
+ console.log(` Running: ${inspection.totals.runningTasks}`);
2855
+
2856
+ // Show per-priority concurrency information if configured
2857
+ if (Object.keys(inspection.scheduler.priorityConcurrency).length > 0) {
2858
+ console.log("\n--- Priority Concurrency ---");
2859
+ Object.entries(inspection.scheduler.priorityConcurrency).forEach(([priority, info]) => {
2860
+ console.log(` Priority ${priority}: ${info.running}/${info.limit} (${info.available} available)`);
2861
+ });
2862
+ }
2863
+
2864
+ console.log("\n--- Timer State ---");
2865
+ console.log(`Interval: ${inspection.timers.schedulerInterval.active ? `Active (${inspection.timers.schedulerInterval.id})` : "None"}`);
2866
+ console.log(`Timeout: ${inspection.timers.schedulerTimeout.active ? `Active (${inspection.timers.schedulerTimeout.id})` : "None"}`);
2867
+ if (inspection.timers.nextRunIn !== null) {
2868
+ console.log(`Next Run: ${inspection.timers.nextRunIn}ms`);
2869
+ }
2870
+
2871
+ if (inspection.delays.activeDelays > 0) {
2872
+ console.log("\n--- Active Delays ---");
2873
+ inspection.delays.delayDetails.forEach((delay) => {
2874
+ console.log(` Priority ${delay.priority}: expires in ${delay.expiresIn}ms`);
2875
+ });
2876
+ }
2877
+
2878
+ if (Object.keys(inspection.coalescing).length > 0) {
2879
+ console.log("\n--- Coalescing Groups ---");
2880
+ Object.entries(inspection.coalescing).forEach(([key, info]) => {
2881
+ console.log(` ${key}: ${info.groupCount} groups, ${info.totalTasks} tasks`);
2882
+ });
2883
+ }
2884
+
2885
+ if (detailed) {
2886
+ console.log("\n--- Detailed Task Information ---");
2887
+ if (inspection.queues.pending.count > 0) {
2888
+ console.log("\nPending Tasks:");
2889
+ inspection.queues.pending.tasks.forEach((task) => {
2890
+ console.log(` ${task.id}: priority ${task.priority}, ready in ${task.readyIn}ms`);
2891
+ });
2892
+ }
2893
+
2894
+ if (inspection.queues.ready.count > 0) {
2895
+ console.log("\nReady Tasks:");
2896
+ inspection.queues.ready.tasks.forEach((task) => {
2897
+ console.log(` ${task.id}: priority ${task.priority}`);
2898
+ });
2899
+ }
2900
+
2901
+ if (inspection.queues.running.count > 0) {
2902
+ console.log("\nRunning Tasks:");
2903
+ inspection.queues.running.tasks.forEach((task) => {
2904
+ console.log(` ${task.id}: priority ${task.priority}, running for ${task.runningFor}ms`);
2905
+ });
2906
+ }
2907
+ }
2908
+
2909
+ console.log("=====================================\n");
2910
+ }
2911
+ }