@fractal-solutions/qflow 1.0.53 → 1.0.55
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 +299 -0
- package/dist/qflow.d.ts +8 -5
- package/dist/qflow.js +117 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
* **Modular & Extensible:** Easily define custom nodes and compose them into complex, reusable flows.
|
|
8
8
|
* **Synchronous & Asynchronous Flows:** Supports both blocking and non-blocking execution models.
|
|
9
|
+
* **Observability:** Monitor workflows with a built-in event system that emits detailed lifecycle events for flows and nodes.
|
|
9
10
|
* **Shared State Management:** Pass and manipulate data across nodes using a central, mutable `shared` object.
|
|
10
11
|
* **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows, including parallel execution.
|
|
11
12
|
* **Agents:** Built upon the `qflow` core functionality are plug and play agents with extensive tool integrations available.
|
|
@@ -83,6 +84,27 @@ A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the ove
|
|
|
83
84
|
**Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
|
|
84
85
|
These specialized flows are designed to process collections of items. They run a sub-flow for each item in the batch. `AsyncParallelBatchFlow` is particularly useful for concurrently processing batch items, significantly speeding up operations.
|
|
85
86
|
|
|
87
|
+
## Observability (Event System)
|
|
88
|
+
|
|
89
|
+
`qflow` includes a built-in event system for `AsyncFlow` that provides detailed insights into the execution of your workflows. This allows for powerful, real-time monitoring, logging, and debugging.
|
|
90
|
+
|
|
91
|
+
You can attach listeners to an `AsyncFlow` instance to subscribe to key lifecycle events.
|
|
92
|
+
|
|
93
|
+
### Available Events
|
|
94
|
+
|
|
95
|
+
* `flow:start`: Emitted when the flow begins.
|
|
96
|
+
* **Payload:** `{ flowId, startTime }`
|
|
97
|
+
* `flow:end`: Emitted when the flow finishes, either successfully or with an error.
|
|
98
|
+
* **Payload:** `{ flowId, endTime, duration, status, error }`
|
|
99
|
+
* `node:start`: Emitted just before a node executes.
|
|
100
|
+
* **Payload:** `{ flowId, nodeClass, startTime, params }`
|
|
101
|
+
* `node:end`: Emitted right after a node finishes.
|
|
102
|
+
* **Payload:** `{ flowId, nodeClass, endTime, duration, status, result, error }`
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
86
108
|
## Basic Usage & Examples
|
|
87
109
|
|
|
88
110
|
### 1. Simple Node
|
|
@@ -246,9 +268,286 @@ await asyncFlow.runAsync({});
|
|
|
246
268
|
|
|
247
269
|
See [documentation/examples.md](documentation/examples.md) for a full list of examples.
|
|
248
270
|
|
|
271
|
+
### 5. Observability
|
|
272
|
+
|
|
273
|
+
This example demonstrates how to use the built-in event system to monitor the execution of a flow.
|
|
274
|
+
|
|
275
|
+
```javascript
|
|
276
|
+
import { AsyncFlow, AsyncNode } from '@fractal-solutions/qflow';
|
|
277
|
+
|
|
278
|
+
const colors = {
|
|
279
|
+
reset: "\x1b[0m",
|
|
280
|
+
cyan: "\x1b[36m",
|
|
281
|
+
green: "\x1b[32m",
|
|
282
|
+
red: "\x1b[31m",
|
|
283
|
+
grey: "\x1b[90m"
|
|
284
|
+
};
|
|
285
|
+
function colorize(text, color) {
|
|
286
|
+
return `${color}${text}${colors.reset}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// A simple node that simulates some work
|
|
290
|
+
class WorkNode extends AsyncNode {
|
|
291
|
+
async execAsync() {
|
|
292
|
+
const workTime = Math.random() * 100 + 50; // 50-150ms
|
|
293
|
+
await new Promise(resolve => setTimeout(resolve, workTime));
|
|
294
|
+
return { status: 'work_done' };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// A node that is designed to fail once before succeeding
|
|
299
|
+
let failCount = 0;
|
|
300
|
+
class SometimesFailsNode extends AsyncNode {
|
|
301
|
+
constructor() {
|
|
302
|
+
// Configure this node to allow 1 retry (for a total of 2 attempts)
|
|
303
|
+
super(2, 0.1);
|
|
304
|
+
}
|
|
305
|
+
async execAsync() {
|
|
306
|
+
if (failCount < 1) {
|
|
307
|
+
failCount++;
|
|
308
|
+
throw new Error('Simulating a transient error');
|
|
309
|
+
}
|
|
310
|
+
return { status: 'succeeded_after_failure' };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// 1. Define the workflow
|
|
315
|
+
const startNode = new WorkNode();
|
|
316
|
+
const middleNode = new SometimesFailsNode();
|
|
317
|
+
const endNode = new WorkNode();
|
|
318
|
+
|
|
319
|
+
startNode.next(middleNode);
|
|
320
|
+
middleNode.next(endNode);
|
|
321
|
+
|
|
322
|
+
// 2. Create the flow
|
|
323
|
+
const myFlow = new AsyncFlow(startNode);
|
|
324
|
+
|
|
325
|
+
// 3. Attach listeners for observability
|
|
326
|
+
myFlow.on('flow:start', (payload) => {
|
|
327
|
+
const time = new Date(payload.startTime).toLocaleTimeString();
|
|
328
|
+
console.log(`\n${colorize(`[FLOW:START]`, colors.cyan)} ${payload.flowId} at ${time}`);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
myFlow.on('node:start', (payload) => {
|
|
332
|
+
console.log(colorize(` [NODE:START] ${payload.nodeClass}`, colors.grey));
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
myFlow.on('node:end', (payload) => {
|
|
336
|
+
const status = payload.status.toUpperCase();
|
|
337
|
+
const color = payload.status === 'success' ? colors.green : colors.red;
|
|
338
|
+
const statusStr = colorize(status.padEnd(7), color); // Pad for alignment
|
|
339
|
+
const duration = `${payload.duration.toFixed(2)}ms`.padStart(10);
|
|
340
|
+
console.log(` [NODE:END] ${payload.nodeClass.padEnd(18)} | Status: ${statusStr} | Duration: ${duration}`);
|
|
341
|
+
if (payload.error) {
|
|
342
|
+
console.log(colorize(` └─ ERROR: ${payload.error.message}`, colors.red));
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
myFlow.on('flow:end', (payload) => {
|
|
347
|
+
const status = payload.status.toUpperCase();
|
|
348
|
+
const color = payload.status === 'success' ? colors.green : colors.red;
|
|
349
|
+
const statusStr = colorize(status.padEnd(7), color);
|
|
350
|
+
const duration = `${payload.duration.toFixed(2)}ms`;
|
|
351
|
+
console.log(`\n${colorize(`[FLOW:END]`, colors.cyan)} ${payload.flowId} | Status: ${statusStr} | Duration: ${duration}`);
|
|
352
|
+
if (payload.error) {
|
|
353
|
+
console.log(colorize(` └─ FLOW ERROR: ${payload.error.message}`, colors.red));
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// 4. Run the flow
|
|
358
|
+
await myFlow.runAsync({});
|
|
359
|
+
|
|
360
|
+
// Expected output:
|
|
361
|
+
//
|
|
362
|
+
// [FLOW:START] <flow-id> at <time>
|
|
363
|
+
// [NODE:START] WorkNode
|
|
364
|
+
// [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
|
|
365
|
+
// [NODE:START] SometimesFailsNode
|
|
366
|
+
// [NODE:END] SometimesFailsNode | Status: ERROR | Duration: X.XXms
|
|
367
|
+
// └─ ERROR: Simulating a transient error
|
|
368
|
+
// [NODE:START] SometimesFailsNode
|
|
369
|
+
// [NODE:END] SometimesFailsNode | Status: SUCCESS | Duration: X.XXms
|
|
370
|
+
// [NODE:START] WorkNode
|
|
371
|
+
// [NODE:END] WorkNode | Status: SUCCESS | Duration: XX.XXms
|
|
372
|
+
//
|
|
373
|
+
// [FLOW:END] <flow-id> | Status: SUCCESS | Duration: XXX.XXms
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
## Logging
|
|
381
|
+
|
|
382
|
+
`qflow` provides a simple yet powerful logging mechanism that gives you per-node control over how and where log messages are sent.
|
|
383
|
+
|
|
384
|
+
### Basic Usage
|
|
385
|
+
|
|
386
|
+
By default, all built-in nodes will log to the console. You don't need to configure anything for this to work.
|
|
387
|
+
|
|
388
|
+
### Per-Node Logging Configuration
|
|
389
|
+
|
|
390
|
+
To customize the logging for a specific node, you can pass a `logging` object in its parameters. This gives you fine-grained control over the logging behavior of each node in your flow.
|
|
391
|
+
|
|
392
|
+
```javascript
|
|
393
|
+
import { HttpRequestNode } from '@fractal-solutions/qflow/nodes';
|
|
394
|
+
|
|
395
|
+
const httpNode = new HttpRequestNode();
|
|
396
|
+
|
|
397
|
+
// This node will log to the console by default
|
|
398
|
+
httpNode.setParams({
|
|
399
|
+
url: 'https://api.example.com/data'
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// This node will log to a file
|
|
403
|
+
const anotherHttpNode = new HttpRequestNode();
|
|
404
|
+
anotherHttpNode.setParams({
|
|
405
|
+
url: 'https://api.example.com/other-data',
|
|
406
|
+
logging: {
|
|
407
|
+
method: 'file',
|
|
408
|
+
params: { filePath: './logs/http.log' }
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
### Logging Methods
|
|
414
|
+
|
|
415
|
+
The following logging methods are available out of the box:
|
|
416
|
+
|
|
417
|
+
* **`console` (default):** Logs messages to the console.
|
|
418
|
+
* **`file`:** Appends log messages to a file.
|
|
419
|
+
* **params:** `{ filePath: string }`
|
|
420
|
+
* **`event`:** Emits log messages through an event emitter.
|
|
421
|
+
* **params:** `{ emitter: EventEmitter }`
|
|
422
|
+
* **`remote`:** Sends log messages to a remote server via a POST request.
|
|
423
|
+
* **params:** `{ url: string }`
|
|
424
|
+
|
|
425
|
+
### Examples
|
|
426
|
+
|
|
427
|
+
#### Logging to a File
|
|
428
|
+
|
|
429
|
+
```javascript
|
|
430
|
+
import { CodeInterpreterNode } from '@fractal-solutions/qflow/nodes';
|
|
431
|
+
|
|
432
|
+
const codeNode = new CodeInterpreterNode();
|
|
433
|
+
codeNode.setParams({
|
|
434
|
+
code: 'print("Hello from Python!")',
|
|
435
|
+
logging: {
|
|
436
|
+
method: 'file',
|
|
437
|
+
params: { filePath: './logs/code-interpreter.log' }
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
#### Logging to an Event Emitter
|
|
443
|
+
|
|
444
|
+
This is useful for integrating `qflow`'s logging with your application's event system.
|
|
445
|
+
|
|
446
|
+
```javascript
|
|
447
|
+
import { EventEmitter } from 'events';
|
|
448
|
+
import { MemoryNode } from '@fractal-solutions/qflow/nodes';
|
|
449
|
+
|
|
450
|
+
const myEmitter = new EventEmitter();
|
|
451
|
+
myEmitter.on('log', (logEntry) => {
|
|
452
|
+
console.log('Received log event:', logEntry);
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
const memoryNode = new MemoryNode();
|
|
456
|
+
memoryNode.setParams({
|
|
457
|
+
action: 'store',
|
|
458
|
+
content: 'This is a test memory.',
|
|
459
|
+
logging: {
|
|
460
|
+
method: 'event',
|
|
461
|
+
params: { emitter: myEmitter }
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
#### Disabling Logging for a Node
|
|
467
|
+
|
|
468
|
+
You can disable logging for a specific node by setting the `type` to `none`.
|
|
469
|
+
|
|
470
|
+
```javascript
|
|
471
|
+
const silentHttpNode = new HttpRequestNode();
|
|
472
|
+
silentHttpNode.setParams({
|
|
473
|
+
url: 'https://api.example.com/silent',
|
|
474
|
+
logging: {
|
|
475
|
+
type: 'none'
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
### Global Log Level
|
|
481
|
+
|
|
482
|
+
You can set a global log level to control the verbosity of all logs in your application. Only messages with a severity level equal to or higher than the current log level will be processed.
|
|
483
|
+
|
|
484
|
+
```javascript
|
|
485
|
+
import { setLogLevel, LogLevel } from '@fractal-solutions/qflow/logger';
|
|
486
|
+
|
|
487
|
+
// Set the global log level to INFO.
|
|
488
|
+
// This will show INFO, WARN, and ERROR messages, but hide DEBUG messages.
|
|
489
|
+
setLogLevel(LogLevel.INFO);
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
The available log levels are, in order of severity:
|
|
493
|
+
|
|
494
|
+
* `LogLevel.DEBUG`: Detailed information, useful for debugging.
|
|
495
|
+
* `LogLevel.INFO`: General information about the application's state.
|
|
496
|
+
* `LogLevel.WARN`: Indicates a potential problem that does not prevent the application from running.
|
|
497
|
+
* `LogLevel.ERROR`: Indicates a serious error that prevented a specific operation from completing.
|
|
498
|
+
* `LogLevel.NONE`: Disables all logging.
|
|
499
|
+
|
|
500
|
+
### Making Your Custom Nodes Loggable
|
|
501
|
+
|
|
502
|
+
You can make your own custom nodes loggable by following the same pattern as the built-in nodes.
|
|
503
|
+
|
|
504
|
+
1. **Import the `log` function:**
|
|
505
|
+
```javascript
|
|
506
|
+
import { log } from '@fractal-solutions/qflow/logger';
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
2. **Call the `log` function:** In your node's methods, call the `log` function and pass `this.params.logging` as the second argument. This will allow users of your node to configure its logging behavior.
|
|
510
|
+
|
|
511
|
+
Here is an example of a custom node that implements loggable behavior:
|
|
512
|
+
|
|
513
|
+
```javascript
|
|
514
|
+
import { AsyncNode } from '@fractal-solutions/qflow';
|
|
515
|
+
import { log } from '@fractal-solutions/qflow/logger';
|
|
516
|
+
|
|
517
|
+
class MyCustomNode extends AsyncNode {
|
|
518
|
+
async execAsync() {
|
|
519
|
+
log('Starting execution of MyCustomNode', this.params.logging);
|
|
520
|
+
// ... your node's logic ...
|
|
521
|
+
|
|
522
|
+
log('Finished execution of MyCustomNode', this.params.logging);
|
|
523
|
+
|
|
524
|
+
return 'default';
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// --- User of your node can now configure logging ---
|
|
529
|
+
|
|
530
|
+
const myNode = new MyCustomNode();
|
|
531
|
+
|
|
532
|
+
// This will log to the console (default)
|
|
533
|
+
myNode.setParams({ /* ... */ });
|
|
534
|
+
|
|
535
|
+
// This will log to a file
|
|
536
|
+
const anotherNode = new MyCustomNode();
|
|
537
|
+
anotherNode.setParams({
|
|
538
|
+
/* ... */,
|
|
539
|
+
logging: {
|
|
540
|
+
method: 'file',
|
|
541
|
+
params: { filePath: './my-custom-node.log' }
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
|
|
249
547
|
|
|
250
548
|
## Agents
|
|
251
549
|
|
|
550
|
+
|
|
252
551
|
For a detailed explanation of the agents, see the [Agents documentation](documentation/agents.md). The tools available to agents are documented in the [Tools documentation](documentation/integrated_nodes.md).
|
|
253
552
|
|
|
254
553
|
## Integrated Nodes and their Examples
|
package/dist/qflow.d.ts
CHANGED
|
@@ -35,24 +35,27 @@ export class AsyncNode extends Node {
|
|
|
35
35
|
execAsync(prepRes: any): Promise<void>;
|
|
36
36
|
execFallbackAsync(prepRes: any, error: any): Promise<void>;
|
|
37
37
|
postAsync(shared: any, prepRes: any, execRes: any): Promise<void>;
|
|
38
|
-
_exec(prepRes: any, shared: any): Promise<void>;
|
|
38
|
+
_exec(prepRes: any, shared: any, observer?: {}): Promise<void>;
|
|
39
39
|
runAsync(shared: any): Promise<void>;
|
|
40
40
|
_runAsync(shared: any): Promise<void>;
|
|
41
41
|
_run(): void;
|
|
42
42
|
}
|
|
43
43
|
export class AsyncBatchNode extends AsyncNode {
|
|
44
|
-
_exec(items: any): Promise<void[]>;
|
|
44
|
+
_exec(items: any, shared: any, observer: any): Promise<void[]>;
|
|
45
45
|
}
|
|
46
46
|
export class AsyncParallelBatchNode extends AsyncNode {
|
|
47
|
-
_exec(items: any): Promise<any[]>;
|
|
47
|
+
_exec(items: any, shared: any, observer: any): Promise<any[]>;
|
|
48
48
|
}
|
|
49
49
|
export class AsyncFlow extends Flow {
|
|
50
|
+
listeners: {};
|
|
51
|
+
on(eventName: any, callback: any): void;
|
|
52
|
+
emit(eventName: any, payload: any): void;
|
|
50
53
|
prepAsync(shared: any): Promise<void>;
|
|
51
54
|
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
52
|
-
_orchAsync(shared: any, params?: {}, initialNode?: any): Promise<any>;
|
|
55
|
+
_orchAsync(flowId: any, shared: any, params?: {}, initialNode?: any): Promise<any>;
|
|
53
56
|
_runAsync(shared: any): Promise<any>;
|
|
54
57
|
run(): void;
|
|
55
|
-
runAsync(shared
|
|
58
|
+
runAsync(shared?: {}): Promise<any>;
|
|
56
59
|
}
|
|
57
60
|
export class AsyncBatchFlow extends AsyncFlow {
|
|
58
61
|
}
|
package/dist/qflow.js
CHANGED
|
@@ -127,18 +127,69 @@ class AsyncNode extends Node {
|
|
|
127
127
|
throw error;
|
|
128
128
|
}
|
|
129
129
|
async postAsync(shared, prepRes, execRes) { }
|
|
130
|
-
async _exec(prepRes, shared) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
130
|
+
async _exec(prepRes, shared, observer = {}) {
|
|
131
|
+
const { emit, flowId } = observer;
|
|
132
|
+
const nodeClass = this.constructor.name;
|
|
133
|
+
const nodeStartTime = performance.now();
|
|
134
|
+
if (emit) {
|
|
135
|
+
emit('node:start', {
|
|
136
|
+
flowId,
|
|
137
|
+
nodeClass,
|
|
138
|
+
startTime: Date.now(),
|
|
139
|
+
params: this.params
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
let finalResult;
|
|
143
|
+
let finalError = null;
|
|
144
|
+
try {
|
|
145
|
+
for (let i = 0; i < this.maxRetries; i++) {
|
|
146
|
+
try {
|
|
147
|
+
finalResult = await this.execAsync(prepRes, shared);
|
|
148
|
+
finalError = null; // Succeeded, clear any error from previous attempt
|
|
149
|
+
break; // Exit retry loop
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
finalError = e;
|
|
153
|
+
if (emit) {
|
|
154
|
+
emit('node:retry', {
|
|
155
|
+
flowId,
|
|
156
|
+
nodeClass,
|
|
157
|
+
attempt: i + 1,
|
|
158
|
+
maxRetries: this.maxRetries,
|
|
159
|
+
error: { message: e.message }
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
if (i >= this.maxRetries - 1) {
|
|
163
|
+
// On the last attempt, let fallback handle it.
|
|
164
|
+
// The fallback is expected to throw if it cannot recover.
|
|
165
|
+
finalResult = await this.execFallbackAsync(prepRes, e);
|
|
166
|
+
finalError = null; // If fallback doesn't throw, it "succeeded" in recovering
|
|
167
|
+
}
|
|
168
|
+
if (this.wait > 0)
|
|
169
|
+
await new Promise(resolve => setTimeout(resolve, this.wait * 1000));
|
|
170
|
+
}
|
|
134
171
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
finalError = e;
|
|
175
|
+
// Re-throw to stop the flow execution in _orchAsync
|
|
176
|
+
throw e;
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
if (emit) {
|
|
180
|
+
const nodeEndTime = performance.now();
|
|
181
|
+
emit('node:end', {
|
|
182
|
+
flowId,
|
|
183
|
+
nodeClass,
|
|
184
|
+
endTime: Date.now(),
|
|
185
|
+
duration: nodeEndTime - nodeStartTime,
|
|
186
|
+
status: finalError ? 'error' : 'success',
|
|
187
|
+
error: finalError ? { message: finalError.message, stack: finalError.stack } : null,
|
|
188
|
+
result: finalResult
|
|
189
|
+
});
|
|
140
190
|
}
|
|
141
191
|
}
|
|
192
|
+
return finalResult;
|
|
142
193
|
}
|
|
143
194
|
async runAsync(shared) {
|
|
144
195
|
if (Object.keys(this.successors).length) {
|
|
@@ -156,48 +207,92 @@ class AsyncNode extends Node {
|
|
|
156
207
|
}
|
|
157
208
|
}
|
|
158
209
|
class AsyncBatchNode extends AsyncNode {
|
|
159
|
-
async _exec(items) {
|
|
210
|
+
async _exec(items, shared, observer) {
|
|
160
211
|
const results = [];
|
|
161
212
|
for (const item of items) {
|
|
162
|
-
results.push(await super._exec(item));
|
|
213
|
+
results.push(await super._exec(item, shared, observer));
|
|
163
214
|
}
|
|
164
215
|
return results;
|
|
165
216
|
}
|
|
166
217
|
}
|
|
167
218
|
class AsyncParallelBatchNode extends AsyncNode {
|
|
168
|
-
async _exec(items) {
|
|
169
|
-
return await Promise.all(items.map(item => super._exec(item)));
|
|
219
|
+
async _exec(items, shared, observer) {
|
|
220
|
+
return await Promise.all(items.map(item => super._exec(item, shared, observer)));
|
|
170
221
|
}
|
|
171
222
|
}
|
|
172
223
|
class AsyncFlow extends Flow {
|
|
224
|
+
constructor(start = null) {
|
|
225
|
+
super(start);
|
|
226
|
+
this.listeners = {};
|
|
227
|
+
}
|
|
228
|
+
on(eventName, callback) {
|
|
229
|
+
if (!this.listeners[eventName]) {
|
|
230
|
+
this.listeners[eventName] = [];
|
|
231
|
+
}
|
|
232
|
+
this.listeners[eventName].push(callback);
|
|
233
|
+
}
|
|
234
|
+
emit(eventName, payload) {
|
|
235
|
+
if (this.listeners[eventName]) {
|
|
236
|
+
for (const callback of this.listeners[eventName]) {
|
|
237
|
+
try {
|
|
238
|
+
callback(payload);
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
console.error(`Error in event listener for '${eventName}':`, e);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
173
246
|
async prepAsync(shared) { }
|
|
174
247
|
async postAsync(shared, prepRes, execRes) {
|
|
175
248
|
return execRes;
|
|
176
249
|
}
|
|
177
|
-
async _orchAsync(shared, params = {}, initialNode = this.startNode) {
|
|
250
|
+
async _orchAsync(flowId, shared, params = {}, initialNode = this.startNode) {
|
|
178
251
|
let curr = initialNode;
|
|
179
252
|
let lastAction = null;
|
|
180
253
|
let lastExecRes = null;
|
|
181
254
|
let p = { ...this.params, ...params };
|
|
182
255
|
while (curr) {
|
|
183
256
|
curr.setParams(p);
|
|
257
|
+
const observerContext = { emit: this.emit.bind(this), flowId };
|
|
184
258
|
const prepRes = curr instanceof AsyncNode ? await curr.prepAsync(shared) : curr.prep(shared);
|
|
185
|
-
const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared) : curr._exec(prepRes, shared);
|
|
259
|
+
const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared, observerContext) : curr._exec(prepRes, shared);
|
|
186
260
|
lastAction = curr instanceof AsyncNode ? await curr.postAsync(shared, prepRes, execRes) : curr.post(shared, prepRes, execRes);
|
|
187
|
-
lastExecRes = execRes;
|
|
261
|
+
lastExecRes = execRes;
|
|
188
262
|
curr = this.getNextNode(curr, lastAction);
|
|
189
263
|
}
|
|
190
264
|
return lastExecRes;
|
|
191
265
|
}
|
|
192
266
|
async _runAsync(shared) {
|
|
193
|
-
const
|
|
194
|
-
const
|
|
195
|
-
|
|
267
|
+
const flowId = crypto.randomUUID();
|
|
268
|
+
const flowStartTime = performance.now();
|
|
269
|
+
this.emit('flow:start', { flowId, startTime: Date.now() });
|
|
270
|
+
let result;
|
|
271
|
+
let flowError = null;
|
|
272
|
+
try {
|
|
273
|
+
const prepRes = await this.prepAsync(shared);
|
|
274
|
+
result = await this._orchAsync(flowId, shared);
|
|
275
|
+
return await this.postAsync(shared, prepRes, result);
|
|
276
|
+
}
|
|
277
|
+
catch (e) {
|
|
278
|
+
flowError = e;
|
|
279
|
+
throw e; // Re-throw so the caller knows the flow failed
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
const flowEndTime = performance.now();
|
|
283
|
+
this.emit('flow:end', {
|
|
284
|
+
flowId,
|
|
285
|
+
endTime: Date.now(),
|
|
286
|
+
duration: flowEndTime - flowStartTime,
|
|
287
|
+
status: flowError ? 'error' : 'success',
|
|
288
|
+
error: flowError ? { message: flowError.message, stack: flowError.stack } : null,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
196
291
|
}
|
|
197
292
|
run() {
|
|
198
293
|
throw new Error("Use runAsync instead.");
|
|
199
294
|
}
|
|
200
|
-
async runAsync(shared) {
|
|
295
|
+
async runAsync(shared = {}) {
|
|
201
296
|
return await this._runAsync(shared);
|
|
202
297
|
}
|
|
203
298
|
}
|
|
@@ -206,7 +301,7 @@ class AsyncBatchFlow extends AsyncFlow {
|
|
|
206
301
|
const prepResults = await this.prepAsync(shared) || [];
|
|
207
302
|
const results = [];
|
|
208
303
|
for (const bp of prepResults) {
|
|
209
|
-
results.push(await this._orchAsync(shared, { ...this.params, ...bp }));
|
|
304
|
+
results.push(await this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }));
|
|
210
305
|
}
|
|
211
306
|
return await this.postAsync(shared, prepResults, results);
|
|
212
307
|
}
|
|
@@ -215,11 +310,9 @@ class AsyncParallelBatchFlow extends AsyncFlow {
|
|
|
215
310
|
async _runAsync(shared) {
|
|
216
311
|
const prepResults = await this.prepAsync(shared) || [];
|
|
217
312
|
const results = await Promise.all(prepResults.map(bp => {
|
|
218
|
-
// Create a new instance of the startNode for each batch item
|
|
219
313
|
const newStartNode = new this.startNode.constructor();
|
|
220
|
-
// Copy successors from the original startNode to the new instance
|
|
221
314
|
Object.assign(newStartNode.successors, this.startNode.successors);
|
|
222
|
-
return this._orchAsync(shared, { ...this.params, ...bp }, newStartNode);
|
|
315
|
+
return this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }, newStartNode);
|
|
223
316
|
}));
|
|
224
317
|
return await this.postAsync(shared, prepResults, results);
|
|
225
318
|
}
|
package/package.json
CHANGED