//! DAG 定义 — 可序列化/反序列化,用于持久化和模板 use serde::{Deserialize, Serialize}; use std::collections::HashMap; use crate::dag::Dag; /// DAG 定义 — 可序列化/反序列化,用于持久化和模板 #[derive(Serialize, Deserialize, Clone, Debug)] pub struct DagDef { pub nodes: HashMap, pub edges: Vec, } /// 节点定义 #[derive(Serialize, Deserialize, Clone, Debug)] pub struct NodeDef { pub id: String, pub node_type: String, pub config: serde_json::Value, #[serde(default)] pub label: Option, } /// 边定义 #[derive(Serialize, Deserialize, Clone, Debug)] pub struct EdgeDef { pub source: String, pub target: String, #[serde(default)] pub condition: Option, } impl DagDef { /// 创建空的 DAG 定义 pub fn new() -> Self { Self { nodes: HashMap::new(), edges: Vec::new(), } } /// 添加节点定义 pub fn add_node(&mut self, id: impl Into, node_type: impl Into, config: serde_json::Value) { let id = id.into(); self.nodes.insert(id.clone(), NodeDef { id, node_type: node_type.into(), config, label: None, }); } /// 添加边定义 pub fn add_edge(&mut self, source: impl Into, target: impl Into) { self.edges.push(EdgeDef { source: source.into(), target: target.into(), condition: None, }); } /// 添加带条件的边定义 pub fn add_edge_with_condition( &mut self, source: impl Into, target: impl Into, condition: impl Into, ) { self.edges.push(EdgeDef { source: source.into(), target: target.into(), condition: Some(condition.into()), }); } /// 从已有的运行时 Dag 提取定义(忽略节点实例,仅保留元数据) /// /// 注意:此方法只能提取边的定义,节点配置无法从 trait object 反推 pub fn from_dag_edges(dag: &Dag) -> Self { let edges: Vec = dag.edges.iter().map(|e| EdgeDef { source: e.source.clone(), target: e.target.clone(), condition: e.condition.clone(), }).collect(); let nodes: HashMap = dag.nodes.iter().map(|(id, node)| { (id.clone(), NodeDef { id: id.clone(), node_type: node.node_type().to_string(), config: serde_json::Value::Null, label: None, }) }).collect(); Self { nodes, edges } } } impl Default for DagDef { fn default() -> Self { Self::new() } }