Skip to main content

sh_layer2/workflow_engine/
node.rs

1//! # Node Definition
2//!
3//! 工作流节点定义。
4
5use serde::{Deserialize, Serialize};
6
7/// 节点状态
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
9pub enum NodeStatus {
10    #[default]
11    Pending,
12    Running,
13    Completed,
14    Failed,
15    Skipped,
16}
17
18/// 工作流节点
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Node {
21    /// 节点 ID
22    pub id: String,
23    /// 节点名称
24    pub name: String,
25    /// 节点类型
26    #[serde(default = "default_node_type")]
27    pub node_type: String,
28    /// 节点配置
29    #[serde(default)]
30    pub config: serde_json::Value,
31    /// 依赖的节点 ID
32    #[serde(default)]
33    pub dependencies: Vec<String>,
34    /// 超时时间(毫秒)
35    #[serde(default = "default_timeout")]
36    pub timeout_ms: u64,
37    /// 重试次数
38    #[serde(default)]
39    pub retry_count: u32,
40}
41
42fn default_node_type() -> String {
43    "task".to_string()
44}
45
46fn default_timeout() -> u64 {
47    30000
48}
49
50impl Node {
51    /// 创建新节点
52    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
53        Self {
54            id: id.into(),
55            name: name.into(),
56            node_type: default_node_type(),
57            config: serde_json::Value::Null,
58            dependencies: Vec::new(),
59            timeout_ms: default_timeout(),
60            retry_count: 0,
61        }
62    }
63
64    /// 设置节点类型
65    pub fn with_type(mut self, node_type: impl Into<String>) -> Self {
66        self.node_type = node_type.into();
67        self
68    }
69
70    /// 设置配置
71    pub fn with_config(mut self, config: serde_json::Value) -> Self {
72        self.config = config;
73        self
74    }
75
76    /// 添加依赖
77    pub fn depends_on(mut self, node_id: &str) -> Self {
78        self.dependencies.push(node_id.to_string());
79        self
80    }
81
82    /// 设置超时
83    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
84        self.timeout_ms = timeout_ms;
85        self
86    }
87
88    /// 设置重试次数
89    pub fn with_retry(mut self, retry_count: u32) -> Self {
90        self.retry_count = retry_count;
91        self
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn test_node_creation() {
101        let node = Node::new("test", "Test Node");
102        assert_eq!(node.id, "test");
103        assert_eq!(node.name, "Test Node");
104    }
105
106    #[test]
107    fn test_node_builder() {
108        let node = Node::new("test", "Test Node")
109            .with_type("custom")
110            .with_timeout(60000)
111            .depends_on("dep1");
112
113        assert_eq!(node.node_type, "custom");
114        assert_eq!(node.timeout_ms, 60000);
115        assert_eq!(node.dependencies.len(), 1);
116    }
117}