@cldmv/holdmytask 1.6.0 → 1.6.1

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