wingfoil 4.0.0

graph based stream processing framework
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
use derive_new::new;
use std::cell::RefCell;
use std::fmt::{Debug, Display};
use std::rc::Rc;
use tinyvec::TinyVec;

pub use crate::graph::GraphState;
pub use crate::time::*;
/// Attribute macro for `impl MutableNode` blocks.
///
/// Generates `fn upstreams()` and/or `impl StreamPeekRef<T>` to eliminate
/// boilerplate in custom node definitions.  See [`MutableNode`] for the full
/// attribute syntax.
///
/// **Scope requirement**: the generated `upstreams()` body calls
/// [`AsUpstreamNodes`] unqualified, so `AsUpstreamNodes` must be in scope.
/// `use wingfoil::*` satisfies this; selective imports must add
/// `use wingfoil::AsUpstreamNodes` explicitly.
pub use wingfoil_derive::node;

/// A small vector optimised for single-element bursts.
///
/// In multi-threaded or async contexts, multiple values may arrive between
/// engine cycles, so incoming data is always a `Burst<T>` rather than a
/// plain `T`.  Use [`.collapse()`](crate::StreamOperators::collapse) to
/// reduce a burst to its latest value.
pub type Burst<T> = TinyVec<[T; 1]>;

/// Macro to create a `Burst<T>` with type inference.
///
/// # Examples
///
/// ```
/// # use wingfoil::burst;
/// # use wingfoil::Burst;
/// // Create an empty burst
/// let empty: Burst<i32> = burst![];
///
/// // Create a burst with one element
/// let one: Burst<i32> = burst![42];
///
/// // Create a burst with multiple elements
/// let many: Burst<i32> = burst![1, 2, 3];
/// ```
#[macro_export]
macro_rules! burst {
    () => {
        ::tinyvec::TinyVec::new()
    };
    ($($item:expr),* $(,)?) => {
        ::tinyvec::tiny_vec!($($item),*)
    };
}

/// Wraps a [Stream] to indicate whether it is an active or passive dependency.
/// Active dependencies trigger downstream nodes when they tick.
/// Passive dependencies are read but don't trigger execution.
pub enum Dep<T> {
    Active(Rc<dyn Stream<T>>),
    Passive(Rc<dyn Stream<T>>),
}

impl<T> Dep<T> {
    pub fn stream(&self) -> &Rc<dyn Stream<T>> {
        match self {
            Dep::Active(s) | Dep::Passive(s) => s,
        }
    }

    pub fn is_active(&self) -> bool {
        matches!(self, Dep::Active(_))
    }

    #[must_use]
    pub fn as_node(&self) -> Rc<dyn Node>
    where
        T: 'static,
    {
        self.stream().clone().as_node()
    }
}

/// The graph can ask a [Node] what it's upstreams sources are.  The node
/// replies with a [UpStreams] for passive and active sources.   All sources
/// are wired upstream.   Active nodes trigger [Node].cycle() when they tick.
/// Passive [Node]s do not.   
#[derive(new, Default)]
pub struct UpStreams {
    pub active: Vec<Rc<dyn Node>>,
    pub passive: Vec<Rc<dyn Node>>,
}

impl UpStreams {
    pub fn none() -> UpStreams {
        UpStreams::new(Vec::new(), Vec::new())
    }
}

/// [Stream]s produce values constrained by this trait.  For large structs that you
/// would prefer not to clone, it is recommended to wrap them in a [Rc](std::rc::Rc)
/// so they can be cloned cheaply.
#[doc(hidden)]
pub trait Element: Debug + Clone + Default + 'static {}

impl<T> Element for T where T: Debug + Clone + Default + 'static {}

/// Helper trait so the `#[node]` macro can call a single method
/// regardless of whether the field is `Rc<dyn Node>`, `Rc<dyn Stream<T>>`, or
/// a `Vec` of either.
pub trait AsUpstreamNodes {
    fn as_upstream_nodes(&self) -> Vec<Rc<dyn Node>>;
}

impl AsUpstreamNodes for Rc<dyn Node> {
    fn as_upstream_nodes(&self) -> Vec<Rc<dyn Node>> {
        vec![self.clone()]
    }
}

impl<T> AsUpstreamNodes for Rc<dyn Stream<T>> {
    fn as_upstream_nodes(&self) -> Vec<Rc<dyn Node>> {
        vec![self.clone().as_node()]
    }
}

impl<U: AsUpstreamNodes> AsUpstreamNodes for Vec<U> {
    fn as_upstream_nodes(&self) -> Vec<Rc<dyn Node>> {
        self.iter().flat_map(|u| u.as_upstream_nodes()).collect()
    }
}

/// Implement this trait create your own [Node].
pub trait MutableNode {
    /// Called by the graph when it determines that this node
    /// is required to be cycled.
    /// Returns Ok(true) if the node's state changed, Ok(false) otherwise.
    fn cycle(&mut self, state: &mut GraphState) -> anyhow::Result<bool>;
    /// Called by the graph at wiring time to discover upstream dependencies.
    /// Active upstreams trigger this node when they tick; passive are read-only.
    /// Defaults to `UpStreams::none()` (source node).  Use `#[node(active = [...])]`
    /// to generate this automatically, or override manually for complex cases.
    fn upstreams(&self) -> UpStreams {
        UpStreams::none()
    }
    /// called by the graph after wiring and before start
    #[allow(unused_variables)]
    fn setup(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        Ok(())
    }
    /// Called by the graph after wiring and before the first cycle.
    /// Can be used to request an initial callback.
    #[allow(unused_variables)]
    fn start(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        Ok(())
    }
    /// Called by the graph after the last cycle.  Can be used to clean up resources.
    #[allow(unused_variables)]
    fn stop(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        Ok(())
    }
    #[allow(unused_variables)]
    fn teardown(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        Ok(())
    }

    fn type_name(&self) -> String {
        tynm::type_name::<Self>()
    }
}

impl Display for dyn Node {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.type_name())
    }
}

impl<T> Debug for dyn Stream<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.type_name())
    }
}

/// A wiring point in the Graph.
pub trait Node: MutableNode {
    /// This is like Node::cycle but doesn't require mutable self
    /// Returns Ok(true) if the node's state changed, Ok(false) otherwise.
    fn cycle(&self, state: &mut GraphState) -> anyhow::Result<bool>;
    fn setup(&self, state: &mut GraphState) -> anyhow::Result<()>;
    fn start(&self, state: &mut GraphState) -> anyhow::Result<()>;
    fn stop(&self, state: &mut GraphState) -> anyhow::Result<()>;
    fn teardown(&self, state: &mut GraphState) -> anyhow::Result<()>;
}

/// A trait through which a reference to [Stream]'s value can
/// be peeked at.
pub trait StreamPeekRef<T: Clone>: MutableNode {
    fn peek_ref(&self) -> &T;
    fn clone_from_cell_ref(&self, cell_ref: std::cell::Ref<'_, T>) -> T {
        cell_ref.clone()
    }
}

/// The trait through which a [Stream]s can current value
/// can be peeked at.
pub trait StreamPeek<T> {
    fn peek_value(&self) -> T;
    fn peek_ref_cell(&self) -> std::cell::Ref<'_, T>;
}

/// A [Node] which has some state that can peeked at.
pub trait Stream<T>: Node + StreamPeek<T> + AsNode {}

// RefCell

impl<NODE: MutableNode> Node for RefCell<NODE> {
    fn cycle(&self, state: &mut GraphState) -> anyhow::Result<bool> {
        self.borrow_mut().cycle(state)
    }
    fn setup(&self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().setup(state)
    }
    fn start(&self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().start(state)
    }
    fn stop(&self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().stop(state)
    }
    fn teardown(&self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().teardown(state)
    }
}

impl<NODE: MutableNode> MutableNode for RefCell<NODE> {
    fn cycle(&mut self, graph_state: &mut GraphState) -> anyhow::Result<bool> {
        self.borrow_mut().cycle(graph_state)
    }
    fn upstreams(&self) -> UpStreams {
        self.borrow().upstreams()
    }
    fn start(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().start(state)
    }
    fn stop(&mut self, state: &mut GraphState) -> anyhow::Result<()> {
        self.borrow_mut().stop(state)
    }
    fn type_name(&self) -> String {
        self.borrow().type_name()
    }
}

impl<STREAM, T> StreamPeek<T> for RefCell<STREAM>
where
    STREAM: StreamPeekRef<T>,
    T: Clone,
{
    fn peek_ref_cell(&self) -> std::cell::Ref<'_, T> {
        std::cell::Ref::map(self.borrow(), |strm| strm.peek_ref())
    }
    fn peek_value(&self) -> T {
        self.borrow().clone_from_cell_ref(self.peek_ref_cell())
    }
}

impl<STREAM, T> Stream<T> for RefCell<STREAM>
where
    STREAM: StreamPeekRef<T> + 'static,
    T: Clone + 'static,
{
}

/// Used to cast Rc<dyn [Stream]> to Rc<dyn [Node]>
pub trait AsNode {
    #[must_use]
    fn as_node(self: Rc<Self>) -> Rc<dyn Node>;
}

impl<NODE: Node + 'static> AsNode for NODE {
    fn as_node(self: Rc<Self>) -> Rc<dyn Node> {
        self
    }
}

/// Used co cast Rc of concrete stream into Rc of dyn [Stream].
pub trait AsStream<T> {
    #[must_use]
    fn as_stream(self: Rc<Self>) -> Rc<dyn Stream<T>>;
}

impl<T, STREAM: Stream<T> + 'static> AsStream<T> for STREAM {
    fn as_stream(self: Rc<Self>) -> Rc<dyn Stream<T>> {
        self
    }
}

/// Used to consume a concrete [MutableNode] and return
/// an Rc<dyn [Node]>>.
pub trait IntoNode {
    #[must_use]
    fn into_node(self) -> Rc<dyn Node>;
}

impl<NODE: MutableNode + 'static> IntoNode for NODE {
    fn into_node(self) -> Rc<dyn Node> {
        Rc::new(RefCell::new(self))
    }
}

/// Used to consume a concrete [Stream] and return
/// an Rc<dyn [Stream]>>.
pub trait IntoStream<T> {
    #[must_use]
    fn into_stream(self) -> Rc<dyn Stream<T>>;
}

impl<T, STREAM> IntoStream<T> for STREAM
where
    T: Clone + 'static,
    STREAM: StreamPeekRef<T> + 'static,
{
    fn into_stream(self) -> Rc<dyn Stream<T>> {
        Rc::new(RefCell::new(self))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{GraphState, RunFor, RunMode};
    use crate::nodes::{CallBackStream, NodeOperators};
    use std::cell::RefCell;

    // ── burst! macro ────────────────────────────────────────────────────────

    #[test]
    fn burst_empty() {
        let b: Burst<i32> = burst![];
        assert!(b.is_empty());
    }

    #[test]
    fn burst_single() {
        let b: Burst<i32> = burst![42];
        assert_eq!(b.len(), 1);
        assert_eq!(b[0], 42);
    }

    #[test]
    fn burst_multiple() {
        let b: Burst<i32> = burst![1, 2, 3];
        assert_eq!(b.as_slice(), &[1, 2, 3]);
    }

    // ── Dep ─────────────────────────────────────────────────────────────────

    #[test]
    fn dep_active_is_active() {
        let src: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let dep = Dep::Active(src.clone());
        assert!(dep.is_active());
        assert!(Rc::ptr_eq(dep.stream(), &src));
    }

    #[test]
    fn dep_passive_is_not_active() {
        let src: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let dep = Dep::Passive(src.clone());
        assert!(!dep.is_active());
    }

    // ── UpStreams ────────────────────────────────────────────────────────────

    #[test]
    fn upstreams_none_is_empty() {
        let u = UpStreams::none();
        assert!(u.active.is_empty());
        assert!(u.passive.is_empty());
    }

    #[test]
    fn upstreams_new_stores_vecs() {
        let src: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let node = src.clone().as_node();
        let u = UpStreams::new(vec![node], vec![]);
        assert_eq!(u.active.len(), 1);
        assert!(u.passive.is_empty());
    }

    // ── AsUpstreamNodes ──────────────────────────────────────────────────────

    #[test]
    fn rc_node_as_upstream_nodes() {
        let src: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let node: Rc<dyn Node> = src.clone().as_node();
        let ups = node.as_upstream_nodes();
        assert_eq!(ups.len(), 1);
    }

    #[test]
    fn rc_stream_as_upstream_nodes() {
        let src: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let ups = src.as_upstream_nodes();
        assert_eq!(ups.len(), 1);
    }

    #[test]
    fn vec_as_upstream_nodes() {
        let s1: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let s2: Rc<dyn Stream<u64>> = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let v: Vec<Rc<dyn Stream<u64>>> = vec![s1, s2];
        let ups = v.as_upstream_nodes();
        assert_eq!(ups.len(), 2);
    }

    // ── IntoNode / IntoStream ────────────────────────────────────────────────

    #[test]
    fn into_node_creates_rc_dyn_node() {
        let cb = CallBackStream::<u64>::new();
        let node: Rc<dyn Node> = cb.into_node();
        // should be runnable (no upstreams → source node)
        node.run(RunMode::HistoricalFrom(NanoTime::ZERO), RunFor::Cycles(1))
            .unwrap();
    }

    #[test]
    fn into_stream_creates_rc_dyn_stream() {
        let src: Rc<RefCell<CallBackStream<u64>>> = Rc::new(RefCell::new(CallBackStream::new()));
        // peek_value via the Stream trait object
        let _: u64 = src.peek_value();
    }

    // ── GraphState integration via run ───────────────────────────────────────

    #[test]
    fn graph_state_new_starts_at_zero() {
        let state = GraphState::new(
            RunMode::HistoricalFrom(NanoTime::ZERO),
            RunFor::Cycles(1),
            NanoTime::ZERO,
        );
        assert_eq!(state.time(), NanoTime::ZERO);
    }

    // ── Debug for dyn Stream<T> ──────────────────────────────────────────────

    #[test]
    fn debug_for_dyn_stream_uses_type_name() {
        use crate::nodes::CallBackStream;
        use std::cell::RefCell;
        let cb = Rc::new(RefCell::new(CallBackStream::<u64>::new()));
        let stream: Rc<dyn Stream<u64>> = cb.as_stream();
        // Debug impl delegates to type_name(); just check it doesn't panic
        let s = format!("{:?}", &*stream);
        assert!(!s.is_empty());
    }
}