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
use std::{collections::HashMap, sync::Arc};

use crate::{
    error::Error,
    sync::RwLock,
    traits::{Adapter, UnitProcess},
    ModuleParam,
};

struct Edge {
    to: String,
    adapter: Option<Arc<dyn Adapter>>,
}

pub struct PipelineNet {
    nodes: HashMap<String, Arc<RwLock<dyn UnitProcess + Send + Sync>>>,
    edges: HashMap<String, Vec<Edge>>,
    groups: HashMap<String, String>, // Maps group names to input node names for each group.
}

impl PipelineNet {
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            edges: HashMap::new(),
            groups: HashMap::new(),
        }
    }

    // Add a node that implements `UnitProcess`
    pub fn add_node(&mut self, name: &str, node: Arc<RwLock<dyn UnitProcess + Send + Sync>>) {
        self.nodes.insert(name.into(), node);
    }
    // Add an edge between nodes
    pub fn add_edge(&mut self, from: &str, to: &str) {
        let edge = Edge {
            to: to.to_string(),
            adapter: None,
        };
        self.edges.entry(from.to_string()).or_default().push(edge);
    }

    // Add an edge between nodes with an adapter
    pub fn add_edge_with_adapter<A: Adapter + 'static>(
        &mut self,
        from: &str,
        to: &str,
        adapter: A,
    ) {
        let edge = Edge {
            to: to.to_string(),
            adapter: Some(Arc::new(adapter)),
        };
        self.edges.entry(from.to_string()).or_default().push(edge);
    }

    // Set group with input node.
    pub fn set_group_input(&mut self, group_name: &str, input_node_name: &str) {
        self.groups
            .insert(group_name.into(), input_node_name.into());
    }

    // Process a group starting from the group's input node, collecting the each results.
    pub async fn process_group(
        &self,
        group_name: &str,
        initial_input: ModuleParam,
    ) -> Result<HashMap<String, ModuleParam>, Error> {
        let input_node_name = self
            .groups
            .get(group_name)
            .ok_or_else(|| Error::NotFound(group_name.to_string()))?;

        let mut results = HashMap::new();
        let mut stack = vec![(input_node_name.as_str(), initial_input)];

        // bfs
        while let Some((current_node_name, input)) = stack.pop() {
            if results.contains_key(current_node_name) {
                continue; // Skip if visited
            }

            let node = self
                .nodes
                .get(current_node_name)
                .ok_or_else(|| Error::NotFound(current_node_name.to_string()))?;

            let processed_input = node.read().await.process(input).await?;

            // let processed_input = node.process(input).await?;

            results.insert(current_node_name.to_string(), processed_input.clone());

            if let Some(edges) = self.edges.get(current_node_name) {
                for edge in edges {
                    let adapted_input = edge
                        .adapter
                        .as_ref()
                        .map(|adapter| adapter.adapt(processed_input.clone()))
                        .unwrap_or_else(|| processed_input.clone());
                    stack.push((&edge.to, adapted_input));
                }
            }
        }

        Ok(results)
    }
}

#[cfg(test)]
mod tests {
    //
    //
    use super::*;
    use crate::sync::block_on;
    use async_trait::async_trait;
    use std::sync::Arc;

    // Mock implementation
    #[derive(Default)]
    struct MockUnitProcess;

    #[async_trait]
    impl UnitProcess for MockUnitProcess {
        fn get_name(&self) -> &str {
            "MockUnit"
        }
        async fn process(&self, input: ModuleParam) -> Result<ModuleParam, Error> {
            Ok(input)
        }
    }

    struct MockAdapter;

    impl Adapter for MockAdapter {
        fn adapt(&self, input: ModuleParam) -> ModuleParam {
            input
        }
    }

    #[test]
    fn test_pipeline_net() {
        let mut pipeline = PipelineNet::new();

        // Mock input for processing
        let mock_input: &str = "TestInput";
        let initial_input = ModuleParam::Str(mock_input.into());

        // Add nodes
        let node1 = Arc::new(RwLock::new(MockUnitProcess::default()));
        let node2 = Arc::new(RwLock::new(MockUnitProcess::default()));

        pipeline.add_node("node1", node1);
        pipeline.add_node("node2", node2);

        pipeline.add_edge_with_adapter("node1", "node2", |v: ModuleParam| {
            if let ModuleParam::Str(param) = v.clone() {
                assert_eq!(param, "TestInput");
            }
            v
        });

        // Set group input
        pipeline.set_group_input("group1", "node1");

        block_on(async move {
            let results = pipeline
                .process_group("group1", initial_input)
                .await
                .expect("Failed to process group");

            assert!(results.contains_key("node1"));
            assert!(results.contains_key("node2"));
            assert_eq!(
                results.get("node1").unwrap().as_string().unwrap(),
                mock_input
            );
            assert_eq!(
                results.get("node2").unwrap().as_string().unwrap(),
                mock_input
            );
        });
    }
}