reflow_network 0.2.1

Network executor for Reflow โ€” routes messages between actors, manages subgraphs, and emits runtime events.
Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Comprehensive Test Example for Reflow Network WASM Bindings
// Tests: 1. Graph Creation, 2. Stateful Actors, 3. Network Composition

import init, {
  Graph,
  GraphNetwork,
  GraphHistory,
  Network,
  MemoryState,
  WasmActorContext,
  JsWasmActor,
  init_panic_hook,
  ActorRunContext
} from '../pkg/reflow_network.js';

// WASM initialization flag
let wasmInitialized = false;

// ============================================================================
// 1. STATEFUL ACTOR IMPLEMENTATIONS
// ============================================================================

/**
 * Generator Actor - Produces sequential numbers with state tracking
 */
class GeneratorActor {
  constructor() {
    this.inports = ["trigger"];
    this.outports = ["output"];
    this.state = null; // Will be injected by WASM bridge
    this.config = { maxCount: 10, step: 1 };
  }

  /**
   * 
   * @param {ActorRunContext} context 
   */
  run(context) {
    const currentCount = context.state.get("counter") || 0;
    const generated = context.state.get("generated") || [];
    const maxCount = this.config.maxCount;

    if (currentCount < maxCount) {
      const newValue = currentCount + this.config.step;

      // Update state through context
      context.state.set("counter", newValue);
      generated.push(newValue);
      context.state.set("generated", generated);

      console.log(`๐Ÿ”ข Generator: Produced ${newValue} (${newValue}/${maxCount})`);

      // Send the generated number through context
      context.send({
        output: {
          value: newValue,
          sequence: newValue,
          isLast: newValue >= maxCount
        }
      });
    } else {
      console.log("๐Ÿ”ข Generator: Reached maximum count, stopping");
      context.send({ output: { value: null, isLast: true } });
    }
  }

  getState() {
    return this.state ? this.state.getAll() : {};
  }

  setState(newState) {
    if (this.state) {
      this.state.setAll(newState);
    }
  }
}

/**
 * Accumulator Actor - Maintains running sum with state persistence
 */
class AccumulatorActor {
  constructor() {
    this.inports = ["input"];
    this.outports = ["sum", "average"];
    this.state = null; // Will be injected by WASM bridge
    this.config = { precision: 2 };
  }
  /**
   * 
   * @param {ActorRunContext} context 
   */
  run(context) {
    if (context.input && context.input.input !== null) {
      const value = context.input.input.value;
      const currentTotal = context.state.get("total") || 0;
      const currentCount = context.state.get("count") || 0;
      const values = context.state.get("values") || [];

      // Update state through context
      const newTotal = currentTotal + value;
      const newCount = currentCount + 1;
      values.push(value);

      context.state.set("total", newTotal);
      context.state.set("count", newCount);
      context.state.set("values", values);

      const average = newTotal / newCount;

      console.log(`๐Ÿ“Š Accumulator: Added ${value}, Total: ${newTotal}, Avg: ${average.toFixed(this.config.precision)}`);

      // Send results through context
      context.send({
        sum: {
          total: newTotal,
          count: newCount,
          lastValue: value
        },
        average: {
          value: average,
          precision: this.config.precision,
          sampleSize: newCount
        }
      });
    }
  }

  getState() {
    return this.state ? this.state.getAll() : {};
  }

  setState(newState) {
    if (this.state) {
      this.state.setAll(newState);
    }
  }
}

/**
 * Filter Actor - Filters values based on configurable criteria with state
 */
class FilterActor {
  constructor() {
    this.inports = ["input"];
    this.outports = ["passed", "filtered"];
    this.state = null; // Will be injected by WASM bridge
    this.config = {
      minValue: 3,
      maxValue: 8,
      filterType: "range" // "range", "even", "odd"
    };
  }

  /**
 * 
 * @param {ActorRunContext} context 
 */
  run(context) {
    if (context.input && context.input.input !== undefined) {
      const value = context.input.input.count;
      const passedCount = context.state.get("passedCount") || 0;
      const filteredCount = context.state.get("filteredCount") || 0;
      const passedValues = context.state.get("passedValues") || [];
      const filteredValues = context.state.get("filteredValues") || [];

      let passes = false;

      // Apply filter logic based on configuration
      switch (this.config.filterType) {
        case "range":
          passes = value >= this.config.minValue && value <= this.config.maxValue;
          break;
        case "even":
          passes = value % 2 === 0;
          break;
        case "odd":
          passes = value % 2 !== 0;
          break;
        default:
          passes = true;
      }

      if (passes) {
        context.state.set("passedCount", passedCount + 1);
        passedValues.push(value);
        context.state.set("passedValues", passedValues);

        console.log(`โœ… Filter: PASSED ${value} (${passedCount + 1} total passed)`);
        context.send({
          passed: {
            value: value,
            reason: `Meets ${this.config.filterType} criteria`,
            passedCount: passedCount + 1
          }
        });
      } else {
        context.state.set("filteredCount", filteredCount + 1);
        filteredValues.push(value);
        context.state.set("filteredValues", filteredValues);

        console.log(`โŒ Filter: FILTERED ${value} (${filteredCount + 1} total filtered)`);
        context.send({
          filtered: {
            value: value,
            reason: `Does not meet ${this.config.filterType} criteria`,
            filteredCount: filteredCount + 1
          }
        });
      }
    }
  }

  getState() {
    return this.state ? this.state.getAll() : {};
  }

  setState(newState) {
    if (this.state) {
      this.state.setAll(newState);
    }
  }
}

/**
 * Logger Actor - Tracks and logs all messages with detailed state
 */
class LoggerActor {
  constructor() {
    this.inports = ["input"];
    this.outports = ["log"];
    this.state = null; // Will be injected by WASM bridge
    this.config = { logLevel: "info", maxLogs: 100 };
  }
  /**
   * 
   * @param {ActorRunContext} context 
   */
  run(context) {
    const messageCount = context.state.get("messageCount") || 0;
    const logs = context.state.get("logs") || [];
    const startTime = context.state.get("startTime") || Date.now();

    // Initialize startTime if not set
    if (!context.state.has("startTime")) {
      context.state.set("startTime", Date.now());
    }

    const logEntry = {
      id: messageCount + 1,
      timestamp: Date.now(),
      elapsed: Date.now() - startTime,
      data: context.input.input,
      source: "filter"
    };

    // Update state through context
    context.state.set("messageCount", messageCount + 1);
    logs.push(logEntry);

    // Keep only the last maxLogs entries
    if (logs.length > this.config.maxLogs) {
      logs.shift();
    }
    context.state.set("logs", logs);

    console.log(`๐Ÿ“ Logger: Message #${logEntry.id} after ${logEntry.elapsed}ms - ${JSON.stringify(context.input.input)}`);

    context.send({
      log: {
        entry: logEntry,
        totalMessages: messageCount + 1,
        uptime: logEntry.elapsed
      }
    });
  }

  getState() {
    return this.state ? this.state.getAll() : {};
  }

  setState(newState) {
    if (this.state) {
      this.state.setAll(newState);
    }
  }
}

// ============================================================================
// 2. GRAPH CREATION AND MANAGEMENT
// ============================================================================

function createProcessingGraph() {
  console.log("\n๐Ÿ—๏ธ  Creating Processing Graph...");

  // Create a new graph with metadata
  const graph = new Graph("DataProcessingPipeline", true, {
    description: "A comprehensive data processing pipeline with stateful actors",
    version: "1.0.0",
    author: "Reflow Network Test",
    created: new Date().toISOString()
  });

  // Add nodes to the graph
  console.log("๐Ÿ“ฆ Adding nodes to graph...");

  graph.addNode("generator", "GeneratorActor", {
    x: 100, y: 100,
    description: "Generates sequential numbers"
  });

  graph.addNode("accumulator", "AccumulatorActor", {
    x: 300, y: 100,
    description: "Accumulates and averages values"
  });

  graph.addNode("filter", "FilterActor", {
    x: 500, y: 100,
    description: "Filters values based on criteria"
  });

  graph.addNode("logger", "LoggerActor", {
    x: 700, y: 100,
    description: "Logs all processed messages"
  });

  // Add connections between nodes
  console.log("๐Ÿ”— Adding connections...");

  graph.addConnection("generator", "output", "accumulator", "input", {
    label: "Generated numbers",
    color: "#4CAF50"
  });

  graph.addConnection("accumulator", "sum", "filter", "input", {
    label: "Accumulated sums",
    color: "#2196F3"
  });

  graph.addConnection("filter", "passed", "logger", "input", {
    label: "Filtered results",
    color: "#FF9800"
  });

  // Add initial data to trigger the pipeline
  graph.addInitial({ trigger: true, timestamp: Date.now() }, "generator", "trigger", {
    description: "Initial trigger to start generation"
  });

  // Add graph-level inports and outports
  graph.addInport("start", "generator", "trigger", { type: "flow" }, {
    description: "External trigger to start the pipeline"
  });

  graph.addOutport("results", "logger", "log", { type: "object", value: "log" }, {
    description: "Final processed results"
  });

  // let graph_export = graph.toJSON();
  // console.log("โœ… Graph created successfully!");
  // console.log(`   - Nodes: ${Object.keys(graph_export.processes || {}).length}`);
  // console.log(`   - Connections: ${(graph_export.connections || []).length}`);

  return graph;
}

// ============================================================================
// 3. NETWORK COMPOSITION AND EXECUTION
// ============================================================================

async function createAndRunNetwork() {
  console.log("\n๐Ÿš€ Creating and Starting Network...");



  // Create a graph network with history support
  const [graphWithHistory, history] = Graph.withHistoryAndLimit(50);

  // Load our graph into the history-enabled graph
  // const loadedGraph = Graph.load(graph.toJSON(), {});

  const graph = createProcessingGraph();

  // Create the network from the graph
  const network = new GraphNetwork(graph);

  // Register all our actor implementations
  console.log("๐ŸŽญ Registering actors...");

  network.registerActor("GeneratorActor", new GeneratorActor());
  network.registerActor("AccumulatorActor", new AccumulatorActor());
  network.registerActor("FilterActor", new FilterActor());
  network.registerActor("LoggerActor", new LoggerActor());

  // Set up event listening
  let eventCount = 0;
  network.next((event) => {
    eventCount++;
    console.log(`๐Ÿ“ก Network Event #${eventCount}:`, JSON.stringify({
      type: event._type,
      actor: event.actorId,
      port: event.port,
      hasData: !!event.data
    }));
  });

  // Start the network
  console.log("๐ŸŽฌ Starting network...");
  await network.start();

  console.log("โœ… Network started successfully!");

  // Let the pipeline run for a while
  console.log("\nโณ Running pipeline for 5 seconds...");

  return new Promise((resolve) => {
    setTimeout(async () => {
      console.log("\n๐Ÿ›‘ Stopping network...");
      network.shutdown();

      console.log(`๐Ÿ“Š Final Statistics:`);
      console.log(`   - Total network events: ${eventCount}`);
      console.log(`   - Pipeline completed successfully`);

      resolve({
        graph,
        history: history,
        eventCount: eventCount
      });
    }, 5000);
  });
}

// ============================================================================
// 4. DEMONSTRATION OF GRAPH HISTORY AND STATE MANAGEMENT
// ============================================================================

function demonstrateGraphHistory(graph, history) {
  console.log("\n๐Ÿ“š Demonstrating Graph History...");

  // Get initial state
  const initialState = history.getState();
  console.log("Initial history state:", JSON.stringify({
    canUndo: initialState.can_undo,
    canRedo: initialState.can_redo,
    undoSize: initialState.undo_size
  }));

  // Make some changes to demonstrate history
  console.log("Making changes to graph...");

  // Add a new node
  graph.addNode("monitor", "MonitorActor", {
    x: 900, y: 100,
    description: "Monitors system performance"
  });

  // Process events to update history
  history.processEvents(graph);

  // Check history state after changes
  const afterChanges = history.getState();
  console.log("After changes:", JSON.stringify({
    canUndo: afterChanges.can_undo,
    canRedo: afterChanges.can_redo,
    undoSize: afterChanges.undo_size
  }));

  // Demonstrate undo
  if (afterChanges.can_undo) {
    console.log("Performing undo...");
    history.undo(graph);

    const afterUndo = history.getState();
    console.log("After undo:", JSON.stringify({
      canUndo: afterUndo.can_undo,
      canRedo: afterUndo.can_redo,
      redoSize: afterUndo.redo_size
    }));
  }

  // Demonstrate redo
  if (history.getState().can_redo) {
    console.log("Performing redo...");
    history.redo(graph);

    const afterRedo = history.getState();
    console.log("After redo:", JSON.stringify({
      canUndo: afterRedo.can_undo,
      canRedo: afterRedo.can_redo
    }));
  }
}

// ============================================================================
// 5. WASM INITIALIZATION AND MAIN EXECUTION FUNCTION
// ============================================================================

async function initializeWasm() {
  if (!wasmInitialized) {
    console.log("๐Ÿ”ง Initializing WASM module...");
    await init();
    init_panic_hook();
    wasmInitialized = true;
    console.log("โœ… WASM module initialized successfully");
  }
}

async function runComprehensiveTest() {
  console.log("๐Ÿงช Starting Comprehensive Reflow Network Test");
  console.log("=".repeat(60));

  try {
    // Ensure WASM is initialized before running tests
    await initializeWasm();

    // // Test 1: Graph Creation
    // console.log("\n1๏ธโƒฃ  TESTING GRAPH CREATION");
    // const graph = createProcessingGraph();



    // Test 2: Network Composition and Execution
    console.log("\n2๏ธโƒฃ  TESTING NETWORK COMPOSITION & EXECUTION");
    const result = await createAndRunNetwork();

    //  // Export and display graph structure
    // const graphExport = graph.toJSON();
    // console.log("๐Ÿ“‹ Graph Export Summary:");
    // console.log(`   - Case Sensitive: ${graphExport.caseSensitive}`);
    // console.log(`   - Properties: ${JSON.stringify(graphExport.properties)}`);
    // console.log(`   - Processes: ${Object.keys(graphExport.processes || {}).length}`);
    // console.log(`   - Connections: ${(graphExport.connections || []).length}`);
    // console.log(`   - Inports: ${Object.keys(graphExport.inports || {}).length}`);
    // console.log(`   - Outports: ${Object.keys(graphExport.outports || {}).length}`);

    // Test 3: Graph History and State Management
    console.log("\n3๏ธโƒฃ  TESTING GRAPH HISTORY & STATE MANAGEMENT");
    demonstrateGraphHistory(result.graph, result.history);

    // Test 4: Actor State Inspection
    console.log("\n4๏ธโƒฃ  TESTING ACTOR STATE INSPECTION");
    console.log("Note: Actor states would be inspected during network execution");
    console.log("Each actor maintains its own MemoryState with persistent data");

    console.log("\n" + "=".repeat(60));
    console.log("โœ… ALL TESTS COMPLETED SUCCESSFULLY!");
    console.log("๐ŸŽ‰ Reflow Network WASM bindings are working correctly!");

    return {
      success: true,
      testsRun: 4,
      graphNodes: Object.keys(result.graph.toJSON().processes || {}).length,
      networkEvents: result.eventCount
    };

  } catch (error) {
    console.error("\nโŒ TEST FAILED:", error);
    console.error("Stack trace:", error.stack);
    return {
      success: false,
      error: error.message
    };
  }
}

// ============================================================================
// 6. EXPORT AND EXECUTION
// ============================================================================

// Export for use in other modules
export {
  GeneratorActor,
  AccumulatorActor,
  FilterActor,
  LoggerActor,
  createProcessingGraph,
  createAndRunNetwork,
  demonstrateGraphHistory,
  runComprehensiveTest
};

// Auto-run if this is the main module
if (typeof window !== 'undefined') {
  // Browser environment
  window.runReflowTest = runComprehensiveTest;
  console.log("๐ŸŒ Browser environment detected. Call window.runReflowTest() to start the test.");
} else {
  // Node.js environment - Initialize WASM before running tests
  (async () => {
    try {
      const result = await runComprehensiveTest();
      console.log("\n๐Ÿ“Š Final Test Result:", result);
      process.exit(result.success ? 0 : 1);
    } catch (error) {
      console.error("๐Ÿ’ฅ Unhandled error:", error);
      process.exit(1);
    }
  })();
}