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