@cadenza.io/core 3.13.3 → 3.15.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/dist/index.js CHANGED
@@ -79,13 +79,230 @@ function formatTimestamp(timestamp) {
79
79
 
80
80
  // src/engine/SignalBroker.ts
81
81
  var import_uuid = require("uuid");
82
+
83
+ // node_modules/lodash-es/isObject.js
84
+ function isObject(value) {
85
+ var type = typeof value;
86
+ return value != null && (type == "object" || type == "function");
87
+ }
88
+ var isObject_default = isObject;
89
+
90
+ // node_modules/lodash-es/_freeGlobal.js
91
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
92
+ var freeGlobal_default = freeGlobal;
93
+
94
+ // node_modules/lodash-es/_root.js
95
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
96
+ var root = freeGlobal_default || freeSelf || Function("return this")();
97
+ var root_default = root;
98
+
99
+ // node_modules/lodash-es/now.js
100
+ var now = function() {
101
+ return root_default.Date.now();
102
+ };
103
+ var now_default = now;
104
+
105
+ // node_modules/lodash-es/_trimmedEndIndex.js
106
+ var reWhitespace = /\s/;
107
+ function trimmedEndIndex(string) {
108
+ var index = string.length;
109
+ while (index-- && reWhitespace.test(string.charAt(index))) {
110
+ }
111
+ return index;
112
+ }
113
+ var trimmedEndIndex_default = trimmedEndIndex;
114
+
115
+ // node_modules/lodash-es/_baseTrim.js
116
+ var reTrimStart = /^\s+/;
117
+ function baseTrim(string) {
118
+ return string ? string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "") : string;
119
+ }
120
+ var baseTrim_default = baseTrim;
121
+
122
+ // node_modules/lodash-es/_Symbol.js
123
+ var Symbol2 = root_default.Symbol;
124
+ var Symbol_default = Symbol2;
125
+
126
+ // node_modules/lodash-es/_getRawTag.js
127
+ var objectProto = Object.prototype;
128
+ var hasOwnProperty = objectProto.hasOwnProperty;
129
+ var nativeObjectToString = objectProto.toString;
130
+ var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
131
+ function getRawTag(value) {
132
+ var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
133
+ try {
134
+ value[symToStringTag] = void 0;
135
+ var unmasked = true;
136
+ } catch (e) {
137
+ }
138
+ var result = nativeObjectToString.call(value);
139
+ if (unmasked) {
140
+ if (isOwn) {
141
+ value[symToStringTag] = tag;
142
+ } else {
143
+ delete value[symToStringTag];
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+ var getRawTag_default = getRawTag;
149
+
150
+ // node_modules/lodash-es/_objectToString.js
151
+ var objectProto2 = Object.prototype;
152
+ var nativeObjectToString2 = objectProto2.toString;
153
+ function objectToString(value) {
154
+ return nativeObjectToString2.call(value);
155
+ }
156
+ var objectToString_default = objectToString;
157
+
158
+ // node_modules/lodash-es/_baseGetTag.js
159
+ var nullTag = "[object Null]";
160
+ var undefinedTag = "[object Undefined]";
161
+ var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
162
+ function baseGetTag(value) {
163
+ if (value == null) {
164
+ return value === void 0 ? undefinedTag : nullTag;
165
+ }
166
+ return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
167
+ }
168
+ var baseGetTag_default = baseGetTag;
169
+
170
+ // node_modules/lodash-es/isObjectLike.js
171
+ function isObjectLike(value) {
172
+ return value != null && typeof value == "object";
173
+ }
174
+ var isObjectLike_default = isObjectLike;
175
+
176
+ // node_modules/lodash-es/isSymbol.js
177
+ var symbolTag = "[object Symbol]";
178
+ function isSymbol(value) {
179
+ return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
180
+ }
181
+ var isSymbol_default = isSymbol;
182
+
183
+ // node_modules/lodash-es/toNumber.js
184
+ var NAN = 0 / 0;
185
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
186
+ var reIsBinary = /^0b[01]+$/i;
187
+ var reIsOctal = /^0o[0-7]+$/i;
188
+ var freeParseInt = parseInt;
189
+ function toNumber(value) {
190
+ if (typeof value == "number") {
191
+ return value;
192
+ }
193
+ if (isSymbol_default(value)) {
194
+ return NAN;
195
+ }
196
+ if (isObject_default(value)) {
197
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
198
+ value = isObject_default(other) ? other + "" : other;
199
+ }
200
+ if (typeof value != "string") {
201
+ return value === 0 ? value : +value;
202
+ }
203
+ value = baseTrim_default(value);
204
+ var isBinary = reIsBinary.test(value);
205
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
206
+ }
207
+ var toNumber_default = toNumber;
208
+
209
+ // node_modules/lodash-es/debounce.js
210
+ var FUNC_ERROR_TEXT = "Expected a function";
211
+ var nativeMax = Math.max;
212
+ var nativeMin = Math.min;
213
+ function debounce(func, wait, options) {
214
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
215
+ if (typeof func != "function") {
216
+ throw new TypeError(FUNC_ERROR_TEXT);
217
+ }
218
+ wait = toNumber_default(wait) || 0;
219
+ if (isObject_default(options)) {
220
+ leading = !!options.leading;
221
+ maxing = "maxWait" in options;
222
+ maxWait = maxing ? nativeMax(toNumber_default(options.maxWait) || 0, wait) : maxWait;
223
+ trailing = "trailing" in options ? !!options.trailing : trailing;
224
+ }
225
+ function invokeFunc(time) {
226
+ var args = lastArgs, thisArg = lastThis;
227
+ lastArgs = lastThis = void 0;
228
+ lastInvokeTime = time;
229
+ result = func.apply(thisArg, args);
230
+ return result;
231
+ }
232
+ function leadingEdge(time) {
233
+ lastInvokeTime = time;
234
+ timerId = setTimeout(timerExpired, wait);
235
+ return leading ? invokeFunc(time) : result;
236
+ }
237
+ function remainingWait(time) {
238
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
239
+ return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
240
+ }
241
+ function shouldInvoke(time) {
242
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
243
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
244
+ }
245
+ function timerExpired() {
246
+ var time = now_default();
247
+ if (shouldInvoke(time)) {
248
+ return trailingEdge(time);
249
+ }
250
+ timerId = setTimeout(timerExpired, remainingWait(time));
251
+ }
252
+ function trailingEdge(time) {
253
+ timerId = void 0;
254
+ if (trailing && lastArgs) {
255
+ return invokeFunc(time);
256
+ }
257
+ lastArgs = lastThis = void 0;
258
+ return result;
259
+ }
260
+ function cancel() {
261
+ if (timerId !== void 0) {
262
+ clearTimeout(timerId);
263
+ }
264
+ lastInvokeTime = 0;
265
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
266
+ }
267
+ function flush() {
268
+ return timerId === void 0 ? result : trailingEdge(now_default());
269
+ }
270
+ function debounced() {
271
+ var time = now_default(), isInvoking = shouldInvoke(time);
272
+ lastArgs = arguments;
273
+ lastThis = this;
274
+ lastCallTime = time;
275
+ if (isInvoking) {
276
+ if (timerId === void 0) {
277
+ return leadingEdge(lastCallTime);
278
+ }
279
+ if (maxing) {
280
+ clearTimeout(timerId);
281
+ timerId = setTimeout(timerExpired, wait);
282
+ return invokeFunc(lastCallTime);
283
+ }
284
+ }
285
+ if (timerId === void 0) {
286
+ timerId = setTimeout(timerExpired, wait);
287
+ }
288
+ return result;
289
+ }
290
+ debounced.cancel = cancel;
291
+ debounced.flush = flush;
292
+ return debounced;
293
+ }
294
+ var debounce_default = debounce;
295
+
296
+ // src/engine/SignalBroker.ts
82
297
  var SignalBroker = class _SignalBroker {
83
298
  // execId -> emitted signals
84
299
  constructor() {
85
300
  this.debug = false;
86
301
  this.verbose = false;
302
+ this.debouncedEmitters = /* @__PURE__ */ new Map();
87
303
  // TODO: Signals should be a class with a the observers, registered flag and other data.
88
304
  this.signalObservers = /* @__PURE__ */ new Map();
305
+ this.emittedSignalsRegistry = /* @__PURE__ */ new Set();
89
306
  this.emitStacks = /* @__PURE__ */ new Map();
90
307
  this.addSignal("meta.signal_broker.added");
91
308
  }
@@ -192,6 +409,9 @@ var SignalBroker = class _SignalBroker {
192
409
  this.addSignal(signal);
193
410
  this.signalObservers.get(signal).tasks.add(routineOrTask);
194
411
  }
412
+ registerEmittedSignal(signal) {
413
+ this.emittedSignalsRegistry.add(signal);
414
+ }
195
415
  /**
196
416
  * Unsubscribes a routine/task from a signal.
197
417
  * @param signal The signal.
@@ -247,20 +467,20 @@ var SignalBroker = class _SignalBroker {
247
467
  }
248
468
  const emit = () => this.emit(signal, context);
249
469
  if (leading) {
250
- const now = Date.now();
470
+ const now2 = Date.now();
251
471
  const start = startDateTime?.getTime();
252
- if (!start || start <= now) {
472
+ if (!start || start <= now2) {
253
473
  emit();
254
474
  }
255
475
  }
256
476
  let firstDelay = intervalMs;
257
477
  if (startDateTime) {
258
478
  let slot = startDateTime.getTime();
259
- const now = Date.now();
260
- while (slot < now) {
479
+ const now2 = Date.now();
480
+ while (slot < now2) {
261
481
  slot += intervalMs;
262
482
  }
263
- firstDelay = slot - now;
483
+ firstDelay = slot - now2;
264
484
  }
265
485
  let timer = null;
266
486
  let stopped = false;
@@ -277,6 +497,19 @@ var SignalBroker = class _SignalBroker {
277
497
  }
278
498
  };
279
499
  }
500
+ debounce(signal, context, delayMs = 500) {
501
+ let debouncedEmitter = this.debouncedEmitters.get(signal);
502
+ if (!debouncedEmitter) {
503
+ this.debouncedEmitters.set(
504
+ signal,
505
+ debounce_default((ctx) => {
506
+ this.emit(signal, ctx);
507
+ }, delayMs)
508
+ );
509
+ debouncedEmitter = this.debouncedEmitters.get(signal);
510
+ }
511
+ debouncedEmitter(context);
512
+ }
280
513
  /**
281
514
  * Emits a signal with the specified context, triggering any associated handlers for that signal.
282
515
  *
@@ -454,14 +687,18 @@ var SignalBroker = class _SignalBroker {
454
687
  listObservedSignals() {
455
688
  return Array.from(this.signalObservers.keys());
456
689
  }
690
+ listEmittedSignals() {
691
+ return Array.from(this.emittedSignalsRegistry);
692
+ }
457
693
  reset() {
458
694
  this.emitStacks.clear();
459
695
  this.signalObservers.clear();
696
+ this.emittedSignalsRegistry.clear();
460
697
  }
461
698
  };
462
699
 
463
700
  // src/engine/GraphRunner.ts
464
- var import_uuid6 = require("uuid");
701
+ var import_uuid5 = require("uuid");
465
702
 
466
703
  // src/engine/GraphRun.ts
467
704
  var import_uuid2 = require("uuid");
@@ -1966,8 +2203,178 @@ var GraphRoutine = class extends SignalEmitter {
1966
2203
  }
1967
2204
  };
1968
2205
 
2206
+ // src/engine/GraphRunner.ts
2207
+ var GraphRunner = class extends SignalEmitter {
2208
+ /**
2209
+ * Constructs a runner.
2210
+ * @param isMeta Meta flag (default false).
2211
+ * @edge Creates 'Start run' meta-task chained to registry gets.
2212
+ */
2213
+ constructor(isMeta = false) {
2214
+ super(isMeta);
2215
+ this.debug = false;
2216
+ this.verbose = false;
2217
+ this.isRunning = false;
2218
+ this.isMeta = false;
2219
+ this.isMeta = isMeta;
2220
+ this.strategy = Cadenza.runStrategy.PARALLEL;
2221
+ this.currentRun = new GraphRun(this.strategy);
2222
+ }
2223
+ /**
2224
+ * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
2225
+ * routines, or arrays of tasks and routines. Handles metadata and execution context management.
2226
+ *
2227
+ * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.
2228
+ * It can be a single task, a single routine, or an array of tasks and routines.
2229
+ * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.
2230
+ * Used to propagate information across task or routine executions.
2231
+ * @return {void} - This method does not return a value.
2232
+ */
2233
+ addTasks(tasks, context = {}) {
2234
+ let _tasks = Array.isArray(tasks) ? tasks : [tasks];
2235
+ if (_tasks.length === 0) {
2236
+ console.warn("No tasks/routines to add.");
2237
+ return;
2238
+ }
2239
+ let routineName = _tasks.map((t) => t.name).join(" | ");
2240
+ let routineVersion = null;
2241
+ let isMeta = _tasks.every((t) => t.isMeta);
2242
+ const allTasks = _tasks.flatMap((t) => {
2243
+ if (t instanceof GraphRoutine) {
2244
+ routineName = t.name;
2245
+ routineVersion = t.version;
2246
+ isMeta = t.isMeta;
2247
+ const routineTasks = [];
2248
+ t.forEachTask((task) => routineTasks.push(task));
2249
+ return routineTasks;
2250
+ }
2251
+ return t;
2252
+ });
2253
+ const isSubMeta = allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;
2254
+ context.__isSubMeta = isSubMeta;
2255
+ const isNewTrace = !context.__routineExecId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
2256
+ const executionTraceId = context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid5.v4)();
2257
+ context.__executionTraceId = executionTraceId;
2258
+ const routineExecId = context.__routineExecId ?? (0, import_uuid5.v4)();
2259
+ context.__routineExecId = routineExecId;
2260
+ const ctx = new GraphContext(context || {});
2261
+ if (!isSubMeta) {
2262
+ const contextData = ctx.export();
2263
+ if (isNewTrace) {
2264
+ this.emitMetrics("meta.runner.new_trace", {
2265
+ data: {
2266
+ uuid: executionTraceId,
2267
+ issuer_type: "service",
2268
+ // TODO: Add issuer type
2269
+ issuer_id: context.__metadata?.__issuerId ?? context.__issuerId ?? null,
2270
+ issued_at: formatTimestamp(Date.now()),
2271
+ intent: context.__metadata?.__intent ?? context.__intent ?? null,
2272
+ context: contextData,
2273
+ is_meta: isMeta
2274
+ },
2275
+ __metadata: {
2276
+ __executionTraceId: executionTraceId
2277
+ }
2278
+ });
2279
+ }
2280
+ this.emitMetrics("meta.runner.added_tasks", {
2281
+ data: {
2282
+ uuid: routineExecId,
2283
+ name: routineName,
2284
+ routineVersion,
2285
+ isMeta,
2286
+ executionTraceId,
2287
+ context: isNewTrace ? contextData.id : contextData,
2288
+ previousRoutineExecution: context.__localRoutineExecId ?? context.__metadata?.__routineExecId ?? null,
2289
+ created: formatTimestamp(Date.now())
2290
+ },
2291
+ __metadata: {
2292
+ __executionTraceId: executionTraceId
2293
+ }
2294
+ });
2295
+ }
2296
+ allTasks.forEach(
2297
+ (task) => this.currentRun.addNode(
2298
+ new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose)
2299
+ )
2300
+ );
2301
+ }
2302
+ /**
2303
+ * Executes the provided tasks or routines. Maintains the execution state
2304
+ * and handles synchronous or asynchronous processing.
2305
+ *
2306
+ * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.
2307
+ * @param {AnyObject} [context] - An optional context object to be used during task execution.
2308
+ * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.
2309
+ */
2310
+ run(tasks, context) {
2311
+ if (tasks) {
2312
+ this.addTasks(tasks, context ?? {});
2313
+ }
2314
+ if (this.isRunning) {
2315
+ return this.currentRun;
2316
+ }
2317
+ if (this.currentRun) {
2318
+ this.isRunning = true;
2319
+ const runResult = this.currentRun.run();
2320
+ if (runResult instanceof Promise) {
2321
+ return this.runAsync(runResult);
2322
+ }
2323
+ }
2324
+ return this.reset();
2325
+ }
2326
+ /**
2327
+ * Executes the provided asynchronous operation and resets the state afterwards.
2328
+ *
2329
+ * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.
2330
+ * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.
2331
+ */
2332
+ async runAsync(run) {
2333
+ await run;
2334
+ return this.reset();
2335
+ }
2336
+ /**
2337
+ * Resets the current state of the graph, creating a new GraphRun instance
2338
+ * and returning the previous run instance.
2339
+ * If the debug mode is not enabled, it will destroy the existing resources.
2340
+ *
2341
+ * @return {GraphRun} The last GraphRun instance before the reset.
2342
+ */
2343
+ reset() {
2344
+ this.isRunning = false;
2345
+ const lastRun = this.currentRun;
2346
+ if (!this.debug) {
2347
+ this.destroy();
2348
+ }
2349
+ this.currentRun = new GraphRun(this.strategy);
2350
+ return lastRun;
2351
+ }
2352
+ setDebug(value) {
2353
+ this.debug = value;
2354
+ }
2355
+ setVerbose(value) {
2356
+ this.verbose = value;
2357
+ }
2358
+ destroy() {
2359
+ this.currentRun.destroy();
2360
+ }
2361
+ /**
2362
+ * Sets the strategy to be used for running the graph and initializes
2363
+ * the current run with the provided strategy if no process is currently running.
2364
+ *
2365
+ * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.
2366
+ * @return {void}
2367
+ */
2368
+ setStrategy(strategy) {
2369
+ this.strategy = strategy;
2370
+ if (!this.isRunning) {
2371
+ this.currentRun = new GraphRun(this.strategy);
2372
+ }
2373
+ }
2374
+ };
2375
+
1969
2376
  // src/graph/definition/Task.ts
1970
- var import_uuid5 = require("uuid");
2377
+ var import_uuid6 = require("uuid");
1971
2378
 
1972
2379
  // src/graph/iterators/TaskIterator.ts
1973
2380
  var TaskIterator = class {
@@ -2116,7 +2523,7 @@ var Task = class _Task extends SignalEmitter {
2116
2523
  }
2117
2524
  clone(traverse = false, includeSignals = false) {
2118
2525
  const clonedTask = new _Task(
2119
- `${this.name} (clone ${(0, import_uuid5.v4)().slice(0, 8)})`,
2526
+ `${this.name} (clone ${(0, import_uuid6.v4)().slice(0, 8)})`,
2120
2527
  this.taskFunction,
2121
2528
  this.description,
2122
2529
  this.concurrency,
@@ -2601,6 +3008,14 @@ var Task = class _Task extends SignalEmitter {
2601
3008
  mapPrevious(callback) {
2602
3009
  return Array.from(this.predecessorTasks).map(callback);
2603
3010
  }
3011
+ makeRoutine(name, description) {
3012
+ if (this.isMeta) {
3013
+ Cadenza.createMetaRoutine(name, [this], description);
3014
+ } else {
3015
+ Cadenza.createRoutine(name, [this], description);
3016
+ }
3017
+ return this;
3018
+ }
2604
3019
  /**
2605
3020
  * Adds the specified signals to the current instance, making it observe them.
2606
3021
  * If the instance is already observing a signal, it will be skipped.
@@ -2657,29 +3072,33 @@ var Task = class _Task extends SignalEmitter {
2657
3072
  emitsOnFail(...signals) {
2658
3073
  signals.forEach((signal) => {
2659
3074
  this.signalsToEmitOnFail.add(signal);
2660
- this.attachSignal(signal, true);
3075
+ this.attachSignal(signal);
2661
3076
  });
2662
3077
  return this;
2663
3078
  }
2664
3079
  /**
2665
3080
  * Attaches a signal to the current context and emits metadata if the register flag is set.
2666
3081
  *
2667
- * @param {string} signal - The name of the signal to attach.
2668
- * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as "on fail".
3082
+ * @param {...string} signals - The names of the signals to attach.
2669
3083
  * @return {void} This method does not return a value.
2670
3084
  */
2671
- attachSignal(signal, isOnFail = false) {
2672
- this.emitsSignals.add(signal);
2673
- if (this.register) {
2674
- this.emitWithMetadata("meta.task.attached_signal", {
2675
- data: {
2676
- signalName: signal.split(":")[0],
2677
- taskName: this.name,
2678
- taskVersion: this.version,
2679
- isOnFail
2680
- }
2681
- });
2682
- }
3085
+ attachSignal(...signals) {
3086
+ signals.forEach((signal) => {
3087
+ this.emitsSignals.add(signal);
3088
+ Cadenza.broker.registerEmittedSignal(signal);
3089
+ if (this.register) {
3090
+ const isOnFail = this.signalsToEmitOnFail.has(signal);
3091
+ this.emitWithMetadata("meta.task.attached_signal", {
3092
+ data: {
3093
+ signalName: signal.split(":")[0],
3094
+ taskName: this.name,
3095
+ taskVersion: this.version,
3096
+ isOnFail
3097
+ }
3098
+ });
3099
+ }
3100
+ });
3101
+ return this;
2683
3102
  }
2684
3103
  /**
2685
3104
  * Unsubscribes the current instance from the specified signals.
@@ -3059,205 +3478,6 @@ var GraphRegistry = class _GraphRegistry {
3059
3478
  }
3060
3479
  };
3061
3480
 
3062
- // src/engine/GraphRunner.ts
3063
- var GraphRunner = class extends SignalEmitter {
3064
- /**
3065
- * Constructs a runner.
3066
- * @param isMeta Meta flag (default false).
3067
- * @edge Creates 'Start run' meta-task chained to registry gets.
3068
- */
3069
- constructor(isMeta = false) {
3070
- super(isMeta);
3071
- this.debug = false;
3072
- this.verbose = false;
3073
- this.isRunning = false;
3074
- this.isMeta = false;
3075
- this.isMeta = isMeta;
3076
- this.strategy = Cadenza.runStrategy.PARALLEL;
3077
- this.currentRun = new GraphRun(this.strategy);
3078
- }
3079
- init() {
3080
- if (this.isMeta) return;
3081
- Cadenza.createMetaTask(
3082
- "Start run",
3083
- this.startRun.bind(this),
3084
- "Starts a run"
3085
- ).doAfter(
3086
- GraphRegistry.instance.getTaskByName,
3087
- GraphRegistry.instance.getRoutineByName
3088
- );
3089
- }
3090
- /**
3091
- * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
3092
- * routines, or arrays of tasks and routines. Handles metadata and execution context management.
3093
- *
3094
- * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.
3095
- * It can be a single task, a single routine, or an array of tasks and routines.
3096
- * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.
3097
- * Used to propagate information across task or routine executions.
3098
- * @return {void} - This method does not return a value.
3099
- */
3100
- addTasks(tasks, context = {}) {
3101
- let _tasks = Array.isArray(tasks) ? tasks : [tasks];
3102
- if (_tasks.length === 0) {
3103
- console.warn("No tasks/routines to add.");
3104
- return;
3105
- }
3106
- let routineName = _tasks.map((t) => t.name).join(" | ");
3107
- let routineVersion = null;
3108
- let isMeta = _tasks.every((t) => t.isMeta);
3109
- const allTasks = _tasks.flatMap((t) => {
3110
- if (t instanceof GraphRoutine) {
3111
- routineName = t.name;
3112
- routineVersion = t.version;
3113
- isMeta = t.isMeta;
3114
- const routineTasks = [];
3115
- t.forEachTask((task) => routineTasks.push(task));
3116
- return routineTasks;
3117
- }
3118
- return t;
3119
- });
3120
- const isSubMeta = allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;
3121
- context.__isSubMeta = isSubMeta;
3122
- const isNewTrace = !context.__routineExecId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
3123
- const executionTraceId = context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid6.v4)();
3124
- context.__executionTraceId = executionTraceId;
3125
- const routineExecId = context.__routineExecId ?? (0, import_uuid6.v4)();
3126
- context.__routineExecId = routineExecId;
3127
- const ctx = new GraphContext(context || {});
3128
- if (!isSubMeta) {
3129
- const contextData = ctx.export();
3130
- if (isNewTrace) {
3131
- this.emitMetrics("meta.runner.new_trace", {
3132
- data: {
3133
- uuid: executionTraceId,
3134
- issuer_type: "service",
3135
- // TODO: Add issuer type
3136
- issuer_id: context.__metadata?.__issuerId ?? context.__issuerId ?? null,
3137
- issued_at: formatTimestamp(Date.now()),
3138
- intent: context.__metadata?.__intent ?? context.__intent ?? null,
3139
- context: contextData,
3140
- is_meta: isMeta
3141
- },
3142
- __metadata: {
3143
- __executionTraceId: executionTraceId
3144
- }
3145
- });
3146
- }
3147
- this.emitMetrics("meta.runner.added_tasks", {
3148
- data: {
3149
- uuid: routineExecId,
3150
- name: routineName,
3151
- routineVersion,
3152
- isMeta,
3153
- executionTraceId,
3154
- context: isNewTrace ? contextData.id : contextData,
3155
- previousRoutineExecution: context.__localRoutineExecId ?? context.__metadata?.__routineExecId ?? null,
3156
- // TODO: There is a chance this is not added to the database yet...
3157
- created: formatTimestamp(Date.now())
3158
- },
3159
- __metadata: {
3160
- __executionTraceId: executionTraceId
3161
- }
3162
- });
3163
- }
3164
- allTasks.forEach(
3165
- (task) => this.currentRun.addNode(
3166
- new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose)
3167
- )
3168
- );
3169
- }
3170
- /**
3171
- * Executes the provided tasks or routines. Maintains the execution state
3172
- * and handles synchronous or asynchronous processing.
3173
- *
3174
- * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.
3175
- * @param {AnyObject} [context] - An optional context object to be used during task execution.
3176
- * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.
3177
- */
3178
- run(tasks, context) {
3179
- if (tasks) {
3180
- this.addTasks(tasks, context ?? {});
3181
- }
3182
- if (this.isRunning) {
3183
- return this.currentRun;
3184
- }
3185
- if (this.currentRun) {
3186
- this.isRunning = true;
3187
- const runResult = this.currentRun.run();
3188
- if (runResult instanceof Promise) {
3189
- return this.runAsync(runResult);
3190
- }
3191
- }
3192
- return this.reset();
3193
- }
3194
- /**
3195
- * Executes the provided asynchronous operation and resets the state afterwards.
3196
- *
3197
- * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.
3198
- * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.
3199
- */
3200
- async runAsync(run) {
3201
- await run;
3202
- return this.reset();
3203
- }
3204
- /**
3205
- * Resets the current state of the graph, creating a new GraphRun instance
3206
- * and returning the previous run instance.
3207
- * If the debug mode is not enabled, it will destroy the existing resources.
3208
- *
3209
- * @return {GraphRun} The last GraphRun instance before the reset.
3210
- */
3211
- reset() {
3212
- this.isRunning = false;
3213
- const lastRun = this.currentRun;
3214
- if (!this.debug) {
3215
- this.destroy();
3216
- }
3217
- this.currentRun = new GraphRun(this.strategy);
3218
- return lastRun;
3219
- }
3220
- setDebug(value) {
3221
- this.debug = value;
3222
- }
3223
- setVerbose(value) {
3224
- this.verbose = value;
3225
- }
3226
- destroy() {
3227
- this.currentRun.destroy();
3228
- }
3229
- /**
3230
- * Sets the strategy to be used for running the graph and initializes
3231
- * the current run with the provided strategy if no process is currently running.
3232
- *
3233
- * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.
3234
- * @return {void}
3235
- */
3236
- setStrategy(strategy) {
3237
- this.strategy = strategy;
3238
- if (!this.isRunning) {
3239
- this.currentRun = new GraphRun(this.strategy);
3240
- }
3241
- }
3242
- // TODO This should not live here. This is deputy related.
3243
- startRun(context, emit) {
3244
- if (context.task || context.routine) {
3245
- const routine = context.task ?? context.routine;
3246
- delete context.task;
3247
- delete context.routine;
3248
- context.__routineExecId = context.__metadata?.__deputyExecId ?? null;
3249
- context.__isDeputy = true;
3250
- this.run(routine, context);
3251
- return true;
3252
- } else {
3253
- context.errored = true;
3254
- context.__error = "No routine or task defined.";
3255
- emit("meta.runner.failed", context);
3256
- return false;
3257
- }
3258
- }
3259
- };
3260
-
3261
3481
  // src/graph/definition/DebounceTask.ts
3262
3482
  var DebounceTask = class extends Task {
3263
3483
  constructor(name, task, description = "", debounceTime = 1e3, leading = false, trailing = true, maxWait = 0, concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = false, isSubMeta = false, isHidden = false, inputSchema = void 0, validateInputSchema = false, outputSchema = void 0, validateOutputSchema = false) {
@@ -4216,8 +4436,6 @@ var Cadenza = class {
4216
4436
  }
4217
4437
  this.registry = GraphRegistry.instance;
4218
4438
  this.broker.init();
4219
- this.runner.init();
4220
- this.metaRunner.init();
4221
4439
  }
4222
4440
  /**
4223
4441
  * Retrieves the available strategies for running graphs.
@@ -4325,6 +4543,9 @@ var Cadenza = class {
4325
4543
  startDateTime
4326
4544
  );
4327
4545
  }
4546
+ static debounce(signalName, context, delayMs) {
4547
+ this.broker?.debounce(signalName, context, delayMs);
4548
+ }
4328
4549
  static get(taskName) {
4329
4550
  return this.registry?.tasks.get(taskName);
4330
4551
  }