Skip to main content

lellm_graph/node/
node_core.rs

1//! 节点核心类型与模块。
2//!
3//! v0.4 终态架构:
4//!
5//! - `LeafNode<S>` — 声明式业务节点,只能读 State + emit Mutation
6//! - `ExecutorOperation<S>` — 命令式执行控制,可以 clone/merge/replace_state
7//! - `NodeKind<S, M>` — Graph 的 AST(不实现任何执行 trait)
8//! - `FlowNode<S>` — 向后兼容,等同于 LeafNode
9//!
10//! 职责边界:
11//!
12//! ```text
13//! Graph (AST)
14//!     └── NodeKind
15//!
16//! ExecutionEngine (runtime owner)
17//!     ├── dispatch → match NodeKind
18//!     ├── build_leaf_context() → LeafNode
19//!     └── pass &mut self → ExecutorOperation
20//!
21//! LeafNode
22//!     └── 只能 emit Mutation
23//!
24//! ExecutorOperation
25//!     └── 可以操纵 Executor(fork / merge / replace_state / subgraph)
26//! ```
27
28use std::sync::Arc;
29
30use async_trait::async_trait;
31
32pub use super::node_context::LeafContext;
33use super::node_context::NodeContext;
34use crate::error::GraphError;
35use crate::exec::execution_engine::ExecutionEngine;
36use crate::state::workflow_state::{MergeStrategy, WorkflowState};
37use crate::state::{State, StateMerge};
38
39// ─── 子模块重新导出 ────────────────────────────────────────────
40
41pub use super::barrier_node::{BarrierDefaultAction, BarrierNode};
42pub use super::parallel_node::{ParallelErrorStrategy, ParallelNode, ParallelNodeBuilder};
43
44// ─── LeafNode Trait ───────────────────────────────────────────
45
46/// 声明式业务节点 — 只能读 State + emit Mutation。
47///
48/// 设计原则:
49/// - **只能读 State**(`ctx.state()` 返回 `&S`)
50/// - **只能 emit Mutation**(`ctx.record()`)
51/// - **不能 replace_state / clone_state / fork / merge**
52///
53/// 与 `ExecutorOperation` 完全不同维度:
54/// - LeafNode = 业务逻辑(Task, Condition, Barrier, LLM, Tool)
55/// - ExecutorOperation = 执行控制(Parallel, Retry, Loop, SubGraph)
56///
57/// # 泛型参数
58///
59/// - `S` — 类型化状态(默认 `State` = HashMap,向后兼容)
60#[async_trait]
61pub trait LeafNode<S: WorkflowState = State>: Send + Sync {
62    /// 执行节点逻辑。
63    async fn execute(&self, ctx: &mut LeafContext<'_, S>) -> Result<(), GraphError>;
64}
65
66// ─── ExecutorOperation Trait ──────────────────────────────────
67
68/// 命令式执行控制 — Composite 节点使用。
69///
70/// 直接接收 `&mut ExecutionEngine`,拥有完整能力:
71/// - clone_state / replace_state
72/// - build_leaf_context(用于执行子分支)
73///
74/// 这不是"节点",而是 ExecutionEngine 的内部控制逻辑扩展。
75#[async_trait]
76pub trait ExecutorOperation<S: WorkflowState = State>: Send + Sync {
77    /// 执行组合操作。
78    async fn execute(&self, engine: &mut ExecutionEngine<'_, S>) -> Result<(), GraphError>;
79}
80
81// ─── Backward Compat: FlowNode (deprecated) ───────────────────
82
83/// 向后兼容 — `FlowNode` trait。
84///
85/// **已弃用**。请使用 [`LeafNode`](只读 State + emit Mutation)或
86/// [`ExecutorOperation`](组合节点,完整控制)。
87///
88/// `FlowNode` 接收 `NodeContext`(持有 `&mut S`),绕过了 Mutation 模式,
89/// 不利于 Checkpoint 和审计追踪。
90///
91/// # 迁移指南
92///
93/// - 如果节点只需读 State + 路由 → 迁移到 [`LeafNode`]
94/// - 如果节点需要直接写 State → 迁移到 [`LeafNode`] + `ctx.record(mutation)`
95/// - 如果节点是组合逻辑(Parallel、Subgraph)→ 迁移到 [`ExecutorOperation`]
96#[deprecated(
97    since = "0.6.0",
98    note = "Use LeafNode (read-only state + mutations) or ExecutorOperation (composite control) instead."
99)]
100#[async_trait]
101pub trait FlowNode<S: WorkflowState = State>: Send + Sync {
102    /// 执行节点逻辑。
103    async fn execute(&self, ctx: &mut NodeContext<'_, S>) -> Result<(), GraphError>;
104}
105
106// ─── NodeKind (AST Only) ──────────────────────────────────────
107
108/// Graph 的 AST — 节点类型枚举。
109///
110/// **不实现任何执行 trait。** 它只是数据结构。
111/// 执行分发由 ExecutionEngine 的 match 负责。
112///
113/// # 泛型参数
114///
115/// - `S` — 类型化状态(默认 `State` = HashMap,向后兼容)
116/// - `M` — 并行合并策略(仅 `Parallel` 变体使用,默认 [`StateMerge`])
117#[allow(deprecated)]
118pub enum NodeKind<S: WorkflowState = State, M: MergeStrategy<S> = StateMerge> {
119    /// 自定义逻辑
120    Task(TaskNode<S>),
121    /// 条件分支
122    Condition(ConditionNode<S>),
123    /// Human-in-the-loop 审批屏障
124    Barrier(BarrierNode<S>),
125    /// 并行执行多个分支
126    Parallel(ParallelNode<S, M>),
127    /// 外部节点(由 lellm-agent 等 crate 提供)— 向后兼容,使用 NodeContext
128    ///
129    /// **已弃用**。新代码请使用 `ExternalLeaf`。
130    External(Arc<dyn FlowNode<S>>),
131    /// 外部 Leaf 节点 — 只能读 State + emit Mutation
132    ExternalLeaf(Arc<dyn LeafNode<S>>),
133    /// Subgraph 节点 — 运行时递归执行内层 Graph
134    ///
135    /// CompiledSubgraph 持有类型擦除的 StateProjector,
136    /// 包含 Graph + Lens + Merge 的执行逻辑。
137    Subgraph(super::compiled_subgraph::CompiledSubgraph<S>),
138}
139
140#[allow(deprecated)]
141impl<S: WorkflowState, M: MergeStrategy<S>> Clone for NodeKind<S, M> {
142    fn clone(&self) -> Self {
143        match self {
144            Self::Task(n) => Self::Task(n.clone()),
145            Self::Condition(n) => Self::Condition(n.clone()),
146            Self::Barrier(n) => Self::Barrier(n.clone()),
147            Self::Parallel(n) => Self::Parallel(n.clone()),
148            Self::External(n) => Self::External(n.clone()),
149            Self::ExternalLeaf(n) => Self::ExternalLeaf(n.clone()),
150            Self::Subgraph(n) => Self::Subgraph(n.clone()),
151        }
152    }
153}
154
155// ─── TaskNode ────────────────────────────────────────────────
156
157/// Task 节点回调类型别名(向后兼容 NodeContext)。
158pub type TaskFn<S> = Arc<dyn Fn(&mut NodeContext<'_, S>) -> Result<(), GraphError> + Send + Sync>;
159
160/// 自定义逻辑节点。
161#[derive(Clone)]
162pub struct TaskNode<S: WorkflowState = State> {
163    pub name: String,
164    pub func: TaskFn<S>,
165}
166
167impl<S: WorkflowState> TaskNode<S> {
168    pub fn new(
169        name: impl Into<String>,
170        func: impl Fn(&mut NodeContext<'_, S>) -> Result<(), GraphError> + Send + Sync + 'static,
171    ) -> Self {
172        Self {
173            name: name.into(),
174            func: Arc::new(func),
175        }
176    }
177}
178
179/// TaskNode 实现 FlowNode(向后兼容 — 使用 NodeContext)。
180///
181/// 未来将迁移到 LeafNode + LeafContext。
182#[allow(deprecated)]
183#[async_trait]
184impl<S: WorkflowState> FlowNode<S> for TaskNode<S> {
185    async fn execute(&self, ctx: &mut NodeContext<'_, S>) -> Result<(), GraphError> {
186        (self.func)(ctx)
187    }
188}
189
190// ─── ConditionNode ───────────────────────────────────────────
191
192/// 条件分支回调类型别名。
193pub type BranchCondition<S> = Arc<dyn Fn(&S) -> bool + Send + Sync>;
194
195/// 条件分支节点。
196#[derive(Clone)]
197pub struct ConditionNode<S: WorkflowState = State> {
198    pub name: String,
199    pub branches: Vec<(String, BranchCondition<S>)>,
200}
201
202impl<S: WorkflowState> ConditionNode<S> {
203    pub fn builder(name: impl Into<String>) -> ConditionNodeBuilder<S> {
204        ConditionNodeBuilder {
205            name: name.into(),
206            branches: Vec::new(),
207        }
208    }
209}
210
211/// ConditionNode 构建器。
212pub struct ConditionNodeBuilder<S: WorkflowState = State> {
213    name: String,
214    branches: Vec<(String, BranchCondition<S>)>,
215}
216
217impl<S: WorkflowState> ConditionNodeBuilder<S> {
218    pub fn branch(
219        mut self,
220        target: impl Into<String>,
221        condition: impl Fn(&S) -> bool + Send + Sync + 'static,
222    ) -> Self {
223        self.branches.push((target.into(), Arc::new(condition)));
224        self
225    }
226
227    pub fn build(self) -> ConditionNode<S> {
228        ConditionNode {
229            name: self.name,
230            branches: self.branches,
231        }
232    }
233}
234
235/// ConditionNode 实现 LeafNode(推荐路径 — 只读 state + goto)。
236#[async_trait]
237impl<S: WorkflowState> LeafNode<S> for ConditionNode<S> {
238    async fn execute(&self, ctx: &mut LeafContext<'_, S>) -> Result<(), GraphError> {
239        let state = ctx.state();
240        for (target, condition) in &self.branches {
241            if condition(state) {
242                ctx.goto(target);
243                return Ok(());
244            }
245        }
246        Ok(())
247    }
248}
249
250/// ConditionNode 实现 FlowNode(向后兼容 — 使用 NodeContext)。
251#[allow(deprecated)]
252#[async_trait]
253impl<S: WorkflowState> FlowNode<S> for ConditionNode<S> {
254    async fn execute(&self, ctx: &mut NodeContext<'_, S>) -> Result<(), GraphError> {
255        let state = ctx.state();
256        for (target, condition) in &self.branches {
257            if condition(state) {
258                ctx.goto(target);
259                return Ok(());
260            }
261        }
262        Ok(())
263    }
264}
265
266// ─── Backward Compatibility Alias ─────────────────────────────
267
268/// 向后兼容别名 — `GraphNode` → `FlowNode`。
269#[allow(deprecated)]
270pub type GraphNode<S> = dyn FlowNode<S>;