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
use std::{
    any::{Any, type_name},
    fmt,
    sync::Arc,
};

use indexmap::IndexMap;

use super::{
    error::BspError,
    graph::{NodeId, OutputPin, PortIndex},
    node::NodeOutcome,
};

/// A marker type used to propagate bypassed execution paths in dynamic control-flow topologies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BspSkip;

/// A thread-safe, reference-counted container wrapping arbitrary Rust types.
#[derive(Clone)]
pub struct BspValue {
    inner: Arc<dyn Any + Send + Sync>,
    type_name: &'static str,
}

impl fmt::Debug for BspValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BspValue")
            .field("type_name", &self.type_name)
            .finish_non_exhaustive()
    }
}

impl BspValue {
    pub fn new<T: Any + Send + Sync>(val: T) -> Self {
        Self {
            inner: Arc::new(val) as Arc<dyn Any + Send + Sync>,
            type_name: type_name::<T>(),
        }
    }

    #[must_use]
    pub const fn type_name(&self) -> &'static str {
        self.type_name
    }

    #[must_use]
    pub fn is<T: Any>(&self) -> bool {
        self.inner.as_ref().is::<T>()
    }

    pub fn downcast<T: Any + Send + Sync>(self) -> Result<Arc<T>, Self> {
        if self.is::<T>() {
            let type_name = self.type_name;
            match self.inner.downcast::<T>() {
                Ok(arc_t) => Ok(arc_t),
                Err(arc_any) => Err(Self {
                    inner: arc_any,
                    type_name,
                }),
            }
        } else {
            Err(self)
        }
    }

    #[must_use]
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.inner.as_ref().downcast_ref::<T>()
    }

    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
        Arc::get_mut(&mut self.inner)?.downcast_mut::<T>()
    }
}

// =========================================================================
// TRAITS FOR MACRO INTEGRATION & STATIC DISPATCH
// =========================================================================

/// Translates a raw `BspValue` back into a typed parameter.
pub trait BspFromValue: Sized {
    fn from_value(value: BspValue, node_id: NodeId, port: PortIndex) -> Result<Self, BspError>;
}

/// Serializes a typed output back into a type-erased `BspValue` container.
pub trait BspToValue {
    fn to_value(self) -> BspValue;
}

/// Standardized boundary compiler that converts functional return types into `NodeOutcome`.
pub trait BspOutputPacker {
    fn output_ports() -> Vec<PortIndex>;
    fn pack(self, node_id: NodeId, node_name: &str) -> Result<NodeOutcome, BspError>;

    /// Packs typed outputs into the raw port map — the form
    /// [`crate::node::DataflowNode`] implementors return.
    ///
    /// The default routes through [`BspOutputPacker::pack`]; a `Suspend` outcome has no
    /// port map and is rejected as a validation error (dataflow nodes never suspend —
    /// suspend-capable nodes implement [`crate::node::BspNode`] directly).
    fn pack_outputs(
        self,
        node_id: NodeId,
        node_name: &str,
    ) -> Result<IndexMap<PortIndex, BspValue>, BspError>
    where
        Self: Sized,
    {
        match self.pack(node_id, node_name)? {
            NodeOutcome::Success(outputs) => Ok(outputs),
            NodeOutcome::Suspend { .. } => Err(BspError::ValidationError(format!(
                "node '{node_name}' suspended: suspend outcomes have no port map; \
                 implement BspNode directly for suspend-capable nodes"
            ))),
        }
    }

    /// Returns whether this output compiles dynamic outputs that bypass static validation checks.
    #[must_use]
    fn is_dynamic() -> bool {
        false
    }
}

// Support wrapping directly into Arc references
impl<T: Any + Send + Sync> BspFromValue for Arc<T> {
    fn from_value(value: BspValue, node_id: NodeId, port: PortIndex) -> Result<Self, BspError> {
        let found_type = value.type_name();
        value.downcast::<T>().map_err(|_| BspError::TypeMismatch {
            node_id,
            port_index: port,
            expected: type_name::<T>(),
            found: found_type,
        })
    }
}

impl<T: Any + Send + Sync> BspToValue for Arc<T> {
    fn to_value(self) -> BspValue {
        BspValue {
            inner: self as Arc<dyn Any + Send + Sync>,
            type_name: type_name::<T>(),
        }
    }
}

impl<T: BspFromValue> BspFromValue for Option<T> {
    fn from_value(value: BspValue, node_id: NodeId, port: PortIndex) -> Result<Self, BspError> {
        if value.is::<BspSkip>() {
            Ok(None)
        } else {
            T::from_value(value, node_id, port).map(Some)
        }
    }
}

impl<T: BspToValue + 'static> BspToValue for Option<T> {
    fn to_value(self) -> BspValue {
        self.map_or_else(|| BspValue::new(BspSkip), BspToValue::to_value)
    }
}

impl<T: BspToValue + 'static> BspOutputPacker for Option<T> {
    fn output_ports() -> Vec<PortIndex> {
        vec![0]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        let mut outputs = IndexMap::new();
        outputs.insert(0, self.to_value());
        Ok(NodeOutcome::Success(outputs))
    }
}

// Core suspension pass-through implementations
impl BspOutputPacker for NodeOutcome {
    fn output_ports() -> Vec<PortIndex> {
        vec![0]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        Ok(self)
    }
    fn is_dynamic() -> bool {
        true
    }
}

// Support returning Arc directly
impl<T: Any + Send + Sync> BspOutputPacker for Arc<T> {
    fn output_ports() -> Vec<PortIndex> {
        vec![0]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        let mut outputs = IndexMap::new();
        outputs.insert(0, self.to_value());
        Ok(NodeOutcome::Success(outputs))
    }
}

// Void return support
impl BspOutputPacker for () {
    fn output_ports() -> Vec<PortIndex> {
        Vec::new()
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        Ok(NodeOutcome::Success(IndexMap::new()))
    }
}

// Single generic output compiler routing standard results beautifully
impl<T: BspOutputPacker, E: std::fmt::Display> BspOutputPacker for Result<T, E> {
    fn output_ports() -> Vec<PortIndex> {
        T::output_ports()
    }
    fn pack(self, node_id: NodeId, node_name: &str) -> Result<NodeOutcome, BspError> {
        match self {
            Ok(val) => val.pack(node_id, node_name),
            Err(e) => Err(BspError::NodeExecutionFailed {
                node_id,
                node_name: node_name.to_string(),
                message: e.to_string(),
            }),
        }
    }
    fn is_dynamic() -> bool {
        T::is_dynamic()
    }
}

// =========================================================================
// MULTIPLE-PORT TUPLE OUTPUT PACKING
// =========================================================================

impl<T1, T2> BspOutputPacker for (T1, T2)
where
    T1: BspToValue + 'static,
    T2: BspToValue + 'static,
{
    fn output_ports() -> Vec<PortIndex> {
        vec![0, 1]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        let mut outputs = IndexMap::new();
        outputs.insert(0, self.0.to_value());
        outputs.insert(1, self.1.to_value());
        Ok(NodeOutcome::Success(outputs))
    }
}

impl<T1, T2, T3> BspOutputPacker for (T1, T2, T3)
where
    T1: BspToValue + 'static,
    T2: BspToValue + 'static,
    T3: BspToValue + 'static,
{
    fn output_ports() -> Vec<PortIndex> {
        vec![0, 1, 2]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        let mut outputs = IndexMap::new();
        outputs.insert(0, self.0.to_value());
        outputs.insert(1, self.1.to_value());
        outputs.insert(2, self.2.to_value());
        Ok(NodeOutcome::Success(outputs))
    }
}

// =========================================================================
// BLANKET AGGREGATION & VECTOR PACKING
// =========================================================================

impl<T: BspFromValue + Clone + Send + Sync + 'static> BspFromValue for Vec<T> {
    fn from_value(value: BspValue, node_id: NodeId, port: PortIndex) -> Result<Self, BspError> {
        if value.is::<BspSkip>() {
            return Ok(Self::new());
        }

        // Resolves recursive vector wrapping bugs by validating direct type downcasts
        if value.is::<Self>() {
            let arc_vec = value
                .downcast::<Self>()
                .map_err(|err| BspError::TypeMismatch {
                    node_id,
                    port_index: port,
                    expected: std::any::type_name::<Self>(),
                    found: err.type_name(), // Uses the returned BspValue ownership to extract the type name
                })?;
            return Ok((*arc_vec).clone());
        }

        if let Some(vec_bsp) = value.downcast_ref::<Vec<BspValue>>() {
            let mut result = Self::with_capacity(vec_bsp.len());
            for val in vec_bsp {
                if !val.is::<BspSkip>() {
                    result.push(T::from_value(val.clone(), node_id, port)?);
                }
            }
            Ok(result)
        } else {
            Ok(vec![T::from_value(value, node_id, port)?])
        }
    }
}

impl<T: BspToValue + Send + Sync + 'static> BspToValue for Vec<T> {
    fn to_value(self) -> BspValue {
        BspValue::new(self)
    }
}

impl<T: BspToValue + Send + Sync + 'static> BspOutputPacker for Vec<T> {
    fn output_ports() -> Vec<PortIndex> {
        vec![0]
    }
    fn pack(self, _node_id: NodeId, _node_name: &str) -> Result<NodeOutcome, BspError> {
        let mut outputs = IndexMap::new();
        outputs.insert(0, self.to_value());
        Ok(NodeOutcome::Success(outputs))
    }
}

// =========================================================================
// ERGONOMIC MAP DOWNCASTING EXTENSIONS
// =========================================================================

pub trait BspOutputMapExt {
    fn get_typed<T: std::any::Any + Send + Sync + Clone>(
        &self,
        pin: OutputPin,
    ) -> Result<T, BspError>;
}

impl BspOutputMapExt for IndexMap<OutputPin, BspValue> {
    fn get_typed<T: std::any::Any + Send + Sync + Clone>(
        &self,
        pin: OutputPin,
    ) -> Result<T, BspError> {
        let value = self.get(&pin).ok_or(BspError::NodeNotFound {
            node_id: pin.node_id,
        })?;
        let found_type = value.type_name();
        let arc_t = value
            .clone()
            .downcast::<T>()
            .map_err(|_| BspError::TypeMismatch {
                node_id: pin.node_id,
                port_index: pin.port,
                expected: std::any::type_name::<T>(),
                found: found_type,
            })?;
        Ok((*arc_t).clone())
    }
}

// =========================================================================
// PRIMITIVE TYPE REGISTRATION
// =========================================================================

#[macro_export]
macro_rules! register_bsp_type {
    ($t:ty) => {
        impl $crate::value::BspFromValue for $t {
            fn from_value(
                value: $crate::value::BspValue,
                node_id: $crate::graph::NodeId,
                port: $crate::graph::PortIndex,
            ) -> Result<Self, $crate::error::BspError> {
                let found_type = value.type_name();
                let arc_t =
                    value
                        .downcast::<$t>()
                        .map_err(|_| $crate::error::BspError::TypeMismatch {
                            node_id,
                            port_index: port,
                            expected: std::any::type_name::<$t>(),
                            found: found_type,
                        })?;
                Ok((*arc_t).clone())
            }
        }

        impl $crate::value::BspToValue for $t {
            fn to_value(self) -> $crate::value::BspValue {
                $crate::value::BspValue::new(self)
            }
        }

        impl $crate::value::BspOutputPacker for $t {
            fn output_ports() -> Vec<$crate::graph::PortIndex> {
                vec![0]
            }
            fn pack(
                self,
                _node_id: $crate::graph::NodeId,
                _node_name: &str,
            ) -> Result<$crate::node::NodeOutcome, $crate::error::BspError> {
                let mut outputs = ::indexmap::IndexMap::new();
                outputs.insert(0, $crate::value::BspToValue::to_value(self));
                Ok($crate::node::NodeOutcome::Success(outputs))
            }
        }
    };
}

// Standard primitives registration
register_bsp_type!(i64);
register_bsp_type!(f64);
register_bsp_type!(bool);
register_bsp_type!(String);
register_bsp_type!(serde_json::Value);
register_bsp_type!(BspSkip);