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
//! Provides structures for creating and executing chains.
//!
//! This module defines `Chain` and `ChainBuilder` structures for building chains of
//! operations where each operation is represented by a `Node`. These chains
//! facilitate asynchronous processing of data from an initial input to a final output.

use async_trait::async_trait;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;

use crate::error::AnchorChainError;
use crate::link::StatefulLink;
use crate::node::{Stateful, Stateless};
use crate::state_manager::StateManager;
use crate::{link::Link, node::Node};

/// Represents a chain of nodes that can asynchronously process data.
///
/// `Chain` is constructed from a sequence of `Node` instances, each taking an input
/// and producing an output. The output of one node serves as the input to the next,
/// allowing for a flexible and composable approach to complex asynchronous processing tasks.
#[derive(Debug)]
pub struct Chain<I, O, L> {
    link: L,
    _input: PhantomData<I>,
    _output: PhantomData<O>,
}

impl<I, O, L> Chain<I, O, L>
where
    L: Node<Input = I, Output = O> + Send + Sync + fmt::Debug,
    I: fmt::Debug,
    O: fmt::Debug,
{
    /// Creates a new `Chain` from the provided initial link.
    ///
    /// `Link` serves as a container for chaining two `Node` instances together,
    /// where the output of the first node is fed as the input to the next. These
    /// links can be nested to create a chain of nodes.
    pub fn new(link: L) -> Self {
        Chain {
            link,
            _input: PhantomData,
            _output: PhantomData,
        }
    }

    /// Asynchronously processes the provided input through the chain of nodes.
    ///
    /// The input is processed by each node in the chain, with the output of one node
    /// serving as the input to the next. The final output of the chain is returned.
    /// If any node in the chain returns an error, the processing is halted and
    /// the error is returned.
    pub async fn process(&self, input: I) -> Result<O, AnchorChainError> {
        self.link.process(input).await
    }
}

#[async_trait]
impl<I, O, L> Node for Chain<I, O, L>
where
    L: Node<Input = I, Output = O> + Send + Sync + fmt::Debug,
    I: fmt::Debug + Send + Sync,
    O: fmt::Debug + Send + Sync,
{
    type Input = I;
    type Output = O;

    async fn process(&self, input: Self::Input) -> Result<Self::Output, AnchorChainError> {
        self.process(input).await
    }
}

/// A builder for constructing a `Chain` of nodes.
///
/// `ChainBuilder` allows for incremental construction of a processing chain, adding
/// node one at a time. This approach facilitates clear and concise assembly
/// of complex processing logic.
pub struct ChainBuilder {}

impl ChainBuilder {
    /// Creates a new `ChainBuilder` instance.
    pub fn new() -> Self {
        ChainBuilder {}
    }

    /// Adds the first node to the chain.
    pub fn link<I, N>(self, node: N) -> LinkedChainBuilder<I, N>
    where
        N: Node<Input = I> + Stateless + Send + Sync + fmt::Debug,
        I: Send,
    {
        LinkedChainBuilder {
            link: node,
            _input: PhantomData,
        }
    }

    pub fn link_with_state<I, N, K, V>(self, node: N) -> StatefulLinkedChainBuilder<I, N, K, V>
    where
        N: Node<Input = I> + Stateful<K, V> + Send + Sync + fmt::Debug,
        I: Send,
        K: Eq + Hash + Clone,
        V: Clone,
    {
        StatefulLinkedChainBuilder {
            link: node,
            state: StateManager::new(),
            _input: PhantomData,
        }
    }
}

impl Default for ChainBuilder {
    fn default() -> Self {
        ChainBuilder::new()
    }
}

/// A builder for constructing a `Chain` of nodes using Link.
///
/// `LinkedChainBuilder` takes an initial node and allows for incremental
/// construction of a processing chain, adding nodes one at a time. New nodes
/// are linked to the previous nodes using nested `Link` instances.
pub struct LinkedChainBuilder<I, L> {
    link: L,
    _input: PhantomData<I>,
}

impl<I, L> LinkedChainBuilder<I, L>
where
    L: Node<Input = I> + Send + Sync + fmt::Debug,
    I: Send,
{
    /// Adds a new node to the chain, linking it to the previous node.
    pub fn link<N>(self, next: N) -> LinkedChainBuilder<I, Link<L, N>>
    where
        N: Node<Input = L::Output> + Stateless + Send + Sync + fmt::Debug,
        L::Output: Send,
        Link<L, N>: Node<Input = I>,
    {
        LinkedChainBuilder {
            link: Link::new(self.link, next),
            _input: PhantomData,
        }
    }

    /// Adds a new `StatefulNode` to the chain, linking it to the previous
    /// node. A new `StateManager` will also be created that will be passed
    /// to all stateful nodes in the chain.
    pub fn link_with_state<N, K, V>(
        self,
        next: N,
    ) -> StatefulLinkedChainBuilder<I, StatefulLink<L, N, K, V>, K, V>
    where
        N: Node<Input = L::Output> + Stateful<K, V> + Send + Sync + fmt::Debug,
        L::Output: Send,
        Link<L, N>: Node<Input = I>,
        K: Eq + Hash + Clone + Send + fmt::Debug,
        V: Clone + Send + fmt::Debug,
    {
        let state = StateManager::default();
        StatefulLinkedChainBuilder {
            link: StatefulLink::new(self.link, next, state.clone()),
            state,
            _input: PhantomData,
        }
    }

    /// Finalizes the construction of the chain, returning a `Chain` instance
    /// ready for processing.
    pub fn build(self) -> Chain<I, L::Output, L>
    where
        L: Node,
    {
        Chain {
            link: self.link,
            _input: PhantomData,
            _output: PhantomData,
        }
    }
}

/// A builder for constructing a `Chain` of nodes using `Link` and `StatefulLink`.
///
/// `StatefulLinkedChainBuilder` takes an initial node and allows for incremental
/// construction of a stateful processing chain, adding nodes one at a time. New nodes
/// are linked to the previous nodes using nested `Link` or `StatefulLink` instances.
pub struct StatefulLinkedChainBuilder<I, L, K, V> {
    link: L,
    state: StateManager<K, V>,
    _input: PhantomData<I>,
}

impl<I, L, K, V> StatefulLinkedChainBuilder<I, L, K, V>
where
    L: Node<Input = I> + Send + Sync + fmt::Debug,
    I: Send,
    K: Clone + Send + fmt::Debug,
    V: Clone + Send + fmt::Debug,
{
    /// Adds a new node to the chain, linking it to the previous node.
    pub fn link<N>(self, next: N) -> StatefulLinkedChainBuilder<I, Link<L, N>, K, V>
    where
        N: Node<Input = L::Output> + Stateless + Send + Sync + fmt::Debug,
        L::Output: Send,
        Link<L, N>: Node<Input = I>,
    {
        StatefulLinkedChainBuilder {
            link: Link::new(self.link, next),
            state: self.state,
            _input: PhantomData,
        }
    }

    /// Adds a new `StatefulNode` to the chain, linking it to the previous
    /// node. Each stateful node will be passed an instance of the `StateManager`.
    pub fn link_with_state<N>(
        self,
        next: N,
    ) -> StatefulLinkedChainBuilder<I, StatefulLink<L, N, K, V>, K, V>
    where
        N: Node<Input = L::Output> + Stateful<K, V> + Send + Sync + fmt::Debug,
        L::Output: Send,
        StatefulLink<L, N, K, V>: Node<Input = I>,
    {
        StatefulLinkedChainBuilder {
            link: StatefulLink::new(self.link, next, self.state.clone()),
            state: self.state,
            _input: PhantomData,
        }
    }

    /// Finalizes the construction of the chain, returning a `Chain` instance
    /// ready for processing.
    pub fn build(self) -> Chain<I, L::Output, L>
    where
        L: Node,
    {
        Chain {
            link: self.link,
            _input: PhantomData,
            _output: PhantomData,
        }
    }
}