pocketflow-batch 0.1.0

Batch processing support for PocketFlow
Documentation
use pocketflow_core::*;
use std::collections::HashMap;

#[derive(Clone)]
pub struct BatchNode {
    name: String,
    params: Params,
    successors: HashMap<String, BatchNode>,
    func: std::sync::Arc<
        dyn Fn(&mut (dyn std::any::Any + Send), &Params) -> Result<Option<String>> + Send + Sync,
    >,
}

impl BatchNode {
    pub fn new<F>(name: impl Into<String>, func: F) -> Self
    where
        F: Fn(&mut (dyn std::any::Any + Send), &Params) -> Result<Option<String>>
            + Send
            + Sync
            + 'static,
    {
        Self {
            name: name.into(),
            params: Params::new(),
            successors: HashMap::new(),
            func: std::sync::Arc::new(func),
        }
    }

    pub fn add_successor(&mut self, action: impl Into<String>, node: BatchNode) -> &mut Self {
        self.successors.insert(action.into(), node);
        self
    }

    pub fn next(&mut self, node: BatchNode) -> &mut Self {
        self.add_successor("default", node)
    }

    pub fn set_params(&mut self, params: Params) {
        self.params = params;
    }

    pub fn get_params(&self) -> &Params {
        &self.params
    }

    pub fn get_successor(&self, action: &str) -> Option<&BatchNode> {
        self.successors.get(action)
    }

    pub fn has_successors(&self) -> bool {
        !self.successors.is_empty()
    }

    pub fn run(&self, shared: &mut (dyn std::any::Any + Send)) -> Result<()> {
        if self.has_successors() {
            eprintln!("Warning: BatchNode won't run successors. Use BatchFlow.");
        }
        
        (self.func)(shared, &self.params)?;
        Ok(())
    }

    pub fn run_recursive(&self, shared: &mut (dyn std::any::Any + Send)) -> Result<()> {
        let action = (self.func)(shared, &self.params)?;
        
        if let Some(next_node) = action
            .as_ref()
            .and_then(|a| self.successors.get(a))
            .or_else(|| self.successors.get("default")) {
            next_node.run_recursive(shared)?;
        }
        
        Ok(())
    }
}

#[derive(Clone)]
pub struct BatchFlow {
    start_node: Option<BatchNode>,
    params: Params,
}

impl BatchFlow {
    pub fn new() -> Self {
        Self {
            start_node: None,
            params: Params::new(),
        }
    }

    pub fn start(mut self, node: BatchNode) -> Self {
        self.start_node = Some(node);
        self
    }

    pub fn set_params(&mut self, params: Params) {
        self.params = params;
    }

    pub fn run(&self, shared: &mut (dyn std::any::Any + Send)) -> Result<()> {
        if let Some(ref node) = self.start_node {
            let mut node = node.clone();
            node.set_params(self.params.clone());
            node.run_recursive(shared)?;
        }
        Ok(())
    }

    pub fn run_with_params(&self, shared: &mut (dyn std::any::Any + Send), params: Params) -> Result<()> {
        if let Some(ref node) = self.start_node {
            let mut node = node.clone();
            let mut merged_params = self.params.clone();
            merged_params.merge(&params);
            node.set_params(merged_params);
            node.run_recursive(shared)?;
        }
        Ok(())
    }

    pub fn run_batch(&self, shared: &mut (dyn std::any::Any + Send), batch_params: Vec<Params>) -> Result<Vec<()>> {
        let mut results = Vec::with_capacity(batch_params.len());
        for params in batch_params {
            let flow = BatchFlow {
                start_node: self.start_node.clone(),
                params: self.params.clone(),
            };
            flow.run_with_params(shared, params)?;
            results.push(());
        }
        Ok(results)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[derive(Default, Clone)]
    struct TestShared {
        pub counter: Arc<Mutex<i32>>,
    }

    #[test]
    fn test_batch_flow() {
        let mut shared = TestShared::default();
        
        let node = BatchNode::new("batch", |shared, params| {
            if let Some(shared) = shared.downcast_mut::<TestShared>() {
                let mut counter = shared.counter.lock().unwrap();
                if let Some(value) = params.get("value") {
                    if let Some(num) = value.as_i64() {
                        *counter += num as i32;
                    }
                }
            }
            Ok(None)
        });
        
        let flow = BatchFlow::new().start(node);
        
        let batch_params = vec![
            {
                let mut params = Params::new();
                params.insert("value", 1);
                params
            },
            {
                let mut params = Params::new();
                params.insert("value", 2);
                params
            },
        ];
        
        flow.run_batch(&mut shared, batch_params).unwrap();
        
        let counter = shared.counter.lock().unwrap();
        assert_eq!(*counter, 3);
    }
}