async-nodes 0.1.0

An asynchronous, type-safe node engine implementing the Bulk Synchronous Parallel (BSP) model: control-flow loops, recovery, suspension, and serializable graphs, with dataflow-once pipelines as a profile.
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
use std::{collections::HashSet, sync::Arc};

use async_nodes::{
    BspContext, BspEngine, BspError, BspGraph, BspInterceptor, BspOutputMapExt, BspType, BspValue,
    EngineResult, NodeId, NodeOutcome, OutputPin, node, node_blocking,
};
use indexmap::IndexMap;

// =========================================================================
// 1. TELEMETRY OBSERVER FOR TESTING
// =========================================================================

struct TestInterceptor {
    events: Arc<std::sync::Mutex<Vec<String>>>,
}

impl TestInterceptor {
    fn push_event(&self, event: String) {
        if let Ok(mut guard) = self.events.lock() {
            guard.push(event);
        }
    }
}

impl BspInterceptor for TestInterceptor {
    fn on_node_start(&self, _node_id: NodeId, name: &str) {
        self.push_event(format!("START: {name}"));
    }

    fn on_node_complete(&self, _node_id: NodeId, name: &str, _duration: std::time::Duration) {
        self.push_event(format!("COMPLETE: {name}"));
    }

    fn on_node_error(&self, _node_id: NodeId, name: &str, _err: &BspError) {
        self.push_event(format!("ERROR: {name}"));
    }
}

// =========================================================================
// 2. CONTEXT STRUCTS FOR DEPENDENCY INJECTION
// =========================================================================

#[derive(Clone, Debug)]
struct DatabaseConnection {
    url: String,
}

impl async_nodes::typemap_rev::TypeMapKey for DatabaseConnection {
    type Value = Self;
}

#[derive(Clone, Debug)]
struct AppConfig {
    timeout_ms: u64,
}

impl async_nodes::typemap_rev::TypeMapKey for AppConfig {
    type Value = Self;
}

#[derive(Clone, Debug)]
struct HeavyResource {
    data: Vec<u8>,
}

impl async_nodes::typemap_rev::TypeMapKey for HeavyResource {
    type Value = std::sync::Arc<Self>;
}

// =========================================================================
// 3. TEST NODE DEFINITIONS USING #[node] AND #[node_blocking]
// =========================================================================

#[node("Generator")]
async fn generate_value() -> f64 {
    10.0
}

#[node("Multiply")]
async fn multiply_by_three(input: f64) -> f64 {
    input * 3.0
}

#[node("Source")]
async fn source_value() -> f64 {
    5.0
}

#[node("AddTen")]
async fn add_ten(val: f64) -> f64 {
    tokio::task::yield_now().await;
    val + 10.0
}

#[node("Double")]
async fn double_value(val: f64) -> f64 {
    tokio::task::yield_now().await;
    val * 2.0
}

#[node("Join")]
async fn join_values(left: f64, right: f64) -> f64 {
    left + right
}

#[node_blocking("ComputeHeavy")]
fn run_heavy_blocking_task(input: f64) -> f64 {
    // Simulate a synchronous thread block
    std::thread::sleep(std::time::Duration::from_millis(150));
    input * 5.0
}

#[node("Suspender")]
async fn suspension_checkpoint(val: f64, approved: Option<bool>) -> Result<NodeOutcome, String> {
    if approved == Some(true) {
        let mut out = IndexMap::new();
        out.insert(0, BspValue::new(val));
        out.insert(1, BspValue::new(true));
        Ok(NodeOutcome::Success(out))
    } else if val > 1.0 {
        Ok(NodeOutcome::Suspend {
            payload: serde_json::json!({ "prompt": "Authorize payout?", "amount": val }),
            waiting_inputs: vec![1],
        })
    } else {
        let mut out = IndexMap::new();
        out.insert(0, BspValue::new(val));
        out.insert(1, BspValue::new(false));
        Ok(NodeOutcome::Success(out))
    }
}

#[node("PostAuth")]
async fn handle_post_auth(original_amount: f64, approved: bool) -> f64 {
    if approved { original_amount } else { 0.0 }
}

// Custom structure utilizing the structural type-derive
#[derive(Clone, Debug, PartialEq, BspType)]
struct Transaction {
    id: String,
    amount: f64,
}

#[node("CreateTransaction")]
async fn create_transaction() -> Transaction {
    Transaction {
        id: "tx-4509".to_string(),
        amount: 150.0,
    }
}

#[node("CalculateTaxes")]
async fn calculate_taxes(tx: Transaction) -> f64 {
    tx.amount * 0.15
}

#[node("FormatFloat")]
async fn format_float(val: f64) -> String {
    format!("{val:.1}")
}

#[node("JoinStringCollection")]
async fn join_string_collection(input: Vec<String>) -> String {
    input.join(", ")
}

// Nodes leveraging context injection via owned-cloned semantics
#[node("QueryUser")]
async fn query_user(#[context] db: DatabaseConnection, user_id: f64) -> String {
    format!("User 42 from {} with id {}", db.url, user_id)
}

#[node("FetchTimeout")]
async fn fetch_timeout(#[context] config: AppConfig) -> f64 {
    #[allow(clippy::cast_precision_loss)]
    let timeout = config.timeout_ms as f64;

    timeout
}

// Blocking Node utilizing context-injected Arc (mapped explicitly to TypeMapKey HeavyResource)
#[node_blocking("HeavyDiskWrite")]
fn heavy_disk_write(
    #[context(HeavyResource)] resource: std::sync::Arc<HeavyResource>,
    file_prefix: String,
) -> String {
    std::thread::sleep(std::time::Duration::from_millis(50));
    format!(
        "Wrote prefix '{}' with resource size: {}",
        file_prefix,
        resource.data.len()
    )
}

// =========================================================================
// 4. CORE PIPELINE TESTS
// =========================================================================

#[tokio::test]
async fn test_sequential_pipeline() {
    let mut graph = BspGraph::new();

    let gen_node = graph.add_node(GenerateValueNode::new());
    let mul = graph.add_node(MultiplyByThreeNode::new());

    // Wire Generator Output (0) -> Multiply Input (0)
    graph.add_link(gen_node.output(), mul.input());

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let final_value: f64 = outputs.get_typed(mul.output()).unwrap();
        assert!((final_value - 30.0).abs() < f64::EPSILON);
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_blocking_node_execution() {
    let mut graph = BspGraph::new();

    let src = graph.add_node(SourceValueNode::new()); // Outputs 5.0
    let heavy = graph.add_node(RunHeavyBlockingTaskNode::new()); // 5.0 * 5.0 = 25.0

    graph.add_link(src.output(), heavy.input());

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let final_value: f64 = outputs.get_typed(heavy.output()).unwrap();
        assert!((final_value - 25.0).abs() < f64::EPSILON);
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_parallel_branch_join_determinism() {
    let mut graph = BspGraph::new();

    // Node 1: Source (Outputs 5.0)
    let src = graph.add_node(SourceValueNode::new());

    // Node 2 & 3: Level 1 Parallel Branches (AddTen & Double)
    let add = graph.add_node(AddTenNode::new());
    let dbl = graph.add_node(DoubleValueNode::new());

    // Node 4: Level 2 Join (Adds parallel outcomes together)
    let join = graph.add_node(JoinValuesNode::new());

    // Link output of Source (1) to inputs of AddTen (2) and Double (3)
    graph.add_link(src.output(), add.val());
    graph.add_link(src.output(), dbl.val());

    // Link outputs of AddTen (2) and Double (3) to inputs 0 and 1 of Join (4)
    graph.add_link(add.output(), join.left());
    graph.add_link(dbl.output(), join.right());

    let events = Arc::new(std::sync::Mutex::new(Vec::new()));
    let interceptor = Arc::new(TestInterceptor {
        events: events.clone(),
    });

    let engine = BspEngine::new(graph).with_interceptor(interceptor);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let sum: f64 = outputs.get_typed(join.output()).unwrap();

        // Mathematical verification: (5.0 + 10.0) + (5.0 * 2.0) = 25.0
        assert!((sum - 25.0).abs() < f64::EPSILON);

        // Verification of concurrency logging via interceptor
        // Assert Source starts first
        let events = events.lock().unwrap().clone();
        assert_eq!(events[0], "START: Source");
        assert_eq!(events[1], "COMPLETE: Source");

        // Assert Level 1 nodes ran in the same superstep
        let level_1_started: HashSet<&str> = events[2..4].iter().map(String::as_str).collect();
        assert!(level_1_started.contains("START: AddTen"));
        assert!(level_1_started.contains("START: Double"));

        // Assert Join Node was executed strictly last
        assert_eq!(*events.last().unwrap(), "COMPLETE: Join");
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_graph_suspension_and_resumption() {
    let mut graph = BspGraph::new();
    // Register nodes
    let src = graph.add_node(SourceValueNode::new()); // Outputs 5.0
    let susp = graph.add_node(SuspensionCheckpointNode::new()); // Suspends if input > 1.0
    let auth = graph.add_node(HandlePostAuthNode::new()); // Resolves outcome

    // Wire: Source (1) -> Suspender (2)
    graph.add_link(src.output(), susp.val());

    // Explicit dynamic wire mapping
    // Wire: Suspender (2) -> PostAuth (3)
    graph.add_link(
        OutputPin {
            node_id: susp.id,
            port: 0,
        },
        auth.original_amount(),
    );
    graph.add_link(
        OutputPin {
            node_id: susp.id,
            port: 1,
        },
        auth.approved(),
    );

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await.unwrap();

    match result {
        EngineResult::Suspended(suspended) => {
            // Verify suspension telemetry payload matches expectation
            assert_eq!(suspended.suspensions.len(), 1);
            let suspension = &suspended.suspensions[0];
            assert_eq!(suspension.node_id, susp.id);
            assert_eq!(suspension.waiting_inputs, vec![1]);

            // Simulate host intervention: Inject authorization boolean (true) into waiting input pin (1) of node (2)
            let mut injections = IndexMap::new();
            injections.insert(susp.approved(), BspValue::new(true));

            // Resume execution
            let resumed_result = engine.resume(*suspended, injections).await.unwrap();

            if let EngineResult::Complete(outputs) = resumed_result {
                let amount: f64 = outputs.get_typed(auth.output()).unwrap();

                // PostAuth output should match approved original amount
                assert!((amount - 5.0).abs() < f64::EPSILON);
            } else {
                panic!("Resumed execution failed to complete.");
            }
        }
        EngineResult::Complete(_) => panic!("Graph execution should have suspended."),
        EngineResult::StepLimitReached(_) => panic!("Graph execution should have suspended."),
    }
}

#[tokio::test]
async fn test_cycle_validation() {
    let mut graph = BspGraph::new();

    // Create an invalid cyclic loop: Node 1 -> Node 2 -> Node 1
    let node1 = graph.add_node(AddTenNode::new());
    let node2 = graph.add_node(DoubleValueNode::new());

    graph.add_link(node1.output(), node2.val());
    graph.add_link(node2.output(), node1.val());

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await;

    // Verify engine caught circular deadlock before executing
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BspError::CycleDetected { .. }
    ));
}

#[tokio::test]
async fn test_custom_type_and_ergonomics() {
    let mut graph = BspGraph::new();

    // 1. Auto-incrementing node additions
    let src = graph.add_node(CreateTransactionNode::new());
    let tax = graph.add_node(CalculateTaxesNode::new());

    // 2. Type-safe, handle-based linking
    graph.add_link(src.output(), tax.tx());

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        // 3. Clean type-safe downcasting helper
        let calculated_tax: f64 = outputs.get_typed(tax.output()).unwrap();
        assert!((calculated_tax - 22.5).abs() < f64::EPSILON);
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_multiple_inputs_into_single_port() {
    let mut graph = BspGraph::new();

    // Source 1 and Source 2
    let src1 = graph.add_node(AddTenNode::new()); // Output is f64
    let src2 = graph.add_node(DoubleValueNode::new()); // Output is f64

    // Formatter nodes to turn floats into Strings
    let fmt1 = graph.add_node(FormatFloatNode::new());
    let fmt2 = graph.add_node(FormatFloatNode::new());

    // Target aggregation node taking Vec<String>
    let joiner = graph.add_node(JoinStringCollectionNode::new());

    // Set static inputs to our parallel pipelines
    graph.set_static_input(src1.val(), 10.0); // 10.0 + 10.0 = 20.0
    graph.set_static_input(src2.val(), 10.0); // 10.0 * 2.0 = 20.0

    // Connect source nodes to formatters
    graph.add_link(src1.output(), fmt1.val());
    graph.add_link(src2.output(), fmt2.val());

    // Connect BOTH formatters into the exact same input port of the joiner
    graph.add_link(fmt1.output(), joiner.input());
    graph.add_link(fmt2.output(), joiner.input());

    let engine = BspEngine::new(graph);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let final_string: String = outputs.get_typed(joiner.output()).unwrap();

        // Assert both strings are compiled, aggregated, and joined in parallel supersteps
        let parts: Vec<&str> = final_string.split(", ").collect();
        assert_eq!(parts.len(), 2);
        assert!(parts.contains(&"20.0"));
    } else {
        panic!("The execution pipeline should have finished successfully.");
    }
}

// =========================================================================
// 5. CONTEXT DEPENDENCY INJECTION TESTS
// =========================================================================

#[tokio::test]
async fn test_dependency_injection_async_owned() {
    let mut graph = BspGraph::new();

    let query_node = graph.add_node(QueryUserNode::new());
    graph.set_static_input(query_node.user_id(), 42.0);

    let ctx = BspContext::new();
    ctx.insert::<DatabaseConnection>(DatabaseConnection {
        url: "postgres://localhost:5432".to_string(),
    });

    let engine = BspEngine::new(graph).with_context(ctx);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let outcome: String = outputs.get_typed(query_node.output()).unwrap();
        assert_eq!(outcome, "User 42 from postgres://localhost:5432 with id 42");
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_dependency_injection_async_clone() {
    let mut graph = BspGraph::new();

    let config_node = graph.add_node(FetchTimeoutNode::new());

    let ctx = BspContext::new();
    ctx.insert::<AppConfig>(AppConfig { timeout_ms: 1500 });

    let engine = BspEngine::new(graph).with_context(ctx);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let val: f64 = outputs.get_typed(config_node.output()).unwrap();
        assert!((val - 1500.0).abs() < f64::EPSILON);
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_dependency_injection_blocking_task() {
    let mut graph = BspGraph::new();

    let write_node = graph.add_node(HeavyDiskWriteNode::new());
    graph.set_static_input(write_node.file_prefix(), "backup_v1".to_string());

    let ctx = BspContext::new();
    ctx.insert::<HeavyResource>(std::sync::Arc::new(HeavyResource {
        data: vec![0, 1, 2, 3, 4],
    }));

    let engine = BspEngine::new(graph).with_context(ctx);
    let result = engine.run(()).await.unwrap();

    if let EngineResult::Complete(outputs) = result {
        let outcome: String = outputs.get_typed(write_node.output()).unwrap();
        assert_eq!(outcome, "Wrote prefix 'backup_v1' with resource size: 5");
    } else {
        panic!("Execution should have finished to completion.");
    }
}

#[tokio::test]
async fn test_missing_context_dependency_validation_error() {
    let mut graph = BspGraph::new();
    let _query_node = graph.add_node(QueryUserNode::new());

    let ctx = BspContext::new();
    let engine = BspEngine::new(graph).with_context(ctx);
    let result = engine.run(()).await;

    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("Dependency injection failed"));
    assert!(err_msg.contains("DatabaseConnection"));
}