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