@cldmv/holdmytask 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +324 -5
- package/dist/hold-my-task.mjs +1241 -43
- package/index.cjs +10 -1
- package/index.mjs +13 -1
- package/package.json +1 -1
- package/types/dist/hold-my-task.d.mts +473 -32
- package/types/dist/hold-my-task.d.mts.map +1 -1
- package/types/index.d.mts +3 -0
- package/types/index.d.mts.map +1 -0
package/dist/hold-my-task.mjs
CHANGED
|
@@ -29,37 +29,289 @@ export class HoldMyTask extends EventEmitter {
|
|
|
29
29
|
* @param {boolean} [options.autoStart=true] - Whether to automatically start the scheduler
|
|
30
30
|
* @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
|
|
31
31
|
* @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
|
|
32
|
-
* @param {Object} [options.delays={}] -
|
|
32
|
+
* @param {Object} [options.delays={}] - DEPRECATED: Use priorities[priority].delay instead. Legacy priority-to-delay mapping (auto-converted to priorities)
|
|
33
33
|
* @param {boolean} [options.smartScheduling=true] - Use dynamic timeouts instead of constant polling for better performance
|
|
34
34
|
* @param {number} [options.tick=25] - Polling interval in milliseconds when smartScheduling is disabled
|
|
35
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
|
|
36
52
|
* @example
|
|
53
|
+
* // Enhanced configuration with priority defaults and extended coalescing
|
|
37
54
|
* const queue = new HoldMyTask({
|
|
38
55
|
* concurrency: 2,
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
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
|
+
* }
|
|
42
76
|
* });
|
|
43
77
|
*
|
|
44
78
|
* @example
|
|
45
|
-
* //
|
|
79
|
+
* // Backward compatible (deprecated but still supported)
|
|
46
80
|
* const legacyQueue = new HoldMyTask({
|
|
47
|
-
*
|
|
48
|
-
*
|
|
81
|
+
* coalescingWindowDuration: 1500,
|
|
82
|
+
* coalescingMaxDelay: 3000,
|
|
83
|
+
* coalescingResolveAllPromises: true
|
|
49
84
|
* });
|
|
50
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
|
+
|
|
51
138
|
constructor(options = {}) {
|
|
52
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
|
+
|
|
53
292
|
this.options = {
|
|
54
293
|
concurrency: 1,
|
|
55
294
|
tick: 25,
|
|
56
295
|
autoStart: true,
|
|
57
296
|
defaultPriority: 0,
|
|
58
|
-
maxQueue: Infinity,
|
|
59
|
-
|
|
297
|
+
maxQueue: maxQueue !== undefined ? maxQueue : Infinity,
|
|
298
|
+
priorities: transformedPriorities, // Unified priority configuration system
|
|
60
299
|
smartScheduling: true, // Use smart timeouts instead of polling by default
|
|
61
300
|
healingInterval: 5000, // Self-healing check interval (smart scheduling only)
|
|
62
|
-
|
|
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
|
|
63
315
|
};
|
|
64
316
|
|
|
65
317
|
// Initialize heaps
|
|
@@ -87,23 +339,50 @@ export class HoldMyTask extends EventEmitter {
|
|
|
87
339
|
// Traditional polling state (used when smartScheduling is disabled)
|
|
88
340
|
this.intervalId = null;
|
|
89
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
|
+
|
|
90
347
|
if (this.options.autoStart) {
|
|
91
348
|
this.resume();
|
|
92
349
|
}
|
|
93
350
|
}
|
|
94
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
|
+
|
|
95
367
|
/**
|
|
96
368
|
* Adds a task to the queue for execution. Supports both callback and promise-based APIs.
|
|
97
369
|
* @param {Function} task - The task function to execute. Can be sync or async.
|
|
98
370
|
* @param {Function|Object} [optionsOrCallback] - Either a callback function or options object
|
|
99
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)
|
|
100
373
|
* @param {number} [options.priority] - Task priority (higher numbers run first)
|
|
101
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)
|
|
102
376
|
* @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
|
|
103
377
|
* @param {number} [options.timeout] - Task timeout in milliseconds (for execution time limit)
|
|
104
378
|
* @param {number} [options.expire] - Task expiration timestamp or milliseconds from now (for queue waiting time limit)
|
|
105
|
-
* @param {number} [options.delay] - Delay after task completion before next task of same priority
|
|
379
|
+
* @param {number} [options.delay] - DEPRECATED: Use postDelay instead. Delay after task completion before next task of same priority
|
|
106
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)
|
|
107
386
|
* @param {*} [options.metadata] - Arbitrary metadata to attach to the task
|
|
108
387
|
* @returns {Promise|Object} Promise (if no callback) or task control object with id, cancel, status methods
|
|
109
388
|
* @throws {Error} If queue is destroyed or full
|
|
@@ -125,14 +404,22 @@ export class HoldMyTask extends EventEmitter {
|
|
|
125
404
|
*
|
|
126
405
|
* // Alternative: use delay: -1 to bypass
|
|
127
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
|
|
128
411
|
*/
|
|
129
412
|
enqueue(task, optionsOrCallback, options = {}) {
|
|
130
413
|
if (this.destroyed) {
|
|
131
|
-
|
|
414
|
+
const error = new Error("Queue is destroyed");
|
|
415
|
+
setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
|
|
416
|
+
return Promise.reject(error);
|
|
132
417
|
}
|
|
133
418
|
|
|
134
419
|
if (this.tasks.size >= this.options.maxQueue) {
|
|
135
|
-
|
|
420
|
+
const error = new Error("Queue is full");
|
|
421
|
+
setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
|
|
422
|
+
return Promise.reject(error);
|
|
136
423
|
}
|
|
137
424
|
|
|
138
425
|
// Handle dual API: callback can be second or third parameter
|
|
@@ -145,16 +432,35 @@ export class HoldMyTask extends EventEmitter {
|
|
|
145
432
|
finalOptions = { ...optionsOrCallback, ...options };
|
|
146
433
|
}
|
|
147
434
|
|
|
148
|
-
|
|
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
|
+
}
|
|
149
444
|
const now = this.now();
|
|
150
|
-
|
|
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);
|
|
151
456
|
|
|
152
457
|
// Calculate expiration timestamp
|
|
153
458
|
let expireAt = null;
|
|
154
459
|
if (finalOptions.expire !== undefined) {
|
|
155
|
-
// If expire
|
|
156
|
-
|
|
157
|
-
|
|
460
|
+
// If expire === -1, never expire (useful with coalescing)
|
|
461
|
+
if (finalOptions.expire === -1) {
|
|
462
|
+
expireAt = null;
|
|
463
|
+
} else if (finalOptions.expire > now) {
|
|
158
464
|
expireAt = finalOptions.expire;
|
|
159
465
|
} else {
|
|
160
466
|
expireAt = now + finalOptions.expire;
|
|
@@ -165,7 +471,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
165
471
|
id,
|
|
166
472
|
task,
|
|
167
473
|
callback,
|
|
168
|
-
priority
|
|
474
|
+
priority,
|
|
169
475
|
readyAt,
|
|
170
476
|
expireAt,
|
|
171
477
|
enqueueSeq: this.enqueueSeq++,
|
|
@@ -182,11 +488,11 @@ export class HoldMyTask extends EventEmitter {
|
|
|
182
488
|
|
|
183
489
|
// Check if signal is already aborted
|
|
184
490
|
if (finalOptions.signal?.aborted) {
|
|
185
|
-
this.
|
|
491
|
+
this.cancel(id, "Task was aborted");
|
|
186
492
|
} else if (finalOptions.signal) {
|
|
187
493
|
// For both callback and promise API, the queue handles signal abortion
|
|
188
494
|
finalOptions.signal.addEventListener("abort", () => {
|
|
189
|
-
this.
|
|
495
|
+
this.cancel(id, "Task was aborted");
|
|
190
496
|
});
|
|
191
497
|
}
|
|
192
498
|
|
|
@@ -194,14 +500,13 @@ export class HoldMyTask extends EventEmitter {
|
|
|
194
500
|
if (this.options.smartScheduling) {
|
|
195
501
|
this.scheduleSmartTimeout();
|
|
196
502
|
} else {
|
|
197
|
-
this.
|
|
503
|
+
this._scheduleNextTick();
|
|
198
504
|
}
|
|
199
505
|
}
|
|
200
|
-
|
|
201
506
|
const tasks = this.tasks; // Capture reference
|
|
202
507
|
const taskHandle = {
|
|
203
508
|
id,
|
|
204
|
-
cancel: (reason) => this.
|
|
509
|
+
cancel: (reason) => this.cancel(id, reason),
|
|
205
510
|
status: () => tasks.get(id)?.status ?? "canceled",
|
|
206
511
|
get startedAt() {
|
|
207
512
|
return tasks.get(id)?.startedAt;
|
|
@@ -227,7 +532,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
227
532
|
// Attach task handle properties to the promise with live getters
|
|
228
533
|
const tasksRef = this.tasks;
|
|
229
534
|
Object.defineProperty(promise, "id", { value: id, enumerable: true });
|
|
230
|
-
Object.defineProperty(promise, "cancel", { value: (reason) => this.
|
|
535
|
+
Object.defineProperty(promise, "cancel", { value: (reason) => this.cancel(id, reason), enumerable: true });
|
|
231
536
|
Object.defineProperty(promise, "status", { value: () => tasksRef.get(id)?.status ?? "canceled", enumerable: true });
|
|
232
537
|
Object.defineProperty(promise, "startedAt", { get: () => tasksRef.get(id)?.startedAt, enumerable: true });
|
|
233
538
|
Object.defineProperty(promise, "finishedAt", { get: () => tasksRef.get(id)?.finishedAt, enumerable: true });
|
|
@@ -240,18 +545,576 @@ export class HoldMyTask extends EventEmitter {
|
|
|
240
545
|
return taskHandle;
|
|
241
546
|
}
|
|
242
547
|
|
|
548
|
+
/**
|
|
549
|
+
* Handles tasks with coalescingKey through the coalescing system.
|
|
550
|
+
* @private
|
|
551
|
+
* @internal
|
|
552
|
+
* @param {string} id - Task ID
|
|
553
|
+
* @param {Function} task - Task function
|
|
554
|
+
* @param {Function|null} callback - Callback function (null for promise API)
|
|
555
|
+
* @param {Object} options - Task options
|
|
556
|
+
* @param {number} now - Current timestamp
|
|
557
|
+
* @returns {Promise|Object} Promise or task handle
|
|
558
|
+
*/
|
|
559
|
+
_handleCoalescingTask(id, task, callback, options, now) {
|
|
560
|
+
const { coalescingKey } = options;
|
|
561
|
+
|
|
562
|
+
// Get effective coalescing configuration including new delay and start options
|
|
563
|
+
const coalescingConfig = this.getCoalescingConfig(coalescingKey, options);
|
|
564
|
+
const priority = options.priority ?? this.options.defaultPriority;
|
|
565
|
+
const priorityConfig = this.getPriorityConfig(priority, options);
|
|
566
|
+
|
|
567
|
+
// Apply configuration priority: task options > coalescing key config > priority defaults > coalescing defaults
|
|
568
|
+
const effectiveStart = options.start ?? coalescingConfig.startDelay ?? priorityConfig.startDelay ?? 0;
|
|
569
|
+
|
|
570
|
+
const readyAt = options.timestamp ?? (effectiveStart ? now + effectiveStart : now);
|
|
571
|
+
const windowEnd = now + coalescingConfig.windowDuration;
|
|
572
|
+
const mustRunBy = now + coalescingConfig.maxDelay;
|
|
573
|
+
|
|
574
|
+
// Apply effective delay configuration
|
|
575
|
+
const effectiveDelay = options.delay ?? coalescingConfig.postDelay ?? priorityConfig.postDelay;
|
|
576
|
+
|
|
577
|
+
// Create task item (not added to main queue directly)
|
|
578
|
+
const taskItem = {
|
|
579
|
+
id,
|
|
580
|
+
task,
|
|
581
|
+
callback,
|
|
582
|
+
priority,
|
|
583
|
+
readyAt,
|
|
584
|
+
status: "coalescing",
|
|
585
|
+
signal: options.signal,
|
|
586
|
+
timeout: options.timeout,
|
|
587
|
+
delay: effectiveDelay,
|
|
588
|
+
bypassDelay: options.bypassDelay || options.delay === -1,
|
|
589
|
+
metadata: options.metadata,
|
|
590
|
+
coalescingKey,
|
|
591
|
+
enqueueSeq: this.enqueueSeq++
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
// Handle signal abortion for coalescing tasks
|
|
595
|
+
if (options.signal?.aborted) {
|
|
596
|
+
taskItem.status = "canceled";
|
|
597
|
+
if (callback) {
|
|
598
|
+
try {
|
|
599
|
+
callback(new Error("Task was aborted"), null);
|
|
600
|
+
} catch (callbackError) {
|
|
601
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return this._createTaskHandle(taskItem, callback);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Add abort listener
|
|
608
|
+
options.signal?.addEventListener("abort", () => {
|
|
609
|
+
this._cancelCoalescingTask(id, coalescingKey, "Task was aborted");
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// Find compatible coalescing group or create new one
|
|
613
|
+
const compatibleGroup = this._findCompatibleCoalescingGroup(coalescingKey, now);
|
|
614
|
+
|
|
615
|
+
if (compatibleGroup) {
|
|
616
|
+
// Add to existing group
|
|
617
|
+
this._addToCoalescingGroup(compatibleGroup, taskItem, windowEnd, mustRunBy);
|
|
618
|
+
} else {
|
|
619
|
+
// Create new coalescing group using coalescingConfig
|
|
620
|
+
this._createCoalescingGroup(
|
|
621
|
+
coalescingKey,
|
|
622
|
+
taskItem,
|
|
623
|
+
windowEnd,
|
|
624
|
+
mustRunBy,
|
|
625
|
+
coalescingConfig.multipleCallbacks,
|
|
626
|
+
coalescingConfig.resolveAllPromises
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
return this._createTaskHandle(taskItem, callback);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Finds a compatible coalescing group for a new task.
|
|
635
|
+
* @private
|
|
636
|
+
* @internal
|
|
637
|
+
* @param {string} coalescingKey - The coalescing key
|
|
638
|
+
* @param {number} now - Current timestamp
|
|
639
|
+
* @param {number} windowEnd - End of new task's coalescing window
|
|
640
|
+
* @param {number} mustRunBy - New task's mustRunBy deadline
|
|
641
|
+
* @returns {Object|null} Compatible coalescing group or null
|
|
642
|
+
*/
|
|
643
|
+
_findCompatibleCoalescingGroup(coalescingKey, now) {
|
|
644
|
+
const groups = this.coalescingGroups.get(coalescingKey);
|
|
645
|
+
if (!groups) return null;
|
|
646
|
+
|
|
647
|
+
// Find a group that is within both coalescing window and mustRunBy deadline
|
|
648
|
+
for (const group of groups) {
|
|
649
|
+
if (now <= group.windowEnd && now <= group.mustRunBy) {
|
|
650
|
+
return group;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Creates a new coalescing group with a representative task in the main queue.
|
|
659
|
+
* @private
|
|
660
|
+
* @internal
|
|
661
|
+
* @param {string} coalescingKey - The coalescing key
|
|
662
|
+
* @param {Object} taskItem - The first task item for this group
|
|
663
|
+
* @param {number} windowEnd - End of coalescing window
|
|
664
|
+
* @param {number} mustRunBy - Latest execution deadline
|
|
665
|
+
* @param {boolean} multipleCallbacks - Whether to call multiple callbacks
|
|
666
|
+
* @param {boolean} resolveAllPromises - Whether to resolve all promises with same result
|
|
667
|
+
* @returns {Object} The created coalescing group
|
|
668
|
+
*/
|
|
669
|
+
_createCoalescingGroup(coalescingKey, taskItem, windowEnd, mustRunBy, multipleCallbacks, resolveAllPromises) {
|
|
670
|
+
const representativeId = String(this.nextId++);
|
|
671
|
+
const groupId = String(this.nextGroupId++);
|
|
672
|
+
|
|
673
|
+
// Create representative task that will actually run
|
|
674
|
+
const representative = {
|
|
675
|
+
id: representativeId,
|
|
676
|
+
task: this._createCoalescingRepresentativeTask(coalescingKey, groupId),
|
|
677
|
+
callback: null, // Representative handles its own completion
|
|
678
|
+
priority: taskItem.priority,
|
|
679
|
+
readyAt: taskItem.readyAt,
|
|
680
|
+
expireAt: null, // Use mustRunBy logic instead
|
|
681
|
+
enqueueSeq: this.enqueueSeq++,
|
|
682
|
+
status: "pending",
|
|
683
|
+
signal: null, // Individual tasks handle their own signals
|
|
684
|
+
timeout: taskItem.timeout,
|
|
685
|
+
delay: taskItem.delay || 0,
|
|
686
|
+
bypassDelay: taskItem.bypassDelay || false,
|
|
687
|
+
metadata: { coalescingKey, groupId, representative: true },
|
|
688
|
+
isCoalescingRepresentative: true
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
// Create coalescing group
|
|
692
|
+
const group = {
|
|
693
|
+
coalescingKey,
|
|
694
|
+
groupId,
|
|
695
|
+
tasks: new Map([[taskItem.id, taskItem]]),
|
|
696
|
+
representativeId,
|
|
697
|
+
windowEnd,
|
|
698
|
+
mustRunBy,
|
|
699
|
+
multipleCallbacks,
|
|
700
|
+
resolveAllPromises,
|
|
701
|
+
latestTask: taskItem,
|
|
702
|
+
originalTask: taskItem.task // Store the actual task function
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
// Store group and representative mapping
|
|
706
|
+
if (!this.coalescingGroups.has(coalescingKey)) {
|
|
707
|
+
this.coalescingGroups.set(coalescingKey, []);
|
|
708
|
+
}
|
|
709
|
+
this.coalescingGroups.get(coalescingKey).push(group);
|
|
710
|
+
this.coalescingRepresentatives.set(representativeId, { coalescingKey, groupId });
|
|
711
|
+
|
|
712
|
+
// Add representative to main queue
|
|
713
|
+
this.tasks.set(representativeId, representative);
|
|
714
|
+
this.pendingHeap.push(representative);
|
|
715
|
+
|
|
716
|
+
if (this.isActive) {
|
|
717
|
+
if (this.options.smartScheduling) {
|
|
718
|
+
this.scheduleSmartTimeout();
|
|
719
|
+
} else {
|
|
720
|
+
this._scheduleNextTick();
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
return group;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Adds a task to an existing coalescing group, updating the representative if needed.
|
|
728
|
+
* @private
|
|
729
|
+
* @internal
|
|
730
|
+
* @param {Object} group - The existing coalescing group
|
|
731
|
+
* @param {Object} taskItem - The new task item to add
|
|
732
|
+
* @param {number} windowEnd - End of coalescing window
|
|
733
|
+
* @param {number} mustRunBy - Latest execution deadline
|
|
734
|
+
* @param {number} now - Current timestamp
|
|
735
|
+
* @returns {void}
|
|
736
|
+
*/
|
|
737
|
+
_addToCoalescingGroup(group, taskItem, windowEnd, mustRunBy) {
|
|
738
|
+
// Add task to group
|
|
739
|
+
group.tasks.set(taskItem.id, taskItem);
|
|
740
|
+
|
|
741
|
+
// Update group timing - keep original window but preserve earliest mustRunBy
|
|
742
|
+
// NOTE: Don't extend windowEnd - coalescing window should be fixed from first task
|
|
743
|
+
group.mustRunBy = Math.min(group.mustRunBy, mustRunBy);
|
|
744
|
+
|
|
745
|
+
// Update latest task (this will be the task function that actually runs)
|
|
746
|
+
group.latestTask = taskItem;
|
|
747
|
+
group.originalTask = taskItem.task;
|
|
748
|
+
|
|
749
|
+
// Update representative task in queue if needed
|
|
750
|
+
const representative = this.tasks.get(group.representativeId);
|
|
751
|
+
if (representative) {
|
|
752
|
+
// Update timing - use latest task's timing
|
|
753
|
+
representative.readyAt = taskItem.readyAt;
|
|
754
|
+
representative.priority = taskItem.priority;
|
|
755
|
+
representative.timeout = taskItem.timeout;
|
|
756
|
+
representative.delay = taskItem.delay || representative.delay;
|
|
757
|
+
representative.bypassDelay = taskItem.bypassDelay || representative.bypassDelay;
|
|
758
|
+
|
|
759
|
+
// Rebuild heaps to reflect updated representative
|
|
760
|
+
this._rebuildHeaps();
|
|
761
|
+
|
|
762
|
+
if (this.isActive) {
|
|
763
|
+
if (this.options.smartScheduling) {
|
|
764
|
+
this.scheduleSmartTimeout();
|
|
765
|
+
} else {
|
|
766
|
+
this._scheduleNextTick();
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Creates the representative task function that manages coalesced task execution.
|
|
774
|
+
* @private
|
|
775
|
+
* @internal
|
|
776
|
+
* @param {string} coalescingKey - The coalescing key
|
|
777
|
+
* @param {string} groupId - The group ID
|
|
778
|
+
* @returns {Function} The representative task function
|
|
779
|
+
*/
|
|
780
|
+
_createCoalescingRepresentativeTask(coalescingKey, groupId) {
|
|
781
|
+
return async (signal) => {
|
|
782
|
+
const groups = this.coalescingGroups.get(coalescingKey);
|
|
783
|
+
const group = groups?.find((g) => g.groupId === groupId);
|
|
784
|
+
|
|
785
|
+
if (!group) {
|
|
786
|
+
throw new Error(`Coalescing group ${coalescingKey}:${groupId} not found`);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
try {
|
|
790
|
+
// Execute the actual task (using latest task's function)
|
|
791
|
+
const result = await group.originalTask(signal);
|
|
792
|
+
|
|
793
|
+
// Handle callbacks/promises
|
|
794
|
+
this._resolveCoalescingGroup(group, null, result);
|
|
795
|
+
|
|
796
|
+
return result;
|
|
797
|
+
} catch (error) {
|
|
798
|
+
// Handle errors for all tasks in group
|
|
799
|
+
this._resolveCoalescingGroup(group, error, null);
|
|
800
|
+
throw error;
|
|
801
|
+
} finally {
|
|
802
|
+
// Clean up coalescing group
|
|
803
|
+
this._cleanupCoalescingGroup(coalescingKey, groupId);
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Resolves all callbacks/promises in a coalescing group.
|
|
810
|
+
* @private
|
|
811
|
+
* @internal
|
|
812
|
+
* @param {Object} group - The coalescing group
|
|
813
|
+
* @param {Error|null} error - Error if task failed
|
|
814
|
+
* @param {*} result - Result if task succeeded
|
|
815
|
+
* @returns {void}
|
|
816
|
+
*/
|
|
817
|
+
_resolveCoalescingGroup(group, error, result) {
|
|
818
|
+
if (group.multipleCallbacks) {
|
|
819
|
+
// Multiple callback mode - resolve all non-canceled tasks
|
|
820
|
+
for (const taskItem of group.tasks.values()) {
|
|
821
|
+
if (taskItem.status === "canceled") continue;
|
|
822
|
+
|
|
823
|
+
taskItem.status = error ? "error" : "completed";
|
|
824
|
+
taskItem.finishedAt = this.now();
|
|
825
|
+
|
|
826
|
+
if (error) {
|
|
827
|
+
taskItem.error = error;
|
|
828
|
+
} else {
|
|
829
|
+
taskItem.result = result;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (taskItem.callback) {
|
|
833
|
+
try {
|
|
834
|
+
if (error) {
|
|
835
|
+
taskItem.callback(error, null);
|
|
836
|
+
} else {
|
|
837
|
+
taskItem.callback(null, result);
|
|
838
|
+
}
|
|
839
|
+
} catch (callbackError) {
|
|
840
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
841
|
+
}
|
|
842
|
+
} else if (taskItem.resolve) {
|
|
843
|
+
if (error) {
|
|
844
|
+
taskItem.reject(error);
|
|
845
|
+
} else {
|
|
846
|
+
taskItem.resolve(result);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// Clean up canceled tasks that didn't get resolved
|
|
852
|
+
for (const taskItem of group.tasks.values()) {
|
|
853
|
+
if (taskItem.status === "canceled" && taskItem.reject) {
|
|
854
|
+
taskItem.reject(new Error("Task was canceled"));
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
} else {
|
|
858
|
+
// Single callback mode - resolve latest only or all based on resolveAllPromises option
|
|
859
|
+
for (const taskItem of group.tasks.values()) {
|
|
860
|
+
if (taskItem.status === "canceled") continue;
|
|
861
|
+
|
|
862
|
+
if (taskItem === group.latestTask) {
|
|
863
|
+
// Always resolve the latest task
|
|
864
|
+
taskItem.status = error ? "error" : "completed";
|
|
865
|
+
taskItem.finishedAt = this.now();
|
|
866
|
+
|
|
867
|
+
if (error) {
|
|
868
|
+
taskItem.error = error;
|
|
869
|
+
} else {
|
|
870
|
+
taskItem.result = result;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (taskItem.callback) {
|
|
874
|
+
try {
|
|
875
|
+
if (error) {
|
|
876
|
+
taskItem.callback(error, null);
|
|
877
|
+
} else {
|
|
878
|
+
taskItem.callback(null, result);
|
|
879
|
+
}
|
|
880
|
+
} catch (callbackError) {
|
|
881
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
882
|
+
}
|
|
883
|
+
} else if (taskItem.resolve) {
|
|
884
|
+
if (error) {
|
|
885
|
+
taskItem.reject(error);
|
|
886
|
+
} else {
|
|
887
|
+
taskItem.resolve(result);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
} else {
|
|
891
|
+
// Handle other tasks based on resolveAllPromises setting
|
|
892
|
+
if (group.resolveAllPromises) {
|
|
893
|
+
// Resolve with same result as latest task
|
|
894
|
+
taskItem.status = error ? "error" : "coalesced";
|
|
895
|
+
taskItem.finishedAt = this.now();
|
|
896
|
+
|
|
897
|
+
if (error) {
|
|
898
|
+
taskItem.error = error;
|
|
899
|
+
} else {
|
|
900
|
+
taskItem.result = result;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
if (taskItem.callback) {
|
|
904
|
+
try {
|
|
905
|
+
if (error) {
|
|
906
|
+
taskItem.callback(error, null);
|
|
907
|
+
} else {
|
|
908
|
+
taskItem.callback(null, result);
|
|
909
|
+
}
|
|
910
|
+
} catch (callbackError) {
|
|
911
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
912
|
+
}
|
|
913
|
+
} else if (taskItem.resolve) {
|
|
914
|
+
if (error) {
|
|
915
|
+
taskItem.reject(error);
|
|
916
|
+
} else {
|
|
917
|
+
taskItem.resolve(result);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
} else {
|
|
921
|
+
// Reject other tasks (original behavior)
|
|
922
|
+
taskItem.status = "coalesced";
|
|
923
|
+
taskItem.finishedAt = this.now();
|
|
924
|
+
|
|
925
|
+
if (taskItem.callback) {
|
|
926
|
+
try {
|
|
927
|
+
taskItem.callback(new Error("Task was coalesced with a newer task"), null);
|
|
928
|
+
} catch (callbackError) {
|
|
929
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
930
|
+
}
|
|
931
|
+
} else if (taskItem.reject) {
|
|
932
|
+
taskItem.reject(new Error("Task was coalesced with a newer task"));
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// Clean up canceled tasks
|
|
939
|
+
for (const taskItem of group.tasks.values()) {
|
|
940
|
+
if (taskItem.status === "canceled" && taskItem.reject) {
|
|
941
|
+
taskItem.reject(new Error("Task was canceled"));
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* Cancels a specific task within a coalescing group.
|
|
949
|
+
* @private
|
|
950
|
+
* @internal
|
|
951
|
+
* @param {string} taskId - ID of task to cancel
|
|
952
|
+
* @param {string} coalescingKey - The coalescing key
|
|
953
|
+
* @param {string} reason - Cancellation reason
|
|
954
|
+
* @returns {void}
|
|
955
|
+
*/
|
|
956
|
+
_cancelCoalescingTask(taskId, coalescingKey, reason) {
|
|
957
|
+
const groups = this.coalescingGroups.get(coalescingKey) || [];
|
|
958
|
+
|
|
959
|
+
for (const group of groups) {
|
|
960
|
+
const taskItem = group.tasks.get(taskId);
|
|
961
|
+
if (!taskItem) continue;
|
|
962
|
+
|
|
963
|
+
taskItem.status = "canceled";
|
|
964
|
+
taskItem.finishedAt = this.now();
|
|
965
|
+
|
|
966
|
+
// Handle callback/promise
|
|
967
|
+
if (taskItem.callback) {
|
|
968
|
+
try {
|
|
969
|
+
taskItem.callback(new Error(reason), null);
|
|
970
|
+
} catch (callbackError) {
|
|
971
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
972
|
+
}
|
|
973
|
+
} else if (taskItem.reject) {
|
|
974
|
+
taskItem.reject(new Error(reason));
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// Remove from group
|
|
978
|
+
group.tasks.delete(taskId);
|
|
979
|
+
|
|
980
|
+
// If group is empty, clean up representative task
|
|
981
|
+
if (group.tasks.size === 0) {
|
|
982
|
+
const representative = this.tasks.get(group.representativeId);
|
|
983
|
+
if (representative) {
|
|
984
|
+
this.cancel(group.representativeId, "All coalesced tasks canceled");
|
|
985
|
+
}
|
|
986
|
+
this._cleanupCoalescingGroup(coalescingKey, group.groupId);
|
|
987
|
+
} else {
|
|
988
|
+
// Update latest task if needed
|
|
989
|
+
const remainingTasks = Array.from(group.tasks.values());
|
|
990
|
+
group.latestTask = remainingTasks[remainingTasks.length - 1];
|
|
991
|
+
group.originalTask = group.latestTask.task;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
return; // Found and handled the task
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Cleans up a coalescing group after completion or cancellation.
|
|
1000
|
+
* @private
|
|
1001
|
+
* @internal
|
|
1002
|
+
* @param {string} coalescingKey - The coalescing key
|
|
1003
|
+
* @param {string} groupId - The group ID to clean up
|
|
1004
|
+
* @returns {void}
|
|
1005
|
+
*/
|
|
1006
|
+
_cleanupCoalescingGroup(coalescingKey, groupId) {
|
|
1007
|
+
const groups = this.coalescingGroups.get(coalescingKey);
|
|
1008
|
+
if (!groups) return;
|
|
1009
|
+
|
|
1010
|
+
const groupIndex = groups.findIndex((g) => g.groupId === groupId);
|
|
1011
|
+
if (groupIndex >= 0) {
|
|
1012
|
+
const group = groups[groupIndex];
|
|
1013
|
+
groups.splice(groupIndex, 1);
|
|
1014
|
+
|
|
1015
|
+
// Remove representative mapping
|
|
1016
|
+
this.coalescingRepresentatives.delete(group.representativeId);
|
|
1017
|
+
|
|
1018
|
+
// If no more groups for this key, remove the key entirely
|
|
1019
|
+
if (groups.length === 0) {
|
|
1020
|
+
this.coalescingGroups.delete(coalescingKey);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Rebuilds the heap structures to reflect updated priorities/timing.
|
|
1027
|
+
* @private
|
|
1028
|
+
* @internal
|
|
1029
|
+
* @returns {void}
|
|
1030
|
+
*/
|
|
1031
|
+
_rebuildHeaps() {
|
|
1032
|
+
// Rebuild pending heap
|
|
1033
|
+
const pendingTasks = [...this.pendingHeap.heap];
|
|
1034
|
+
this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
|
|
1035
|
+
for (const task of pendingTasks) {
|
|
1036
|
+
this.pendingHeap.push(task);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// Rebuild ready heap
|
|
1040
|
+
const readyTasks = [...this.readyHeap.heap];
|
|
1041
|
+
this.readyHeap = new MinHeap((a, b) => {
|
|
1042
|
+
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
1043
|
+
if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt;
|
|
1044
|
+
return a.enqueueSeq - b.enqueueSeq;
|
|
1045
|
+
});
|
|
1046
|
+
for (const task of readyTasks) {
|
|
1047
|
+
this.readyHeap.push(task);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/**
|
|
1052
|
+
* Creates a task handle for both regular and coalescing tasks.
|
|
1053
|
+
* @private
|
|
1054
|
+
* @internal
|
|
1055
|
+
* @param {Object} item - The task item
|
|
1056
|
+
* @param {Function|null} callback - Callback function
|
|
1057
|
+
* @returns {Promise|Object} Promise or task control object
|
|
1058
|
+
*/
|
|
1059
|
+
_createTaskHandle(item, callback) {
|
|
1060
|
+
const taskHandle = {
|
|
1061
|
+
id: item.id,
|
|
1062
|
+
cancel: (reason) => {
|
|
1063
|
+
if (item.coalescingKey) {
|
|
1064
|
+
this._cancelCoalescingTask(item.id, item.coalescingKey, reason || "Task canceled");
|
|
1065
|
+
} else {
|
|
1066
|
+
this.cancel(item.id, reason || "Task canceled");
|
|
1067
|
+
}
|
|
1068
|
+
},
|
|
1069
|
+
status: () => item.status,
|
|
1070
|
+
get startedAt() {
|
|
1071
|
+
return item.startedAt;
|
|
1072
|
+
},
|
|
1073
|
+
get finishedAt() {
|
|
1074
|
+
return item.finishedAt;
|
|
1075
|
+
},
|
|
1076
|
+
get result() {
|
|
1077
|
+
return item.result;
|
|
1078
|
+
},
|
|
1079
|
+
get error() {
|
|
1080
|
+
return item.error;
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
|
|
1084
|
+
// Return Promise if no callback provided
|
|
1085
|
+
if (!callback) {
|
|
1086
|
+
const promise = new Promise((resolve, reject) => {
|
|
1087
|
+
item.resolve = resolve;
|
|
1088
|
+
item.reject = reject;
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
// Attach task handle properties to the promise
|
|
1092
|
+
Object.defineProperty(promise, "id", { value: item.id, enumerable: true });
|
|
1093
|
+
Object.defineProperty(promise, "cancel", { value: taskHandle.cancel, enumerable: true });
|
|
1094
|
+
Object.defineProperty(promise, "status", { value: taskHandle.status, enumerable: true });
|
|
1095
|
+
Object.defineProperty(promise, "startedAt", { get: () => item.startedAt, enumerable: true });
|
|
1096
|
+
Object.defineProperty(promise, "finishedAt", { get: () => item.finishedAt, enumerable: true });
|
|
1097
|
+
Object.defineProperty(promise, "result", { get: () => item.result, enumerable: true });
|
|
1098
|
+
Object.defineProperty(promise, "error", { get: () => item.error, enumerable: true });
|
|
1099
|
+
|
|
1100
|
+
return promise;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
return taskHandle;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
243
1106
|
/**
|
|
244
1107
|
* Cancels a pending task by ID.
|
|
245
1108
|
* @param {string} id - The task ID to cancel
|
|
246
1109
|
* @param {string} [reason="Task canceled"] - Reason for cancellation
|
|
247
|
-
* @returns {
|
|
1110
|
+
* @returns {boolean} True if task was found and cancelled, false otherwise
|
|
248
1111
|
* @example
|
|
249
1112
|
* const task = queue.enqueue(() => longRunningTask());
|
|
250
|
-
* queue.
|
|
1113
|
+
* const cancelled = queue.cancel(task.id, "User requested cancellation");
|
|
251
1114
|
*/
|
|
252
|
-
|
|
1115
|
+
cancel(id, reason) {
|
|
253
1116
|
const item = this.tasks.get(id);
|
|
254
|
-
if (!item || item.status !== "pending") return;
|
|
1117
|
+
if (!item || item.status !== "pending") return false;
|
|
255
1118
|
|
|
256
1119
|
item.status = "canceled";
|
|
257
1120
|
item.finishedAt = this.now();
|
|
@@ -262,6 +1125,18 @@ export class HoldMyTask extends EventEmitter {
|
|
|
262
1125
|
if (!item.callback && item.reject) {
|
|
263
1126
|
item.reject(new Error(reason || "Task canceled"));
|
|
264
1127
|
}
|
|
1128
|
+
|
|
1129
|
+
return true;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* Alias for cancel() method for backward compatibility.
|
|
1134
|
+
* @param {string|number} id - The task ID to cancel
|
|
1135
|
+
* @param {string} [reason="Task canceled"] - Reason for cancellation
|
|
1136
|
+
* @returns {boolean} True if task was found and cancelled, false otherwise
|
|
1137
|
+
*/
|
|
1138
|
+
cancelTask(id, reason) {
|
|
1139
|
+
return this.cancel(id, reason);
|
|
265
1140
|
}
|
|
266
1141
|
|
|
267
1142
|
/**
|
|
@@ -308,7 +1183,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
308
1183
|
if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
|
|
309
1184
|
this.schedulerTick();
|
|
310
1185
|
}
|
|
311
|
-
this.
|
|
1186
|
+
this._scheduleNextTick();
|
|
312
1187
|
}
|
|
313
1188
|
}
|
|
314
1189
|
|
|
@@ -334,6 +1209,24 @@ export class HoldMyTask extends EventEmitter {
|
|
|
334
1209
|
this.emit("cancel", item);
|
|
335
1210
|
}
|
|
336
1211
|
|
|
1212
|
+
// Clear coalescing groups
|
|
1213
|
+
for (const [_, groups] of this.coalescingGroups) {
|
|
1214
|
+
for (const group of groups) {
|
|
1215
|
+
for (const taskItem of group.tasks.values()) {
|
|
1216
|
+
taskItem.status = "canceled";
|
|
1217
|
+
if (taskItem.callback) {
|
|
1218
|
+
try {
|
|
1219
|
+
taskItem.callback(new Error("Queue cleared"), null);
|
|
1220
|
+
} catch (callbackError) {
|
|
1221
|
+
this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
|
|
1222
|
+
}
|
|
1223
|
+
} else if (taskItem.reject) {
|
|
1224
|
+
taskItem.reject(new Error("Queue cleared"));
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
|
|
337
1230
|
this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
|
|
338
1231
|
this.readyHeap = new MinHeap((a, b) => {
|
|
339
1232
|
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
@@ -341,6 +1234,8 @@ export class HoldMyTask extends EventEmitter {
|
|
|
341
1234
|
return a.enqueueSeq - b.enqueueSeq;
|
|
342
1235
|
});
|
|
343
1236
|
this.tasks.clear();
|
|
1237
|
+
this.coalescingGroups.clear();
|
|
1238
|
+
this.coalescingRepresentatives.clear();
|
|
344
1239
|
|
|
345
1240
|
// Reschedule since we may have no work
|
|
346
1241
|
if (this.isActive) {
|
|
@@ -411,8 +1306,9 @@ export class HoldMyTask extends EventEmitter {
|
|
|
411
1306
|
* Schedules the next scheduler tick based on when tasks become ready.
|
|
412
1307
|
* @returns {void}
|
|
413
1308
|
* @private
|
|
1309
|
+
* @internal
|
|
414
1310
|
*/
|
|
415
|
-
|
|
1311
|
+
_scheduleNextTick() {
|
|
416
1312
|
if (!this.isActive || this.destroyed) return;
|
|
417
1313
|
|
|
418
1314
|
this.clearTimers();
|
|
@@ -456,7 +1352,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
456
1352
|
if (task && task.status === "pending") {
|
|
457
1353
|
// Check if task has expired before making it ready
|
|
458
1354
|
if (task.expireAt && now >= task.expireAt) {
|
|
459
|
-
this.
|
|
1355
|
+
this._expireTask(task);
|
|
460
1356
|
} else {
|
|
461
1357
|
task.status = "ready";
|
|
462
1358
|
this.readyHeap.push(task);
|
|
@@ -468,7 +1364,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
468
1364
|
// Start tasks up to concurrency limit
|
|
469
1365
|
let hasWaitingTasks = false;
|
|
470
1366
|
const currentTime = this.now();
|
|
471
|
-
const delay = this.lastCompletedPriority !== null ? this.options.
|
|
1367
|
+
const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
|
|
472
1368
|
const delayActive = delay > 0 && currentTime < this.nextAvailableTime;
|
|
473
1369
|
|
|
474
1370
|
while (this.running.size < this.options.concurrency && this.readyHeap.size() > 0) {
|
|
@@ -478,7 +1374,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
478
1374
|
// Check if task has expired before starting it
|
|
479
1375
|
if (task.expireAt && currentTime >= task.expireAt) {
|
|
480
1376
|
this.readyHeap.pop(); // Remove expired task from heap
|
|
481
|
-
this.
|
|
1377
|
+
this._expireTask(task);
|
|
482
1378
|
continue; // Check next task
|
|
483
1379
|
}
|
|
484
1380
|
|
|
@@ -486,7 +1382,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
486
1382
|
|
|
487
1383
|
if (canStart) {
|
|
488
1384
|
this.readyHeap.pop(); // Remove it from heap
|
|
489
|
-
this.
|
|
1385
|
+
this._startTask(task);
|
|
490
1386
|
} else {
|
|
491
1387
|
// Can't start due to delay - check if there are any bypass tasks in the heap
|
|
492
1388
|
const heapArray = this.readyHeap.heap.slice(); // Copy heap array
|
|
@@ -503,7 +1399,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
503
1399
|
for (const t of remainingTasks) {
|
|
504
1400
|
this.readyHeap.push(t);
|
|
505
1401
|
}
|
|
506
|
-
this.
|
|
1402
|
+
this._expireTask(bypassTask);
|
|
507
1403
|
// Update heapArray for next iteration
|
|
508
1404
|
heapArray.splice(i, 1);
|
|
509
1405
|
i--; // Adjust index since we removed an item
|
|
@@ -519,7 +1415,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
519
1415
|
for (const t of remainingTasks) {
|
|
520
1416
|
this.readyHeap.push(t);
|
|
521
1417
|
}
|
|
522
|
-
this.
|
|
1418
|
+
this._startTask(bypassTask);
|
|
523
1419
|
break;
|
|
524
1420
|
}
|
|
525
1421
|
}
|
|
@@ -535,7 +1431,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
535
1431
|
// Schedule next tick if there are pending tasks or tasks that might become available
|
|
536
1432
|
// Note: For smart scheduling, this is handled by runScheduler calling scheduleSmartTimeout
|
|
537
1433
|
if (!this.options.smartScheduling && (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0 || hasWaitingTasks)) {
|
|
538
|
-
this.
|
|
1434
|
+
this._scheduleNextTick();
|
|
539
1435
|
}
|
|
540
1436
|
}
|
|
541
1437
|
|
|
@@ -544,8 +1440,9 @@ export class HoldMyTask extends EventEmitter {
|
|
|
544
1440
|
* @param {Object} item - The expired task item
|
|
545
1441
|
* @returns {void}
|
|
546
1442
|
* @private
|
|
1443
|
+
* @internal
|
|
547
1444
|
*/
|
|
548
|
-
|
|
1445
|
+
_expireTask(item) {
|
|
549
1446
|
if (item.status === "expired" || item.status === "canceled" || item.status === "completed") {
|
|
550
1447
|
return; // Already handled
|
|
551
1448
|
}
|
|
@@ -578,8 +1475,9 @@ export class HoldMyTask extends EventEmitter {
|
|
|
578
1475
|
* @param {Object} item - The task item to execute
|
|
579
1476
|
* @returns {Promise<void>}
|
|
580
1477
|
* @private
|
|
1478
|
+
* @internal
|
|
581
1479
|
*/
|
|
582
|
-
async
|
|
1480
|
+
async _startTask(item) {
|
|
583
1481
|
if (item.status !== "ready") return;
|
|
584
1482
|
|
|
585
1483
|
// For promise API, check if signal is already aborted
|
|
@@ -681,8 +1579,8 @@ export class HoldMyTask extends EventEmitter {
|
|
|
681
1579
|
// Update delay tracking after task completion
|
|
682
1580
|
const completedPriority = item.priority;
|
|
683
1581
|
const taskDelay = item.delay;
|
|
684
|
-
const
|
|
685
|
-
const delay = taskDelay !== undefined ? taskDelay :
|
|
1582
|
+
const priorityDelay = this.options.priorities[completedPriority]?.postDelay ?? 0;
|
|
1583
|
+
const delay = taskDelay !== undefined ? taskDelay : priorityDelay;
|
|
686
1584
|
if (delay > 0) {
|
|
687
1585
|
this.lastCompletedPriority = completedPriority;
|
|
688
1586
|
this.nextAvailableTime = this.now() + delay;
|
|
@@ -747,7 +1645,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
747
1645
|
|
|
748
1646
|
// Check if we have ready tasks that can run immediately
|
|
749
1647
|
if (this.readyHeap.size() > 0 && this.running.size < this.options.concurrency) {
|
|
750
|
-
const delay = this.lastCompletedPriority !== null ? this.options.
|
|
1648
|
+
const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
|
|
751
1649
|
const delayActive = delay > 0 && now < this.nextAvailableTime;
|
|
752
1650
|
|
|
753
1651
|
if (!delayActive) {
|
|
@@ -857,4 +1755,304 @@ export class HoldMyTask extends EventEmitter {
|
|
|
857
1755
|
this.healingInterval = null;
|
|
858
1756
|
}
|
|
859
1757
|
}
|
|
1758
|
+
|
|
1759
|
+
/**
|
|
1760
|
+
* Configure coalescing settings for specific keys dynamically.
|
|
1761
|
+
* @param {string} coalescingKey - The coalescing key to configure
|
|
1762
|
+
* @param {Object} config - Configuration for this key
|
|
1763
|
+
* @param {number} [config.windowDuration] - Window duration in milliseconds for this key
|
|
1764
|
+
* @param {number} [config.maxDelay] - Maximum delay in milliseconds for this key
|
|
1765
|
+
* @param {number} [config.postDelay] - Post-completion delay in milliseconds for this key
|
|
1766
|
+
* @param {number} [config.startDelay] - Pre-execution delay in milliseconds for this key
|
|
1767
|
+
* @param {number} [config.delay] - DEPRECATED: Use postDelay instead
|
|
1768
|
+
* @param {number} [config.start] - DEPRECATED: Use startDelay instead
|
|
1769
|
+
* @param {boolean} [config.multipleCallbacks] - Whether to call multiple callbacks for this key
|
|
1770
|
+
* @param {boolean} [config.resolveAllPromises] - Whether to resolve all promises for this key
|
|
1771
|
+
* @returns {void}
|
|
1772
|
+
*
|
|
1773
|
+
* @example
|
|
1774
|
+
* // Configure specific keys after queue creation
|
|
1775
|
+
* queue.configureCoalescingKey('ui.update', {
|
|
1776
|
+
* windowDuration: 100,
|
|
1777
|
+
* maxDelay: 500,
|
|
1778
|
+
* postDelay: 25,
|
|
1779
|
+
* startDelay: 0
|
|
1780
|
+
* });
|
|
1781
|
+
*
|
|
1782
|
+
* queue.configureCoalescingKey('api.batch', {
|
|
1783
|
+
* windowDuration: 1000,
|
|
1784
|
+
* maxDelay: 5000,
|
|
1785
|
+
* postDelay: 100,
|
|
1786
|
+
* startDelay: 200,
|
|
1787
|
+
* resolveAllPromises: false
|
|
1788
|
+
* });
|
|
1789
|
+
*/
|
|
1790
|
+
configureCoalescingKey(coalescingKey, config) {
|
|
1791
|
+
if (typeof coalescingKey !== "string") {
|
|
1792
|
+
const error = new Error("coalescingKey must be a string");
|
|
1793
|
+
setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
if (typeof config !== "object" || config === null) {
|
|
1797
|
+
const error = new Error("config must be an object");
|
|
1798
|
+
setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// Validate configuration options (accept both old and new property names)
|
|
1803
|
+
const validKeys = [
|
|
1804
|
+
"windowDuration",
|
|
1805
|
+
"maxDelay",
|
|
1806
|
+
"delay",
|
|
1807
|
+
"start",
|
|
1808
|
+
"postDelay",
|
|
1809
|
+
"startDelay",
|
|
1810
|
+
"multipleCallbacks",
|
|
1811
|
+
"resolveAllPromises"
|
|
1812
|
+
];
|
|
1813
|
+
const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
|
|
1814
|
+
if (invalidKeys.length > 0) {
|
|
1815
|
+
const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
|
|
1816
|
+
setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config, invalidKeys }));
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// Transform old property names to new ones for backwards compatibility
|
|
1821
|
+
const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
|
|
1822
|
+
|
|
1823
|
+
// Merge with existing configuration for this key
|
|
1824
|
+
this.options.coalescing.keys[coalescingKey] = {
|
|
1825
|
+
...this.options.coalescing.keys[coalescingKey],
|
|
1826
|
+
...transformedConfig
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
/**
|
|
1831
|
+
* Get the effective coalescing configuration for a specific key.
|
|
1832
|
+
* @param {string} coalescingKey - The coalescing key to get configuration for
|
|
1833
|
+
* @param {Object} [taskOptions={}] - Task-level options that may override key configuration
|
|
1834
|
+
* @returns {Object} The effective configuration for this key
|
|
1835
|
+
*
|
|
1836
|
+
* @example
|
|
1837
|
+
* // Get effective configuration for a key
|
|
1838
|
+
* const config = queue.getCoalescingConfig('ui.update');
|
|
1839
|
+
* console.log(`UI updates coalesce within ${config.windowDuration}ms with ${config.postDelay}ms post-completion delay`);
|
|
1840
|
+
*
|
|
1841
|
+
* // Check with task-level overrides
|
|
1842
|
+
* const effectiveConfig = queue.getCoalescingConfig('ui.update', {
|
|
1843
|
+
* coalescingWindowDuration: 50,
|
|
1844
|
+
* delay: 30 // Still accepts old property names for backwards compatibility
|
|
1845
|
+
* });
|
|
1846
|
+
*/
|
|
1847
|
+
getCoalescingConfig(coalescingKey, taskOptions = {}) {
|
|
1848
|
+
const keyConfig = (this.options.coalescing.keys && this.options.coalescing.keys[coalescingKey]) || {};
|
|
1849
|
+
const defaults = this.options.coalescing.defaults;
|
|
1850
|
+
const priorityConfig = this.getPriorityConfig(taskOptions.priority ?? this.options.defaultPriority);
|
|
1851
|
+
|
|
1852
|
+
const postDelay = taskOptions.delay ?? keyConfig.postDelay ?? priorityConfig.postDelay ?? defaults.postDelay;
|
|
1853
|
+
const startDelay = taskOptions.start ?? keyConfig.startDelay ?? priorityConfig.startDelay ?? defaults.startDelay;
|
|
1854
|
+
|
|
1855
|
+
return {
|
|
1856
|
+
windowDuration: taskOptions.coalescingWindowDuration ?? keyConfig.windowDuration ?? defaults.windowDuration,
|
|
1857
|
+
maxDelay: taskOptions.coalescingMaxDelay ?? keyConfig.maxDelay ?? defaults.maxDelay,
|
|
1858
|
+
// New clear property names
|
|
1859
|
+
postDelay,
|
|
1860
|
+
startDelay,
|
|
1861
|
+
// Old property names for backwards compatibility
|
|
1862
|
+
delay: postDelay,
|
|
1863
|
+
start: startDelay,
|
|
1864
|
+
multipleCallbacks: taskOptions.coalescingMultipleCallbacks ?? keyConfig.multipleCallbacks ?? defaults.multipleCallbacks,
|
|
1865
|
+
resolveAllPromises: taskOptions.coalescingResolveAllPromises ?? keyConfig.resolveAllPromises ?? defaults.resolveAllPromises
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* Get all configured coalescing keys and their configurations.
|
|
1871
|
+
* @returns {Object} Map of coalescingKey to configuration
|
|
1872
|
+
*
|
|
1873
|
+
* @example
|
|
1874
|
+
* // See all configured coalescing keys
|
|
1875
|
+
* const allConfigs = queue.getCoalescingConfigurations();
|
|
1876
|
+
* Object.entries(allConfigs).forEach(([key, config]) => {
|
|
1877
|
+
* console.log(`${key}: ${config.windowDuration}ms window, ${config.maxDelay}ms max delay, ${config.postDelay}ms post-completion delay, ${config.startDelay}ms pre-execution delay`);
|
|
1878
|
+
* });
|
|
1879
|
+
*/
|
|
1880
|
+
getCoalescingConfigurations() {
|
|
1881
|
+
const result = {};
|
|
1882
|
+
for (const key of Object.keys(this.options.coalescing.keys)) {
|
|
1883
|
+
result[key] = this.getCoalescingConfig(key);
|
|
1884
|
+
}
|
|
1885
|
+
return result;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
/**
|
|
1889
|
+
* Configure default settings for specific priorities dynamically.
|
|
1890
|
+
* @param {number} priority - The priority level to configure
|
|
1891
|
+
* @param {Object} config - Configuration for this priority
|
|
1892
|
+
* @param {number} [config.postDelay] - Default post-completion delay in milliseconds for this priority
|
|
1893
|
+
* @param {number} [config.startDelay] - Default pre-execution delay in milliseconds for this priority
|
|
1894
|
+
* @param {number} [config.delay] - DEPRECATED: Use postDelay instead
|
|
1895
|
+
* @param {number} [config.start] - DEPRECATED: Use startDelay instead
|
|
1896
|
+
* @returns {void}
|
|
1897
|
+
*
|
|
1898
|
+
* @example
|
|
1899
|
+
* // Configure priority defaults after queue creation
|
|
1900
|
+
* queue.configurePriority(1, {
|
|
1901
|
+
* postDelay: 100, // High priority tasks have 100ms delay after completion
|
|
1902
|
+
* startDelay: 0 // High priority tasks start immediately
|
|
1903
|
+
* });
|
|
1904
|
+
*
|
|
1905
|
+
* queue.configurePriority(3, {
|
|
1906
|
+
* postDelay: 0, // Low priority tasks have no delay after completion
|
|
1907
|
+
* startDelay: 200 // Low priority tasks wait 200ms before starting
|
|
1908
|
+
* });
|
|
1909
|
+
*/
|
|
1910
|
+
configurePriority(priority, config) {
|
|
1911
|
+
if (typeof priority !== "number") {
|
|
1912
|
+
const error = new Error("priority must be a number");
|
|
1913
|
+
setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
|
|
1914
|
+
return;
|
|
1915
|
+
}
|
|
1916
|
+
if (typeof config !== "object" || config === null) {
|
|
1917
|
+
const error = new Error("config must be an object");
|
|
1918
|
+
setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// Validate configuration options (accept both old and new property names)
|
|
1923
|
+
const validKeys = ["delay", "start", "postDelay", "startDelay"];
|
|
1924
|
+
const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
|
|
1925
|
+
if (invalidKeys.length > 0) {
|
|
1926
|
+
const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
|
|
1927
|
+
setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config, invalidKeys }));
|
|
1928
|
+
return;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
// Transform old property names to new ones for backwards compatibility
|
|
1932
|
+
const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
|
|
1933
|
+
|
|
1934
|
+
// Merge with existing configuration for this priority
|
|
1935
|
+
this.options.priorities[priority] = {
|
|
1936
|
+
...this.options.priorities[priority],
|
|
1937
|
+
...transformedConfig
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
/**
|
|
1942
|
+
* Get the effective configuration for a specific priority.
|
|
1943
|
+
* @param {number} priority - The priority level to get configuration for
|
|
1944
|
+
* @param {Object} [taskOptions={}] - Task-level options that may override priority configuration
|
|
1945
|
+
* @returns {Object} The effective configuration for this priority
|
|
1946
|
+
*
|
|
1947
|
+
* @example
|
|
1948
|
+
* // Get effective configuration for a priority
|
|
1949
|
+
* const config = queue.getPriorityConfig(1);
|
|
1950
|
+
* console.log(`Priority 1 tasks: ${config.delay}ms delay, ${config.start}ms start delay`);
|
|
1951
|
+
*
|
|
1952
|
+
* // Check with task-level overrides
|
|
1953
|
+
* const effectiveConfig = queue.getPriorityConfig(1, {
|
|
1954
|
+
* delay: 50,
|
|
1955
|
+
* start: 10
|
|
1956
|
+
* });
|
|
1957
|
+
*/
|
|
1958
|
+
getPriorityConfig(priority, taskOptions = {}) {
|
|
1959
|
+
const priorityConfig = this.options.priorities[priority] || {};
|
|
1960
|
+
|
|
1961
|
+
const postDelay = taskOptions.delay ?? priorityConfig.postDelay;
|
|
1962
|
+
const startDelay = taskOptions.start ?? priorityConfig.startDelay;
|
|
1963
|
+
|
|
1964
|
+
return {
|
|
1965
|
+
// New clear property names
|
|
1966
|
+
postDelay,
|
|
1967
|
+
startDelay,
|
|
1968
|
+
// Old property names for backwards compatibility
|
|
1969
|
+
delay: postDelay,
|
|
1970
|
+
start: startDelay
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
/**
|
|
1975
|
+
* Get all configured priorities and their configurations.
|
|
1976
|
+
* @returns {Object} Map of priority to configuration
|
|
1977
|
+
*
|
|
1978
|
+
* @example
|
|
1979
|
+
* // See all configured priorities
|
|
1980
|
+
* const allConfigs = queue.getPriorityConfigurations();
|
|
1981
|
+
* Object.entries(allConfigs).forEach(([priority, config]) => {
|
|
1982
|
+
* console.log(`Priority ${priority}: ${config.delay}ms delay, ${config.start}ms start delay`);
|
|
1983
|
+
* });
|
|
1984
|
+
*/
|
|
1985
|
+
getPriorityConfigurations() {
|
|
1986
|
+
const result = {};
|
|
1987
|
+
for (const priority of Object.keys(this.options.priorities)) {
|
|
1988
|
+
result[priority] = this.getPriorityConfig(parseInt(priority));
|
|
1989
|
+
}
|
|
1990
|
+
return result;
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
/**
|
|
1994
|
+
* Alias for destroy() method for common queue system naming.
|
|
1995
|
+
* @returns {void}
|
|
1996
|
+
*/
|
|
1997
|
+
shutdown() {
|
|
1998
|
+
return this.destroy();
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
/**
|
|
2002
|
+
* Alias for enqueue() method for common queue system naming.
|
|
2003
|
+
* @param {Function} task - The task function to execute
|
|
2004
|
+
* @param {Function|Object} optionsOrCallback - Callback function or options object
|
|
2005
|
+
* @param {Object} options - Task options (if callback provided as second parameter)
|
|
2006
|
+
* @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
|
|
2007
|
+
*/
|
|
2008
|
+
schedule(task, optionsOrCallback, options = {}) {
|
|
2009
|
+
return this.enqueue(task, optionsOrCallback, options);
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
/**
|
|
2013
|
+
* Alias for enqueue() method for common queue system naming.
|
|
2014
|
+
* @param {Function} task - The task function to execute
|
|
2015
|
+
* @param {Function|Object} optionsOrCallback - Callback function or options object
|
|
2016
|
+
* @param {Object} options - Task options (if callback provided as second parameter)
|
|
2017
|
+
* @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
|
|
2018
|
+
*/
|
|
2019
|
+
add(task, optionsOrCallback, options = {}) {
|
|
2020
|
+
return this.enqueue(task, optionsOrCallback, options);
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
/**
|
|
2024
|
+
* Find a task by its ID.
|
|
2025
|
+
* @param {string|number} id - The task ID to find
|
|
2026
|
+
* @returns {Object|null} Task object if found, null otherwise
|
|
2027
|
+
*/
|
|
2028
|
+
get(id) {
|
|
2029
|
+
return this.tasks.get(String(id)) || null;
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
/**
|
|
2033
|
+
* Check if a task with the given ID exists.
|
|
2034
|
+
* @param {string|number} id - The task ID to check
|
|
2035
|
+
* @returns {boolean} True if task exists, false otherwise
|
|
2036
|
+
*/
|
|
2037
|
+
has(id) {
|
|
2038
|
+
return this.tasks.has(String(id));
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
/**
|
|
2042
|
+
* Alias for get() method for backward compatibility.
|
|
2043
|
+
* @param {string|number} id - The task ID to find
|
|
2044
|
+
* @returns {Object|null} Task object if found, null otherwise
|
|
2045
|
+
*/
|
|
2046
|
+
getTask(id) {
|
|
2047
|
+
return this.get(id);
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Alias for has() method for backward compatibility.
|
|
2052
|
+
* @param {string|number} id - The task ID to check
|
|
2053
|
+
* @returns {boolean} True if task exists, false otherwise
|
|
2054
|
+
*/
|
|
2055
|
+
hasTask(id) {
|
|
2056
|
+
return this.has(id);
|
|
2057
|
+
}
|
|
860
2058
|
}
|