-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathasync-workflow.ts
More file actions
409 lines (364 loc) · 11.1 KB
/
async-workflow.ts
File metadata and controls
409 lines (364 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/**
* Async Workflow Example (n8n / Zapier style)
*
* Demonstrates async node execution with automatic parallelism.
* Independent branches run concurrently via Promise.all; nodes
* that share no data dependency execute in parallel.
*
* Workflow:
*
* ┌→ [fetch_user] ─────────→ user ─┐
* [webhook] ─ userId → ┤ ├→ [compose] ─ html → [send_email]
* ─ userId → └→ [fetch_orders] → [summarize] → summary ─┘
*
* - webhook: triggers the flow, outputs a userId
* - fetch_user: async lookup (simulated 120ms)
* - fetch_orders: async lookup (simulated 200ms) ← runs in parallel with fetch_user
* - summarize: sync transform on orders
* - compose: waits for BOTH user + summary, merges into email HTML
* - send_email: async side-effect (simulated 80ms)
*/
import {
createGraph,
type Graph,
type GraphNode,
type GraphEdge,
getTopologicalSort,
getEdgesByPort,
getPorts,
getSources,
} from '../src';
// --- Types ---
type StepFn = (inputs: Record<string, unknown>) => unknown | Promise<unknown>;
type NodeData = {
/** Human-readable label */
label: string;
/** The async (or sync) handler for this node */
run: StepFn;
};
type WorkflowGraph = Graph<NodeData>;
// --- Simulated services ---
const users: Record<string, { name: string; email: string }> = {
u1: { name: 'Alice', email: 'alice@example.com' },
u2: { name: 'Bob', email: 'bob@example.com' },
};
const orders: Record<string, { item: string; amount: number }[]> = {
u1: [
{ item: 'Widget', amount: 29.99 },
{ item: 'Gadget', amount: 49.99 },
],
u2: [{ item: 'Thingamajig', amount: 9.99 }],
};
function delay(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
// --- Build the workflow graph ---
const workflow: WorkflowGraph = createGraph<NodeData>({
initialNodeId: 'webhook',
nodes: [
{
id: 'webhook',
data: {
label: 'Webhook Trigger',
run: (inputs) => inputs['payload'],
},
ports: [
{ name: 'payload', direction: 'in' },
{ name: 'userId', direction: 'out' },
],
},
{
id: 'fetch_user',
data: {
label: 'Fetch User',
run: async (inputs) => {
await delay(120);
const id = inputs['userId'] as string;
return users[id] ?? { name: 'Unknown', email: 'unknown@example.com' };
},
},
ports: [
{ name: 'userId', direction: 'in' },
{ name: 'user', direction: 'out' },
],
},
{
id: 'fetch_orders',
data: {
label: 'Fetch Orders',
run: async (inputs) => {
await delay(200);
const id = inputs['userId'] as string;
return orders[id] ?? [];
},
},
ports: [
{ name: 'userId', direction: 'in' },
{ name: 'orders', direction: 'out' },
],
},
{
id: 'summarize',
data: {
label: 'Summarize Orders',
run: (inputs) => {
const items = inputs['orders'] as { item: string; amount: number }[];
const total = items.reduce((sum, o) => sum + o.amount, 0);
return `${items.length} order(s), total $${total.toFixed(2)}`;
},
},
ports: [
{ name: 'orders', direction: 'in' },
{ name: 'summary', direction: 'out' },
],
},
{
id: 'compose',
data: {
label: 'Compose Email',
run: (inputs) => {
const user = inputs['user'] as { name: string; email: string };
const summary = inputs['summary'] as string;
return {
to: user.email,
subject: `Order Summary for ${user.name}`,
html: `<p>Hi ${user.name},</p><p>${summary}</p>`,
};
},
},
ports: [
{ name: 'user', direction: 'in' },
{ name: 'summary', direction: 'in' },
{ name: 'email', direction: 'out' },
],
},
{
id: 'send_email',
data: {
label: 'Send Email',
run: async (inputs) => {
await delay(80);
const email = inputs['email'] as {
to: string;
subject: string;
html: string;
};
return { sent: true, to: email.to, subject: email.subject };
},
},
ports: [
{ name: 'email', direction: 'in' },
{ name: 'result', direction: 'out' },
],
},
],
edges: [
// webhook fans out to two parallel branches
{
id: 'e1',
sourceId: 'webhook',
targetId: 'fetch_user',
sourcePort: 'userId',
targetPort: 'userId',
},
{
id: 'e2',
sourceId: 'webhook',
targetId: 'fetch_orders',
sourcePort: 'userId',
targetPort: 'userId',
},
// orders branch
{
id: 'e3',
sourceId: 'fetch_orders',
targetId: 'summarize',
sourcePort: 'orders',
targetPort: 'orders',
},
// both branches merge into compose
{
id: 'e4',
sourceId: 'fetch_user',
targetId: 'compose',
sourcePort: 'user',
targetPort: 'user',
},
{
id: 'e5',
sourceId: 'summarize',
targetId: 'compose',
sourcePort: 'summary',
targetPort: 'summary',
},
// compose → send
{
id: 'e6',
sourceId: 'compose',
targetId: 'send_email',
sourcePort: 'email',
targetPort: 'email',
},
],
});
// --- Async runner with automatic parallelism ---
/**
* Groups topologically-sorted nodes into levels that can run in parallel.
* Nodes in the same level have all their dependencies satisfied by prior levels.
*/
function getLevels<N>(
g: Graph<N>,
sorted: GraphNode<N>[],
): GraphNode<N>[][] {
const nodeLevel = new Map<string, number>();
for (const node of sorted) {
let maxParentLevel = -1;
for (const edge of g.edges) {
if (edge.targetId === node.id) {
const parentLevel = nodeLevel.get(edge.sourceId) ?? 0;
maxParentLevel = Math.max(maxParentLevel, parentLevel);
}
}
nodeLevel.set(node.id, maxParentLevel + 1);
}
const levels: GraphNode<N>[][] = [];
for (const node of sorted) {
const level = nodeLevel.get(node.id)!;
if (!levels[level]) levels[level] = [];
levels[level].push(node);
}
return levels;
}
/**
* Run an async workflow graph to completion with automatic parallelism.
*
* Nodes at the same topological level execute concurrently via Promise.all.
* Each node's `data.run` function receives its input port values and
* returns output that is routed to downstream ports.
*
* @example
* ```ts
* const result = await runWorkflow(workflow, { userId: 'u1' });
* ```
*/
async function runWorkflow(
g: WorkflowGraph,
triggerPayload: unknown,
): Promise<{ outputs: Map<string, Record<string, unknown>>; log: string[] }> {
const sorted = getTopologicalSort(g);
if (!sorted) throw new Error('Cycle detected — workflow must be acyclic');
const levels = getLevels(g, sorted);
// portValues[nodeId][portName] = value
const portValues = new Map<string, Record<string, unknown>>();
const log: string[] = [];
for (const [levelIdx, level] of levels.entries()) {
const nodeNames = level.map((n) => n.data.label).join(', ');
const parallel = level.length > 1;
log.push(
`Level ${levelIdx}: ${parallel ? '⚡ parallel' : '→ sequential'} [${nodeNames}]`,
);
const start = performance.now();
await Promise.all(
level.map(async (node) => {
const nodeStart = performance.now();
// Gather input port values
const nodeInputs: Record<string, unknown> = {};
// Seed trigger node from payload
if (node.id === g.initialNodeId) {
nodeInputs['payload'] = triggerPayload;
}
// Collect from upstream edges
for (const edge of g.edges) {
if (edge.targetId === node.id && edge.targetPort && edge.sourcePort) {
const sourceVals = portValues.get(edge.sourceId);
if (sourceVals && edge.sourcePort in sourceVals) {
nodeInputs[edge.targetPort] = sourceVals[edge.sourcePort];
}
}
}
// Execute
const result = await node.data.run(nodeInputs);
const elapsed = (performance.now() - nodeStart).toFixed(0);
// Route output to all output ports (single-output convention)
const outPorts = getPorts(g, node.id).filter(
(p) => p.direction === 'out',
);
const outputs: Record<string, unknown> = {};
for (const port of outPorts) {
outputs[port.name] = result;
}
portValues.set(node.id, outputs);
log.push(` ✓ ${node.data.label} (${elapsed}ms)`);
}),
);
const levelElapsed = (performance.now() - start).toFixed(0);
if (parallel) {
log.push(` ⏱ level total: ${levelElapsed}ms (parallel — not sum)`);
}
}
return { outputs: portValues, log };
}
// --- Demo ---
async function main() {
console.log('=== Async Workflow (n8n / Zapier style) ===\n');
// Show graph structure
console.log('Nodes:');
for (const node of workflow.nodes) {
const ports = getPorts(workflow, node.id);
const inPorts = ports
.filter((p) => p.direction === 'in')
.map((p) => p.name);
const outPorts = ports
.filter((p) => p.direction === 'out')
.map((p) => p.name);
console.log(
` ${node.data.label} (${node.id}) in:[${inPorts}] out:[${outPorts}]`,
);
}
console.log('\nEdges:');
for (const edge of workflow.edges) {
console.log(
` ${edge.sourceId}:${edge.sourcePort} → ${edge.targetId}:${edge.targetPort}`,
);
}
console.log(`\ninitialNodeId: "${workflow.initialNodeId}"`);
// Show parallelism plan
const sorted = getTopologicalSort(workflow)!;
const levels = getLevels(workflow, sorted);
console.log(`\nExecution plan (${levels.length} levels):`);
for (const [i, level] of levels.entries()) {
const names = level.map((n) => n.data.label);
console.log(
` Level ${i}: ${names.join(' | ')}${level.length > 1 ? ' ⚡' : ''}`,
);
}
// Run for user u1
console.log('\n--- Run: userId = "u1" ---\n');
const { outputs, log } = await runWorkflow(workflow, 'u1');
for (const line of log) console.log(line);
const sendResult = outputs.get('send_email');
console.log(`\nResult: ${JSON.stringify(sendResult, null, 2)}`);
// Run for user u2
console.log('\n--- Run: userId = "u2" ---\n');
const { outputs: out2, log: log2 } = await runWorkflow(workflow, 'u2');
for (const line of log2) console.log(line);
const sendResult2 = out2.get('send_email');
console.log(`\nResult: ${JSON.stringify(sendResult2, null, 2)}`);
// Show port queries
console.log('\n--- Port queries ---');
console.log(
'Edges into compose:user →',
getEdgesByPort(workflow, 'compose', 'user').map((e) => e.id),
);
console.log(
'Edges into compose:summary →',
getEdgesByPort(workflow, 'compose', 'summary').map((e) => e.id),
);
// Show fan-out from webhook
const sources = getSources(workflow);
console.log(
'Source nodes (inDegree 0):',
sources.map((n) => n.id),
);
}
main();