observed-js 0.1.0 → 0.2.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 +86 -562
- package/dist/actions/index.d.ts +148 -1
- package/dist/actions/index.d.ts.map +1 -1
- package/dist/actions/index.js +739 -84
- package/dist/actions/index.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/scheduler/index.d.ts +74 -2
- package/dist/scheduler/index.d.ts.map +1 -1
- package/dist/scheduler/index.js +198 -5
- package/dist/scheduler/index.js.map +1 -1
- package/package.json +6 -3
package/dist/actions/index.js
CHANGED
|
@@ -1,12 +1,104 @@
|
|
|
1
1
|
import { ExecutionScheduler } from "../scheduler/index.js";
|
|
2
|
+
const PRIORITY_VALUES = {
|
|
3
|
+
low: 0,
|
|
4
|
+
normal: 50,
|
|
5
|
+
high: 75,
|
|
6
|
+
critical: 100
|
|
7
|
+
};
|
|
8
|
+
const isPlainObject = (value) => {
|
|
9
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
10
|
+
};
|
|
11
|
+
const isInvokeOptions = (value) => {
|
|
12
|
+
if (!isPlainObject(value)) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
const maybe = value;
|
|
16
|
+
const hasPriority = Object.prototype.hasOwnProperty.call(maybe, 'priority');
|
|
17
|
+
const hasMetadata = Object.prototype.hasOwnProperty.call(maybe, 'metadata');
|
|
18
|
+
if (!hasPriority && !hasMetadata) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
if (hasPriority) {
|
|
22
|
+
const p = maybe.priority;
|
|
23
|
+
if (p !== undefined && typeof p !== 'string' && typeof p !== 'number') {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (hasMetadata) {
|
|
28
|
+
const m = maybe.metadata;
|
|
29
|
+
if (m !== undefined && !isPlainObject(m)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return true;
|
|
34
|
+
};
|
|
35
|
+
const normalizePriority = (priority) => {
|
|
36
|
+
if (priority === undefined) {
|
|
37
|
+
return PRIORITY_VALUES.normal;
|
|
38
|
+
}
|
|
39
|
+
if (typeof priority === 'string') {
|
|
40
|
+
const mapped = PRIORITY_VALUES[priority];
|
|
41
|
+
if (mapped === undefined) {
|
|
42
|
+
throw new Error(`Unknown priority level: ${priority}`);
|
|
43
|
+
}
|
|
44
|
+
return mapped;
|
|
45
|
+
}
|
|
46
|
+
if (typeof priority !== 'number' || !Number.isFinite(priority)) {
|
|
47
|
+
throw new Error('Priority must be a finite number');
|
|
48
|
+
}
|
|
49
|
+
if (priority < 0 || priority > 100) {
|
|
50
|
+
throw new Error('Priority must be in range [0, 100]');
|
|
51
|
+
}
|
|
52
|
+
return priority;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Error thrown when an operation times out
|
|
56
|
+
*/
|
|
57
|
+
export class TimeoutError extends Error {
|
|
58
|
+
name = 'TimeoutError';
|
|
59
|
+
duration;
|
|
60
|
+
constructor(duration) {
|
|
61
|
+
super(`Operation timed out after ${duration}ms`);
|
|
62
|
+
this.duration = duration;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Error thrown when an operation is cancelled
|
|
67
|
+
*/
|
|
68
|
+
export class CancellationError extends Error {
|
|
69
|
+
name = 'CancellationError';
|
|
70
|
+
reason;
|
|
71
|
+
state;
|
|
72
|
+
constructor(reason, state) {
|
|
73
|
+
super(reason || 'Task was cancelled');
|
|
74
|
+
if (reason !== undefined) {
|
|
75
|
+
this.reason = reason;
|
|
76
|
+
}
|
|
77
|
+
this.state = state || 'running';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
2
80
|
/**
|
|
3
81
|
* Internal implementation of InvocationContext
|
|
4
82
|
*/
|
|
5
83
|
class InvocationContextImpl {
|
|
6
84
|
actionId;
|
|
7
85
|
attachmentsMap = {};
|
|
8
|
-
|
|
86
|
+
// Progress tracking state
|
|
87
|
+
progressTotal = 0;
|
|
88
|
+
progressCompleted = 0;
|
|
89
|
+
progressStartTime = 0;
|
|
90
|
+
lastProgressEmitTime = 0;
|
|
91
|
+
lastProgressPercentage = 0;
|
|
92
|
+
progressRate = 0;
|
|
93
|
+
progressCallback;
|
|
94
|
+
progressThrottle = 100; // ms
|
|
95
|
+
constructor(actionId, progressCallback, progressThrottle) {
|
|
9
96
|
this.actionId = actionId;
|
|
97
|
+
this.progressCallback = progressCallback;
|
|
98
|
+
if (progressThrottle !== undefined) {
|
|
99
|
+
this.progressThrottle = progressThrottle;
|
|
100
|
+
}
|
|
101
|
+
this.progressStartTime = Date.now();
|
|
10
102
|
}
|
|
11
103
|
attach(keyOrData, value) {
|
|
12
104
|
if (typeof keyOrData === 'string') {
|
|
@@ -53,6 +145,89 @@ class InvocationContextImpl {
|
|
|
53
145
|
getAttachments() {
|
|
54
146
|
return { ...this.attachmentsMap };
|
|
55
147
|
}
|
|
148
|
+
setTotal(total) {
|
|
149
|
+
if (total < 0) {
|
|
150
|
+
throw new Error('Progress total must be >= 0');
|
|
151
|
+
}
|
|
152
|
+
this.progressTotal = total;
|
|
153
|
+
// Reset progress when total is set
|
|
154
|
+
this.progressCompleted = 0;
|
|
155
|
+
this.progressStartTime = Date.now();
|
|
156
|
+
this.lastProgressEmitTime = 0;
|
|
157
|
+
this.lastProgressPercentage = 0;
|
|
158
|
+
this.progressRate = 0;
|
|
159
|
+
// Emit initial progress (0%)
|
|
160
|
+
this.emitProgress();
|
|
161
|
+
}
|
|
162
|
+
reportProgress(completed, current) {
|
|
163
|
+
if (completed < 0) {
|
|
164
|
+
throw new Error('Progress completed must be >= 0');
|
|
165
|
+
}
|
|
166
|
+
this.progressCompleted = Math.min(completed, this.progressTotal);
|
|
167
|
+
this.emitProgress(current);
|
|
168
|
+
}
|
|
169
|
+
incrementProgress(current) {
|
|
170
|
+
this.progressCompleted = Math.min(this.progressCompleted + 1, this.progressTotal);
|
|
171
|
+
this.emitProgress(current);
|
|
172
|
+
}
|
|
173
|
+
emitProgress(current) {
|
|
174
|
+
if (!this.progressCallback || this.progressTotal === 0) {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const now = Date.now();
|
|
178
|
+
const elapsedTime = now - this.progressStartTime;
|
|
179
|
+
const percentage = this.progressTotal > 0
|
|
180
|
+
? Math.round((this.progressCompleted / this.progressTotal) * 100)
|
|
181
|
+
: 0;
|
|
182
|
+
// Determine if we should emit
|
|
183
|
+
const isComplete = this.progressCompleted >= this.progressTotal;
|
|
184
|
+
const isStart = this.progressCompleted === 0;
|
|
185
|
+
const timeSinceLastEmit = now - this.lastProgressEmitTime;
|
|
186
|
+
const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
|
|
187
|
+
const significantChange = Math.abs(percentage - this.lastProgressPercentage) >= 5;
|
|
188
|
+
// Always emit on 0% or 100%, or if throttle passed, or significant change
|
|
189
|
+
if (!isStart && !isComplete && shouldThrottle && !significantChange) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
// Calculate rate (items per second) with exponential smoothing
|
|
193
|
+
const currentRate = elapsedTime > 0 ? (this.progressCompleted / (elapsedTime / 1000)) : 0;
|
|
194
|
+
if (this.progressRate === 0) {
|
|
195
|
+
this.progressRate = currentRate;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
this.progressRate = 0.7 * this.progressRate + 0.3 * currentRate;
|
|
199
|
+
}
|
|
200
|
+
// Calculate ETA
|
|
201
|
+
const remaining = this.progressTotal - this.progressCompleted;
|
|
202
|
+
const estimatedTimeRemaining = this.progressRate > 0
|
|
203
|
+
? Math.round((remaining / this.progressRate) * 1000)
|
|
204
|
+
: undefined;
|
|
205
|
+
const progress = {
|
|
206
|
+
completed: this.progressCompleted,
|
|
207
|
+
total: this.progressTotal,
|
|
208
|
+
percentage,
|
|
209
|
+
...(current !== undefined ? { current } : {}),
|
|
210
|
+
...(this.progressRate > 0 ? { rate: Math.round(this.progressRate * 100) / 100 } : {}),
|
|
211
|
+
...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
|
|
212
|
+
startTime: this.progressStartTime,
|
|
213
|
+
elapsedTime
|
|
214
|
+
};
|
|
215
|
+
this.lastProgressEmitTime = now;
|
|
216
|
+
this.lastProgressPercentage = percentage;
|
|
217
|
+
// Fire callback (errors in callback are isolated)
|
|
218
|
+
try {
|
|
219
|
+
this.progressCallback(progress);
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
console.error('Error in progress callback:', error);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
getProgressState() {
|
|
226
|
+
return {
|
|
227
|
+
completed: this.progressCompleted,
|
|
228
|
+
total: this.progressTotal
|
|
229
|
+
};
|
|
230
|
+
}
|
|
56
231
|
}
|
|
57
232
|
export class ActionBuilder {
|
|
58
233
|
/** The execution scheduler for concurrency and rate limiting */
|
|
@@ -65,12 +240,29 @@ export class ActionBuilder {
|
|
|
65
240
|
usesContext = false;
|
|
66
241
|
/** Retry configuration */
|
|
67
242
|
retryOptions;
|
|
243
|
+
/** Timeout configuration */
|
|
244
|
+
timeoutConfig;
|
|
245
|
+
/** Whether this action uses abort signal (set by withAbortSignal wrapper) */
|
|
246
|
+
usesAbortSignal = false;
|
|
247
|
+
/** Progress callback for all invocations */
|
|
248
|
+
progressCallback;
|
|
249
|
+
/** Progress throttle in milliseconds */
|
|
250
|
+
progressThrottle = 100;
|
|
251
|
+
/** Track all active invocations for cancelAll support */
|
|
252
|
+
activeInvocations = new Map();
|
|
253
|
+
/** Default priority for all invocations (0-100) */
|
|
254
|
+
defaultPriority = PRIORITY_VALUES.normal;
|
|
68
255
|
constructor(handler) {
|
|
69
256
|
// Check if handler was wrapped with withContext
|
|
70
257
|
if (handler.__usesContext && handler.__originalHandler) {
|
|
71
258
|
this.usesContext = true;
|
|
72
259
|
this.callbackHandler = handler.__originalHandler;
|
|
73
260
|
}
|
|
261
|
+
// Check if handler was wrapped with withAbortSignal
|
|
262
|
+
else if (handler.__usesAbortSignal && handler.__originalHandler) {
|
|
263
|
+
this.usesAbortSignal = true;
|
|
264
|
+
this.callbackHandler = handler.__originalHandler;
|
|
265
|
+
}
|
|
74
266
|
else {
|
|
75
267
|
this.callbackHandler = handler;
|
|
76
268
|
}
|
|
@@ -92,6 +284,14 @@ export class ActionBuilder {
|
|
|
92
284
|
this.scheduler.setRateLimit(rateLimit);
|
|
93
285
|
return this;
|
|
94
286
|
}
|
|
287
|
+
/**
|
|
288
|
+
* Set default priority for all invocations of this action.
|
|
289
|
+
* Higher priority executes first; FIFO ordering preserved within same priority.
|
|
290
|
+
*/
|
|
291
|
+
setPriority(priority) {
|
|
292
|
+
this.defaultPriority = normalizePriority(priority);
|
|
293
|
+
return this;
|
|
294
|
+
}
|
|
95
295
|
/**
|
|
96
296
|
* Configure retry behavior for failed executions
|
|
97
297
|
* @param options Retry configuration
|
|
@@ -110,6 +310,22 @@ export class ActionBuilder {
|
|
|
110
310
|
this.retryOptions = options;
|
|
111
311
|
return this;
|
|
112
312
|
}
|
|
313
|
+
/**
|
|
314
|
+
* Configure timeout for executions
|
|
315
|
+
* @param options Timeout duration in ms or configuration object
|
|
316
|
+
*/
|
|
317
|
+
setTimeout(options) {
|
|
318
|
+
// Normalize to TimeoutOptions
|
|
319
|
+
const config = typeof options === 'number'
|
|
320
|
+
? { duration: options }
|
|
321
|
+
: options;
|
|
322
|
+
// Validate configuration
|
|
323
|
+
if (config.duration <= 0) {
|
|
324
|
+
throw new Error('Timeout duration must be positive');
|
|
325
|
+
}
|
|
326
|
+
this.timeoutConfig = config;
|
|
327
|
+
return this;
|
|
328
|
+
}
|
|
113
329
|
/**
|
|
114
330
|
* Register a callback to receive wide events after each invocation
|
|
115
331
|
* @param callback Function to receive wide events
|
|
@@ -118,6 +334,21 @@ export class ActionBuilder {
|
|
|
118
334
|
this.eventCallback = callback;
|
|
119
335
|
return this;
|
|
120
336
|
}
|
|
337
|
+
/**
|
|
338
|
+
* Register a callback to receive progress updates
|
|
339
|
+
* @param callback Function to receive progress updates
|
|
340
|
+
* @param options Progress options (throttle)
|
|
341
|
+
*/
|
|
342
|
+
onProgress(callback, options) {
|
|
343
|
+
this.progressCallback = callback;
|
|
344
|
+
if (options?.throttle !== undefined) {
|
|
345
|
+
if (options.throttle < 0) {
|
|
346
|
+
throw new Error('Progress throttle must be >= 0');
|
|
347
|
+
}
|
|
348
|
+
this.progressThrottle = options.throttle;
|
|
349
|
+
}
|
|
350
|
+
return this;
|
|
351
|
+
}
|
|
121
352
|
/**
|
|
122
353
|
* Mark this action as using context (internal - called by withContext)
|
|
123
354
|
*/
|
|
@@ -149,20 +380,157 @@ export class ActionBuilder {
|
|
|
149
380
|
/**
|
|
150
381
|
* Execute handler with retry logic
|
|
151
382
|
*/
|
|
152
|
-
async executeWithRetry(context, payload, actionId, startedAt, emitIntermediateEvents = false) {
|
|
383
|
+
async executeWithRetry(context, payload, actionId, startedAt, priority, metadata, emitIntermediateEvents = false, signal) {
|
|
153
384
|
let result;
|
|
154
385
|
let error;
|
|
155
386
|
const retryDelays = [];
|
|
156
387
|
let attemptNumber = 0;
|
|
157
388
|
const maxAttempts = (this.retryOptions?.maxRetries ?? 0) + 1;
|
|
389
|
+
let timedOut = false;
|
|
390
|
+
let executionTime;
|
|
158
391
|
while (attemptNumber < maxAttempts) {
|
|
392
|
+
// Check for cancellation before each attempt
|
|
393
|
+
if (signal?.aborted) {
|
|
394
|
+
throw new CancellationError(signal.reason || 'Task was cancelled', attemptNumber === 0 ? 'queued' : 'running');
|
|
395
|
+
}
|
|
159
396
|
const isRetry = attemptNumber > 0;
|
|
397
|
+
const attemptStartTime = Date.now();
|
|
160
398
|
try {
|
|
161
|
-
if
|
|
162
|
-
|
|
399
|
+
// Execute with timeout if configured
|
|
400
|
+
if (this.timeoutConfig) {
|
|
401
|
+
const timeoutDuration = this.timeoutConfig.duration;
|
|
402
|
+
const throwOnTimeout = this.timeoutConfig.throwOnTimeout !== false;
|
|
403
|
+
const useAbortSignal = this.timeoutConfig.abortSignal === true;
|
|
404
|
+
if (useAbortSignal && this.usesAbortSignal) {
|
|
405
|
+
// Cooperative cancellation with AbortSignal
|
|
406
|
+
// Create a combined abort controller for timeout + external cancellation
|
|
407
|
+
const timeoutController = new AbortController();
|
|
408
|
+
// Link external cancellation signal to timeout controller
|
|
409
|
+
if (signal) {
|
|
410
|
+
if (signal.aborted) {
|
|
411
|
+
throw new CancellationError(signal.reason || 'Task was cancelled', 'running');
|
|
412
|
+
}
|
|
413
|
+
signal.addEventListener('abort', () => {
|
|
414
|
+
timeoutController.abort(signal.reason);
|
|
415
|
+
}, { once: true });
|
|
416
|
+
}
|
|
417
|
+
const timeoutId = setTimeout(() => {
|
|
418
|
+
timeoutController.abort(new TimeoutError(timeoutDuration));
|
|
419
|
+
}, timeoutDuration);
|
|
420
|
+
try {
|
|
421
|
+
result = await this.callbackHandler(timeoutController.signal, ...payload);
|
|
422
|
+
clearTimeout(timeoutId);
|
|
423
|
+
}
|
|
424
|
+
catch (e) {
|
|
425
|
+
clearTimeout(timeoutId);
|
|
426
|
+
// Check if it was cancelled vs timeout
|
|
427
|
+
if (signal?.aborted) {
|
|
428
|
+
throw new CancellationError(signal.reason || 'Task was cancelled', 'running');
|
|
429
|
+
}
|
|
430
|
+
if (timeoutController.signal.aborted || e instanceof TimeoutError) {
|
|
431
|
+
executionTime = Date.now() - attemptStartTime;
|
|
432
|
+
timedOut = true;
|
|
433
|
+
if (throwOnTimeout) {
|
|
434
|
+
throw new TimeoutError(timeoutDuration);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
throw e;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
// Forced cancellation with Promise.race (timeout + cancellation + handler)
|
|
444
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
445
|
+
setTimeout(() => {
|
|
446
|
+
reject(new TimeoutError(timeoutDuration));
|
|
447
|
+
}, timeoutDuration);
|
|
448
|
+
});
|
|
449
|
+
const cancellationPromise = signal ? new Promise((_, reject) => {
|
|
450
|
+
if (signal.aborted) {
|
|
451
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
signal.addEventListener('abort', () => {
|
|
455
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
|
|
456
|
+
}, { once: true });
|
|
457
|
+
}) : new Promise(() => { }); // Never resolves if no signal
|
|
458
|
+
let handlerPromise;
|
|
459
|
+
if (this.usesContext) {
|
|
460
|
+
handlerPromise = Promise.resolve(this.callbackHandler(context, ...payload));
|
|
461
|
+
}
|
|
462
|
+
else {
|
|
463
|
+
handlerPromise = Promise.resolve(this.callbackHandler(...payload));
|
|
464
|
+
}
|
|
465
|
+
try {
|
|
466
|
+
result = await Promise.race([handlerPromise, timeoutPromise, cancellationPromise]);
|
|
467
|
+
}
|
|
468
|
+
catch (e) {
|
|
469
|
+
if (e instanceof CancellationError) {
|
|
470
|
+
throw e;
|
|
471
|
+
}
|
|
472
|
+
else if (e instanceof TimeoutError) {
|
|
473
|
+
executionTime = Date.now() - attemptStartTime;
|
|
474
|
+
timedOut = true;
|
|
475
|
+
if (throwOnTimeout) {
|
|
476
|
+
throw e;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
throw e;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
163
484
|
}
|
|
164
485
|
else {
|
|
165
|
-
|
|
486
|
+
// No timeout configured, execute normally
|
|
487
|
+
// Check for external cancellation
|
|
488
|
+
if (signal) {
|
|
489
|
+
const cancellationPromise = new Promise((_, reject) => {
|
|
490
|
+
if (signal.aborted) {
|
|
491
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
signal.addEventListener('abort', () => {
|
|
495
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
|
|
496
|
+
}, { once: true });
|
|
497
|
+
});
|
|
498
|
+
let handlerPromise;
|
|
499
|
+
if (this.usesAbortSignal) {
|
|
500
|
+
handlerPromise = Promise.resolve(this.callbackHandler(signal, ...payload));
|
|
501
|
+
}
|
|
502
|
+
else if (this.usesContext) {
|
|
503
|
+
handlerPromise = Promise.resolve(this.callbackHandler(context, ...payload));
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
handlerPromise = Promise.resolve(this.callbackHandler(...payload));
|
|
507
|
+
}
|
|
508
|
+
try {
|
|
509
|
+
result = await Promise.race([handlerPromise, cancellationPromise]);
|
|
510
|
+
}
|
|
511
|
+
catch (e) {
|
|
512
|
+
if (e instanceof CancellationError) {
|
|
513
|
+
throw e;
|
|
514
|
+
}
|
|
515
|
+
else {
|
|
516
|
+
throw e;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
// No signal, execute directly
|
|
522
|
+
if (this.usesAbortSignal) {
|
|
523
|
+
// Create a dummy signal that never aborts
|
|
524
|
+
const dummyController = new AbortController();
|
|
525
|
+
result = await this.callbackHandler(dummyController.signal, ...payload);
|
|
526
|
+
}
|
|
527
|
+
else if (this.usesContext) {
|
|
528
|
+
result = await this.callbackHandler(context, ...payload);
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
result = await this.callbackHandler(...payload);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
166
534
|
}
|
|
167
535
|
// Success!
|
|
168
536
|
error = undefined;
|
|
@@ -196,12 +564,19 @@ export class ActionBuilder {
|
|
|
196
564
|
completedAt,
|
|
197
565
|
duration: completedAt - startedAt,
|
|
198
566
|
input: payload,
|
|
567
|
+
priority,
|
|
568
|
+
...(metadata !== undefined ? { metadata } : {}),
|
|
199
569
|
error,
|
|
200
570
|
attachments: context.getAttachments(),
|
|
201
571
|
retryAttempt: attemptNumber,
|
|
202
572
|
isRetry,
|
|
203
573
|
willRetry: shouldRetry,
|
|
204
|
-
retryDelays: [...retryDelays]
|
|
574
|
+
retryDelays: [...retryDelays],
|
|
575
|
+
...(this.timeoutConfig ? {
|
|
576
|
+
timeout: this.timeoutConfig.duration,
|
|
577
|
+
timedOut,
|
|
578
|
+
...(executionTime !== undefined ? { executionTime } : {})
|
|
579
|
+
} : {})
|
|
205
580
|
};
|
|
206
581
|
try {
|
|
207
582
|
await this.eventCallback(intermediateEvent);
|
|
@@ -218,31 +593,58 @@ export class ActionBuilder {
|
|
|
218
593
|
if (attemptNumber < maxAttempts) {
|
|
219
594
|
const delay = this.calculateRetryDelay(attemptNumber, this.retryOptions);
|
|
220
595
|
retryDelays.push(delay);
|
|
221
|
-
|
|
596
|
+
// Wait for delay with cancellation support
|
|
597
|
+
await new Promise((resolve, reject) => {
|
|
598
|
+
const timeoutId = setTimeout(resolve, delay);
|
|
599
|
+
// Listen for cancellation during retry delay
|
|
600
|
+
if (signal) {
|
|
601
|
+
const abortHandler = () => {
|
|
602
|
+
clearTimeout(timeoutId);
|
|
603
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'retry-delay'));
|
|
604
|
+
};
|
|
605
|
+
if (signal.aborted) {
|
|
606
|
+
clearTimeout(timeoutId);
|
|
607
|
+
reject(new CancellationError(signal.reason || 'Task was cancelled', 'retry-delay'));
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
signal.addEventListener('abort', abortHandler, { once: true });
|
|
611
|
+
}
|
|
612
|
+
});
|
|
222
613
|
}
|
|
223
614
|
}
|
|
224
615
|
}
|
|
225
616
|
if (!error) {
|
|
226
|
-
return { result: result, retryAttempt: attemptNumber, retryDelays };
|
|
617
|
+
return { result: result, retryAttempt: attemptNumber, retryDelays, timedOut, executionTime };
|
|
227
618
|
}
|
|
228
619
|
throw error;
|
|
229
620
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
621
|
+
invoke(...payloadAndMaybeOptions) {
|
|
622
|
+
const lastArg = payloadAndMaybeOptions[payloadAndMaybeOptions.length - 1];
|
|
623
|
+
const options = isInvokeOptions(lastArg) ? lastArg : undefined;
|
|
624
|
+
const payload = (options
|
|
625
|
+
? payloadAndMaybeOptions.slice(0, -1)
|
|
626
|
+
: payloadAndMaybeOptions);
|
|
627
|
+
const invocationMetadata = options?.metadata;
|
|
628
|
+
const priority = normalizePriority(options?.priority ?? this.defaultPriority);
|
|
235
629
|
const actionId = crypto.randomUUID();
|
|
236
630
|
const startedAt = Date.now();
|
|
237
|
-
const context = new InvocationContextImpl(actionId);
|
|
631
|
+
const context = new InvocationContextImpl(actionId, this.progressCallback, this.progressThrottle);
|
|
238
632
|
let eventLoggedResolve;
|
|
239
633
|
let eventLoggedReject;
|
|
240
634
|
const eventLogged = new Promise((resolve, reject) => {
|
|
241
635
|
eventLoggedResolve = resolve;
|
|
242
636
|
eventLoggedReject = reject;
|
|
243
637
|
});
|
|
244
|
-
|
|
245
|
-
|
|
638
|
+
let isCancelled = false;
|
|
639
|
+
let cancellationReason;
|
|
640
|
+
let cancellationState;
|
|
641
|
+
const { promise: data, controller, task } = this.scheduler.schedule(actionId, async (signal) => {
|
|
642
|
+
return await this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal);
|
|
643
|
+
}, { priority });
|
|
644
|
+
// Add catch handler immediately to prevent unhandled rejections
|
|
645
|
+
// This will be overridden by the explicit handlers below
|
|
646
|
+
data.catch(() => {
|
|
647
|
+
// Intentionally empty - errors handled below
|
|
246
648
|
});
|
|
247
649
|
// Attach handlers to emit the final wide event
|
|
248
650
|
data.then(async (execResult) => {
|
|
@@ -254,12 +656,19 @@ export class ActionBuilder {
|
|
|
254
656
|
completedAt,
|
|
255
657
|
duration: completedAt - startedAt,
|
|
256
658
|
input: payload,
|
|
659
|
+
priority,
|
|
660
|
+
...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
|
|
257
661
|
output: execResult.result,
|
|
258
662
|
attachments: context.getAttachments(),
|
|
259
663
|
retryAttempt: execResult.retryAttempt,
|
|
260
664
|
isRetry: execResult.retryAttempt > 0,
|
|
261
665
|
totalAttempts: execResult.retryAttempt + 1,
|
|
262
|
-
retryDelays: execResult.retryDelays
|
|
666
|
+
retryDelays: execResult.retryDelays,
|
|
667
|
+
...(this.timeoutConfig ? {
|
|
668
|
+
timeout: this.timeoutConfig.duration,
|
|
669
|
+
timedOut: execResult.timedOut,
|
|
670
|
+
...(execResult.executionTime !== undefined ? { executionTime: execResult.executionTime } : {})
|
|
671
|
+
} : {})
|
|
263
672
|
};
|
|
264
673
|
// Fire event callback (if registered)
|
|
265
674
|
if (this.eventCallback) {
|
|
@@ -276,79 +685,210 @@ export class ActionBuilder {
|
|
|
276
685
|
eventLoggedResolve();
|
|
277
686
|
}
|
|
278
687
|
}, async (error) => {
|
|
279
|
-
// Error path -
|
|
280
|
-
|
|
688
|
+
// Error path - emit cancellation event if cancelled
|
|
689
|
+
if (error instanceof CancellationError) {
|
|
690
|
+
const completedAt = Date.now();
|
|
691
|
+
const wideEvent = {
|
|
692
|
+
actionId,
|
|
693
|
+
startedAt,
|
|
694
|
+
completedAt,
|
|
695
|
+
duration: completedAt - startedAt,
|
|
696
|
+
input: payload,
|
|
697
|
+
priority,
|
|
698
|
+
...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
|
|
699
|
+
error,
|
|
700
|
+
attachments: context.getAttachments(),
|
|
701
|
+
cancelled: true,
|
|
702
|
+
...(error.reason !== undefined ? { cancelReason: error.reason } : {}),
|
|
703
|
+
cancelledAt: error.state
|
|
704
|
+
};
|
|
705
|
+
if (this.eventCallback) {
|
|
706
|
+
try {
|
|
707
|
+
await this.eventCallback(wideEvent);
|
|
708
|
+
}
|
|
709
|
+
catch (callbackError) {
|
|
710
|
+
console.error('Error in event callback:', callbackError);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
281
714
|
eventLoggedResolve();
|
|
282
715
|
});
|
|
283
|
-
|
|
716
|
+
// Create cancel function
|
|
717
|
+
const cancel = (reason) => {
|
|
718
|
+
if (isCancelled) {
|
|
719
|
+
return; // Already cancelled
|
|
720
|
+
}
|
|
721
|
+
// Try to cancel via scheduler first
|
|
722
|
+
const wasCancelled = this.scheduler.cancel(actionId, reason);
|
|
723
|
+
if (!wasCancelled) {
|
|
724
|
+
// Task already completed or not found, no-op
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
// Only mark as cancelled if scheduler actually cancelled it
|
|
728
|
+
isCancelled = true;
|
|
729
|
+
cancellationReason = reason;
|
|
730
|
+
};
|
|
731
|
+
// Create the data promise that extracts just the result
|
|
732
|
+
const dataPromise = data.then(r => r.result);
|
|
733
|
+
// Add catch handler to prevent unhandled rejection - caller will handle errors
|
|
734
|
+
dataPromise.catch(() => { });
|
|
735
|
+
const handle = {
|
|
284
736
|
actionId,
|
|
285
|
-
data:
|
|
286
|
-
eventLogged
|
|
737
|
+
data: dataPromise,
|
|
738
|
+
eventLogged,
|
|
739
|
+
cancel,
|
|
740
|
+
get cancelled() {
|
|
741
|
+
return isCancelled || task.cancelled;
|
|
742
|
+
},
|
|
743
|
+
get cancelReason() {
|
|
744
|
+
return cancellationReason || task.cancelReason;
|
|
745
|
+
}
|
|
287
746
|
};
|
|
747
|
+
// Track invocation
|
|
748
|
+
this.activeInvocations.set(actionId, handle);
|
|
749
|
+
// Remove from tracking when complete
|
|
750
|
+
data.finally(() => {
|
|
751
|
+
this.activeInvocations.delete(actionId);
|
|
752
|
+
});
|
|
753
|
+
return handle;
|
|
288
754
|
}
|
|
289
|
-
|
|
290
|
-
* Batch invoke - Promise.all style
|
|
291
|
-
* Waits for all invocations to complete and returns results in input order
|
|
292
|
-
* Individual failures don't fail the whole batch
|
|
293
|
-
*/
|
|
294
|
-
async invokeAll(payloads) {
|
|
755
|
+
async invokeAll(payloads, options) {
|
|
295
756
|
if (payloads.length === 0) {
|
|
296
757
|
return [];
|
|
297
758
|
}
|
|
759
|
+
const invocationMetadata = options?.metadata;
|
|
760
|
+
const priority = normalizePriority(options?.priority ?? this.defaultPriority);
|
|
761
|
+
// Create a batch progress tracker if progress callback exists
|
|
762
|
+
let batchCompletedCount = 0;
|
|
763
|
+
const batchStartTime = Date.now();
|
|
764
|
+
let lastBatchProgressEmitTime = 0;
|
|
765
|
+
let lastBatchProgressPercentage = 0;
|
|
766
|
+
let batchProgressRate = 0;
|
|
767
|
+
const emitBatchProgress = () => {
|
|
768
|
+
if (!this.progressCallback) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const now = Date.now();
|
|
772
|
+
const elapsedTime = now - batchStartTime;
|
|
773
|
+
const percentage = Math.round((batchCompletedCount / payloads.length) * 100);
|
|
774
|
+
// Throttle logic
|
|
775
|
+
const isComplete = batchCompletedCount >= payloads.length;
|
|
776
|
+
const isStart = batchCompletedCount === 0;
|
|
777
|
+
const timeSinceLastEmit = now - lastBatchProgressEmitTime;
|
|
778
|
+
const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
|
|
779
|
+
const significantChange = Math.abs(percentage - lastBatchProgressPercentage) >= 5;
|
|
780
|
+
if (!isStart && !isComplete && shouldThrottle && !significantChange) {
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
// Calculate rate with exponential smoothing
|
|
784
|
+
const currentRate = elapsedTime > 0 ? (batchCompletedCount / (elapsedTime / 1000)) : 0;
|
|
785
|
+
if (batchProgressRate === 0) {
|
|
786
|
+
batchProgressRate = currentRate;
|
|
787
|
+
}
|
|
788
|
+
else {
|
|
789
|
+
batchProgressRate = 0.7 * batchProgressRate + 0.3 * currentRate;
|
|
790
|
+
}
|
|
791
|
+
const remaining = payloads.length - batchCompletedCount;
|
|
792
|
+
const estimatedTimeRemaining = batchProgressRate > 0
|
|
793
|
+
? Math.round((remaining / batchProgressRate) * 1000)
|
|
794
|
+
: undefined;
|
|
795
|
+
const progress = {
|
|
796
|
+
completed: batchCompletedCount,
|
|
797
|
+
total: payloads.length,
|
|
798
|
+
percentage,
|
|
799
|
+
...(batchProgressRate > 0 ? { rate: Math.round(batchProgressRate * 100) / 100 } : {}),
|
|
800
|
+
...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
|
|
801
|
+
startTime: batchStartTime,
|
|
802
|
+
elapsedTime
|
|
803
|
+
};
|
|
804
|
+
lastBatchProgressEmitTime = now;
|
|
805
|
+
lastBatchProgressPercentage = percentage;
|
|
806
|
+
try {
|
|
807
|
+
this.progressCallback(progress);
|
|
808
|
+
}
|
|
809
|
+
catch (error) {
|
|
810
|
+
console.error('Error in progress callback:', error);
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
// Emit initial progress (0%)
|
|
814
|
+
if (this.progressCallback) {
|
|
815
|
+
emitBatchProgress();
|
|
816
|
+
}
|
|
298
817
|
const tasks = payloads.map((payload, index) => {
|
|
299
818
|
const actionId = crypto.randomUUID();
|
|
300
819
|
const startedAt = Date.now();
|
|
301
|
-
const context = new InvocationContextImpl(actionId);
|
|
820
|
+
const context = new InvocationContextImpl(actionId, undefined, undefined);
|
|
821
|
+
const { promise, controller } = this.scheduler.schedule(actionId, async (signal) => {
|
|
822
|
+
let result;
|
|
823
|
+
let error;
|
|
824
|
+
let retryAttempt = 0;
|
|
825
|
+
let retryDelays = [];
|
|
826
|
+
let timedOut = false;
|
|
827
|
+
let executionTime;
|
|
828
|
+
try {
|
|
829
|
+
const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal);
|
|
830
|
+
result = execResult.result;
|
|
831
|
+
retryAttempt = execResult.retryAttempt;
|
|
832
|
+
retryDelays = execResult.retryDelays;
|
|
833
|
+
timedOut = execResult.timedOut;
|
|
834
|
+
executionTime = execResult.executionTime;
|
|
835
|
+
return result;
|
|
836
|
+
}
|
|
837
|
+
catch (e) {
|
|
838
|
+
error = e;
|
|
839
|
+
throw e;
|
|
840
|
+
}
|
|
841
|
+
finally {
|
|
842
|
+
// Update batch progress
|
|
843
|
+
batchCompletedCount++;
|
|
844
|
+
emitBatchProgress();
|
|
845
|
+
// Emit final wide event
|
|
846
|
+
const completedAt = Date.now();
|
|
847
|
+
const wideEvent = {
|
|
848
|
+
actionId,
|
|
849
|
+
startedAt,
|
|
850
|
+
completedAt,
|
|
851
|
+
duration: completedAt - startedAt,
|
|
852
|
+
input: payload,
|
|
853
|
+
priority,
|
|
854
|
+
...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
|
|
855
|
+
output: result,
|
|
856
|
+
error,
|
|
857
|
+
attachments: context.getAttachments(),
|
|
858
|
+
...(retryDelays.length > 0 ? {
|
|
859
|
+
retryAttempt,
|
|
860
|
+
isRetry: retryAttempt > 0,
|
|
861
|
+
totalAttempts: retryAttempt + 1,
|
|
862
|
+
retryDelays
|
|
863
|
+
} : {}),
|
|
864
|
+
...(this.timeoutConfig ? {
|
|
865
|
+
timeout: this.timeoutConfig.duration,
|
|
866
|
+
timedOut,
|
|
867
|
+
...(executionTime !== undefined ? { executionTime } : {})
|
|
868
|
+
} : {}),
|
|
869
|
+
...(error instanceof CancellationError ? {
|
|
870
|
+
cancelled: true,
|
|
871
|
+
cancelReason: error.reason,
|
|
872
|
+
cancelledAt: error.state
|
|
873
|
+
} : {})
|
|
874
|
+
};
|
|
875
|
+
if (this.eventCallback) {
|
|
876
|
+
try {
|
|
877
|
+
await this.eventCallback(wideEvent);
|
|
878
|
+
}
|
|
879
|
+
catch (callbackError) {
|
|
880
|
+
console.error('Error in event callback:', callbackError);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}, { priority });
|
|
302
885
|
return {
|
|
303
886
|
actionId,
|
|
304
887
|
index,
|
|
305
888
|
startedAt,
|
|
306
889
|
context,
|
|
307
|
-
promise
|
|
308
|
-
|
|
309
|
-
let error;
|
|
310
|
-
let retryAttempt = 0;
|
|
311
|
-
let retryDelays = [];
|
|
312
|
-
try {
|
|
313
|
-
const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, true);
|
|
314
|
-
result = execResult.result;
|
|
315
|
-
retryAttempt = execResult.retryAttempt;
|
|
316
|
-
retryDelays = execResult.retryDelays;
|
|
317
|
-
return result;
|
|
318
|
-
}
|
|
319
|
-
catch (e) {
|
|
320
|
-
error = e;
|
|
321
|
-
throw e;
|
|
322
|
-
}
|
|
323
|
-
finally {
|
|
324
|
-
// Emit final wide event
|
|
325
|
-
const completedAt = Date.now();
|
|
326
|
-
const wideEvent = {
|
|
327
|
-
actionId,
|
|
328
|
-
startedAt,
|
|
329
|
-
completedAt,
|
|
330
|
-
duration: completedAt - startedAt,
|
|
331
|
-
input: payload,
|
|
332
|
-
output: result,
|
|
333
|
-
error,
|
|
334
|
-
attachments: context.getAttachments(),
|
|
335
|
-
...(retryDelays.length > 0 ? {
|
|
336
|
-
retryAttempt,
|
|
337
|
-
isRetry: retryAttempt > 0,
|
|
338
|
-
totalAttempts: retryAttempt + 1,
|
|
339
|
-
retryDelays
|
|
340
|
-
} : {})
|
|
341
|
-
};
|
|
342
|
-
if (this.eventCallback) {
|
|
343
|
-
try {
|
|
344
|
-
await this.eventCallback(wideEvent);
|
|
345
|
-
}
|
|
346
|
-
catch (callbackError) {
|
|
347
|
-
console.error('Error in event callback:', callbackError);
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
})
|
|
890
|
+
promise,
|
|
891
|
+
controller
|
|
352
892
|
};
|
|
353
893
|
});
|
|
354
894
|
const settledResults = await Promise.allSettled(tasks.map(t => t.promise));
|
|
@@ -372,32 +912,89 @@ export class ActionBuilder {
|
|
|
372
912
|
}
|
|
373
913
|
});
|
|
374
914
|
}
|
|
375
|
-
|
|
376
|
-
* Batch invoke - Async iterator style
|
|
377
|
-
* Yields results as they complete (not in input order)
|
|
378
|
-
* Ideal for processing results as soon as they're available
|
|
379
|
-
*/
|
|
380
|
-
async *invokeStream(payloads) {
|
|
915
|
+
async *invokeStream(payloads, options) {
|
|
381
916
|
if (payloads.length === 0) {
|
|
382
917
|
return;
|
|
383
918
|
}
|
|
919
|
+
const invocationMetadata = options?.metadata;
|
|
920
|
+
const priority = normalizePriority(options?.priority ?? this.defaultPriority);
|
|
921
|
+
// Create a batch progress tracker if progress callback exists
|
|
922
|
+
let batchCompletedCount = 0;
|
|
923
|
+
const batchStartTime = Date.now();
|
|
924
|
+
let lastBatchProgressEmitTime = 0;
|
|
925
|
+
let lastBatchProgressPercentage = 0;
|
|
926
|
+
let batchProgressRate = 0;
|
|
927
|
+
const emitBatchProgress = () => {
|
|
928
|
+
if (!this.progressCallback) {
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
const now = Date.now();
|
|
932
|
+
const elapsedTime = now - batchStartTime;
|
|
933
|
+
const percentage = Math.round((batchCompletedCount / payloads.length) * 100);
|
|
934
|
+
// Throttle logic
|
|
935
|
+
const isComplete = batchCompletedCount >= payloads.length;
|
|
936
|
+
const isStart = batchCompletedCount === 0;
|
|
937
|
+
const timeSinceLastEmit = now - lastBatchProgressEmitTime;
|
|
938
|
+
const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
|
|
939
|
+
const significantChange = Math.abs(percentage - lastBatchProgressPercentage) >= 5;
|
|
940
|
+
if (!isStart && !isComplete && shouldThrottle && !significantChange) {
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
// Calculate rate with exponential smoothing
|
|
944
|
+
const currentRate = elapsedTime > 0 ? (batchCompletedCount / (elapsedTime / 1000)) : 0;
|
|
945
|
+
if (batchProgressRate === 0) {
|
|
946
|
+
batchProgressRate = currentRate;
|
|
947
|
+
}
|
|
948
|
+
else {
|
|
949
|
+
batchProgressRate = 0.7 * batchProgressRate + 0.3 * currentRate;
|
|
950
|
+
}
|
|
951
|
+
const remaining = payloads.length - batchCompletedCount;
|
|
952
|
+
const estimatedTimeRemaining = batchProgressRate > 0
|
|
953
|
+
? Math.round((remaining / batchProgressRate) * 1000)
|
|
954
|
+
: undefined;
|
|
955
|
+
const progress = {
|
|
956
|
+
completed: batchCompletedCount,
|
|
957
|
+
total: payloads.length,
|
|
958
|
+
percentage,
|
|
959
|
+
...(batchProgressRate > 0 ? { rate: Math.round(batchProgressRate * 100) / 100 } : {}),
|
|
960
|
+
...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
|
|
961
|
+
startTime: batchStartTime,
|
|
962
|
+
elapsedTime
|
|
963
|
+
};
|
|
964
|
+
lastBatchProgressEmitTime = now;
|
|
965
|
+
lastBatchProgressPercentage = percentage;
|
|
966
|
+
try {
|
|
967
|
+
this.progressCallback(progress);
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
console.error('Error in progress callback:', error);
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
// Emit initial progress (0%)
|
|
974
|
+
if (this.progressCallback) {
|
|
975
|
+
emitBatchProgress();
|
|
976
|
+
}
|
|
384
977
|
// Create all tasks with tracking info
|
|
385
978
|
const pendingTasks = new Map();
|
|
386
979
|
for (let index = 0; index < payloads.length; index++) {
|
|
387
980
|
const payload = payloads[index];
|
|
388
981
|
const actionId = crypto.randomUUID();
|
|
389
982
|
const startedAt = Date.now();
|
|
390
|
-
const context = new InvocationContextImpl(actionId);
|
|
391
|
-
const
|
|
983
|
+
const context = new InvocationContextImpl(actionId, undefined, undefined);
|
|
984
|
+
const { promise } = this.scheduler.schedule(actionId, async (signal) => {
|
|
392
985
|
let result;
|
|
393
986
|
let error;
|
|
394
987
|
let retryAttempt = 0;
|
|
395
988
|
let retryDelays = [];
|
|
989
|
+
let timedOut = false;
|
|
990
|
+
let executionTime;
|
|
396
991
|
try {
|
|
397
|
-
const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, true);
|
|
992
|
+
const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal);
|
|
398
993
|
result = execResult.result;
|
|
399
994
|
retryAttempt = execResult.retryAttempt;
|
|
400
995
|
retryDelays = execResult.retryDelays;
|
|
996
|
+
timedOut = execResult.timedOut;
|
|
997
|
+
executionTime = execResult.executionTime;
|
|
401
998
|
return result;
|
|
402
999
|
}
|
|
403
1000
|
catch (e) {
|
|
@@ -405,6 +1002,9 @@ export class ActionBuilder {
|
|
|
405
1002
|
throw e;
|
|
406
1003
|
}
|
|
407
1004
|
finally {
|
|
1005
|
+
// Update batch progress
|
|
1006
|
+
batchCompletedCount++;
|
|
1007
|
+
emitBatchProgress();
|
|
408
1008
|
// Emit final wide event
|
|
409
1009
|
const completedAt = Date.now();
|
|
410
1010
|
const wideEvent = {
|
|
@@ -413,6 +1013,8 @@ export class ActionBuilder {
|
|
|
413
1013
|
completedAt,
|
|
414
1014
|
duration: completedAt - startedAt,
|
|
415
1015
|
input: payload,
|
|
1016
|
+
priority,
|
|
1017
|
+
...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
|
|
416
1018
|
output: result,
|
|
417
1019
|
error,
|
|
418
1020
|
attachments: context.getAttachments(),
|
|
@@ -421,6 +1023,16 @@ export class ActionBuilder {
|
|
|
421
1023
|
isRetry: retryAttempt > 0,
|
|
422
1024
|
totalAttempts: retryAttempt + 1,
|
|
423
1025
|
retryDelays
|
|
1026
|
+
} : {}),
|
|
1027
|
+
...(this.timeoutConfig ? {
|
|
1028
|
+
timeout: this.timeoutConfig.duration,
|
|
1029
|
+
timedOut,
|
|
1030
|
+
...(executionTime !== undefined ? { executionTime } : {})
|
|
1031
|
+
} : {}),
|
|
1032
|
+
...(error instanceof CancellationError ? {
|
|
1033
|
+
cancelled: true,
|
|
1034
|
+
cancelReason: error.reason,
|
|
1035
|
+
cancelledAt: error.state
|
|
424
1036
|
} : {})
|
|
425
1037
|
};
|
|
426
1038
|
if (this.eventCallback) {
|
|
@@ -432,7 +1044,8 @@ export class ActionBuilder {
|
|
|
432
1044
|
}
|
|
433
1045
|
}
|
|
434
1046
|
}
|
|
435
|
-
}
|
|
1047
|
+
}, { priority });
|
|
1048
|
+
const taskPromise = promise.then((data) => ({ actionId, index, data, error: undefined }), (error) => ({ actionId, index, data: undefined, error }));
|
|
436
1049
|
pendingTasks.set(actionId, taskPromise);
|
|
437
1050
|
}
|
|
438
1051
|
// Yield results as they complete
|
|
@@ -456,6 +1069,34 @@ export class ActionBuilder {
|
|
|
456
1069
|
getActiveCount() {
|
|
457
1070
|
return this.scheduler.getActiveCount();
|
|
458
1071
|
}
|
|
1072
|
+
/**
|
|
1073
|
+
* Cancel all active invocations of this action
|
|
1074
|
+
* @param reasonOrPredicate Reason string or predicate function to filter invocations
|
|
1075
|
+
*/
|
|
1076
|
+
cancelAll(reasonOrPredicate) {
|
|
1077
|
+
let count = 0;
|
|
1078
|
+
const invocations = Array.from(this.activeInvocations.values());
|
|
1079
|
+
for (const invocation of invocations) {
|
|
1080
|
+
if (typeof reasonOrPredicate === 'function') {
|
|
1081
|
+
if (reasonOrPredicate(invocation)) {
|
|
1082
|
+
invocation.cancel('Cancelled by predicate');
|
|
1083
|
+
count++;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
else {
|
|
1087
|
+
invocation.cancel(reasonOrPredicate);
|
|
1088
|
+
count++;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
return count;
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Cancel only queued (not running) invocations
|
|
1095
|
+
* @param reason Optional cancellation reason
|
|
1096
|
+
*/
|
|
1097
|
+
clearQueue(reason) {
|
|
1098
|
+
return this.scheduler.clearQueue(reason);
|
|
1099
|
+
}
|
|
459
1100
|
}
|
|
460
1101
|
// Factory function that infers types from the handler
|
|
461
1102
|
export function createAction(handler) {
|
|
@@ -475,4 +1116,18 @@ export function withContext(handler) {
|
|
|
475
1116
|
wrapper.__originalHandler = handler;
|
|
476
1117
|
return wrapper;
|
|
477
1118
|
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Wrapper function to enable AbortSignal for a handler
|
|
1121
|
+
* Returns a modified handler that can be used with createAction
|
|
1122
|
+
*/
|
|
1123
|
+
export function withAbortSignal(handler) {
|
|
1124
|
+
// Return a wrapper that will be detected by ActionBuilder
|
|
1125
|
+
const wrapper = ((...args) => {
|
|
1126
|
+
// This will never be called directly - ActionBuilder intercepts it
|
|
1127
|
+
throw new Error('withAbortSignal handler should not be called directly');
|
|
1128
|
+
});
|
|
1129
|
+
wrapper.__usesAbortSignal = true;
|
|
1130
|
+
wrapper.__originalHandler = handler;
|
|
1131
|
+
return wrapper;
|
|
1132
|
+
}
|
|
478
1133
|
//# sourceMappingURL=index.js.map
|