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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! Workflow dispatcher for scheduling and executing nodes.
//!
//! The dispatcher is responsible for:
//! - Traversing the workflow graph
//! - Scheduling nodes for execution when dependencies are met
//! - Handling node results and determining next steps
//! - Managing retries and timeouts
use std::{sync::Arc, time::Duration};
use tokio::{runtime::Runtime, sync::mpsc};
use crate::{
common::{Queue, Shutdown, Vars},
events::{ErrorReason, Event, GraphEvent, Message, NodeEvent, WorkflowAbortedEvent, WorkflowEvent, WorkflowFailedEvent, WorkflowStartEvent},
runtime::{Context, WorkflowCommand},
utils,
workflow::{
Workflow,
actions::{ActionOutput, ActionType},
consts::{IF_ELSE_FALSE, IF_ELSE_SELECTED, IF_ELSE_TRUE},
edge::{EdgeSelectOptions, FixedHandle, SourceHandle},
node::{NodeExecutionStatus, NodeId, NodeResult},
},
};
/// Workflow execution dispatcher.
///
/// The dispatcher manages the execution of a workflow by:
/// - Processing commands (Start, Abort)
/// - Spawning node execution tasks
/// - Handling node completion and scheduling successors
/// - Managing conditional branching (if_else nodes)
pub struct Dispatcher {
/// Execution context with environment and outputs.
ctx: Arc<Context>,
/// The workflow graph to execute.
workflow: Arc<Workflow>,
/// Queue for receiving workflow commands.
command_queue: Arc<Queue<WorkflowCommand>>,
/// Tokio runtime for spawning tasks.
runtime: Arc<Runtime>,
/// Shutdown coordinator.
shutdown: Arc<Shutdown>,
}
impl Dispatcher {
/// Creates a new dispatcher for the given workflow.
pub fn new(
ctx: Arc<Context>,
workflow: Arc<Workflow>,
command_queue: Arc<Queue<WorkflowCommand>>,
runtime: Arc<Runtime>,
) -> Self {
Self {
ctx,
workflow,
command_queue,
runtime,
shutdown: Arc::new(Shutdown::new()),
}
}
/// Starts the dispatcher's main event loop.
///
/// The loop processes:
/// - Workflow commands (Start, Abort)
/// - Node execution results
pub fn start(&self) {
// Internal channel for worker task completion events
let (tx, mut rx) = mpsc::channel::<(NodeId, NodeEvent)>(1024);
let ctx = self.ctx.clone();
let workflow = self.workflow.clone();
let command_queue = self.command_queue.clone();
let runtime = self.runtime.clone();
let shutdown = self.shutdown.clone();
self.runtime.spawn(async move {
loop {
tokio::select! {
_ = shutdown.wait() => break,
// Handle node execution results
Some((nid, event)) = rx.recv() => {
// Publish node event to external channel
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: nid.clone(),
event: GraphEvent::Node(event.clone()),
})).unwrap();
match event {
NodeEvent::Succeeded(_) => {
Self::handle_node_success(&ctx, &workflow, &runtime, &tx, nid).await;
}
NodeEvent::Error(err) => {
// Send workflow failed event
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: nid.clone(),
event: GraphEvent::Workflow(WorkflowEvent::Failed(WorkflowFailedEvent {
error: err.to_string(),
})),
}));
// Stop the workflow
shutdown.shutdown();
}
_ => {}
}
}
// Handle workflow commands
cmd_opt = command_queue.next_async() => {
if let Some(cmd) = cmd_opt {
match cmd {
WorkflowCommand::Start => {
if let Some(root_node) = workflow.get_root_node() {
// Get all node IDs for batch initialization
let node_ids = workflow.get_all_node_ids();
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: "".to_string(),
event: GraphEvent::Workflow(WorkflowEvent::Start(WorkflowStartEvent {
node_ids,
})),
}));
Self::spawn_node(&ctx, &workflow, &runtime, &tx, root_node.id);
}
}
WorkflowCommand::Abort => {
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: "".to_string(),
event: GraphEvent::Workflow(WorkflowEvent::Aborted(WorkflowAbortedEvent {
reason: "Aborted by command".to_string(),
outputs: std::collections::HashMap::new(),
})),
}));
shutdown.shutdown();
}
}
}
}
}
}
});
}
/// Stops the dispatcher.
pub fn stop(&self) {
self.shutdown.shutdown();
}
/// Returns all node outputs collected during execution.
pub fn outputs(&self) -> Vars {
let mut result = Vars::new();
for (nid, vars) in self.ctx.outputs().iter() {
result.set(nid.as_str(), vars.clone());
}
result
}
/// Checks if the dispatcher has completed execution.
pub fn is_complete(&self) -> bool {
self.shutdown.is_terminated()
}
/// Spawns a node for execution in a separate task.
fn spawn_node(
ctx: &Arc<Context>,
workflow: &Arc<Workflow>,
runtime: &Arc<Runtime>,
tx: &mpsc::Sender<(NodeId, NodeEvent)>,
nid: NodeId,
) {
let ctx = ctx.clone();
let workflow = workflow.clone();
let tx = tx.clone();
workflow.mark_node_taken(&nid);
runtime.spawn(async move {
let result = Self::execute_node(ctx, workflow, nid.clone()).await;
let _ = tx.send((nid, result)).await;
});
}
async fn handle_node_success(
ctx: &Arc<Context>,
workflow: &Arc<Workflow>,
runtime: &Arc<Runtime>,
tx: &mpsc::Sender<(NodeId, NodeEvent)>,
nid: NodeId,
) {
workflow.mark_node_executed(&nid);
let mut edge_select_options = EdgeSelectOptions::default();
// Handle if-else node: determine selected branch and skip others
let node = workflow.get_node(&nid).unwrap(); // should be safe
if node.action.action_type() == ActionType::IfElse {
if let Some(outputs) = ctx.outputs().get(&nid) {
if let Some(source_handle) = outputs.get::<String>(IF_ELSE_SELECTED) {
// Determine the selected source handle
let selected_handle = if source_handle == IF_ELSE_TRUE {
SourceHandle::Fixed(FixedHandle::True)
} else if source_handle == IF_ELSE_FALSE {
SourceHandle::Fixed(FixedHandle::False)
} else {
SourceHandle::Node(source_handle)
};
edge_select_options.source_handle = selected_handle.clone();
// Skip unselected branches and send events
let skipped = workflow.skip_unselected_branches(&nid, &selected_handle);
for (skipped_nid, _) in skipped {
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: skipped_nid,
event: GraphEvent::Node(NodeEvent::Skipped),
}));
}
}
}
}
let next_nodes = workflow.get_next_ready_node(&nid, edge_select_options);
let all_executed = workflow.is_all_node_executed();
if next_nodes.is_empty() && all_executed {
let _ = ctx.channel().event_queue().send(Event::new(&Message {
pid: ctx.pid(),
nid: nid.clone(),
event: GraphEvent::Workflow(WorkflowEvent::Succeeded),
}));
ctx.done();
}
for next_nid in next_nodes {
Self::spawn_node(ctx, workflow, runtime, tx, next_nid);
}
}
/// Executes a single node logic, including retries and timeout handling.
/// This function is intended to be spawned as a separate task by the dispatcher.
async fn execute_node(
ctx: Arc<Context>,
workflow: Arc<Workflow>,
nid: NodeId,
) -> NodeEvent {
let event_queue = ctx.channel().event_queue();
let node = match workflow.get_node(&nid) {
Some(n) => Arc::new(n),
None => {
return NodeEvent::Error(ErrorReason::Exception(format!("Node {} not found", nid)));
}
};
let mut retry_times = node.retry.as_ref().map(|r| r.times).unwrap_or(0);
let retry_interval = node.retry.as_ref().map(|r| r.interval).unwrap_or(0);
// Track start time before action execution (as timestamp)
let start_time = utils::time::time_millis();
// Emit Running event
let _ = event_queue.send(Event::new(&Message {
pid: ctx.pid(),
nid: nid.clone(),
event: GraphEvent::Node(NodeEvent::Running(start_time)),
}));
loop {
let action_ctx = ctx.clone();
let action_node = node.clone();
let action_nid = nid.clone();
let run_future = async move {
if let Some(timeout) = action_node.timeout {
tokio::time::timeout(timeout, async move {
action_node.action.run(action_ctx, action_node.id.clone()).await
})
.await
} else {
Ok(action_node.action.run(action_ctx, action_nid).await)
}
};
let ret = tokio::select! {
_ = ctx.wait_shutdown() => return NodeEvent::Stopped(utils::time::time_millis()),
res = run_future => res,
};
// Track end time after action execution (as timestamp)
let end_time = utils::time::time_millis();
// Convert ActionOutput to NodeResult
let node_result = match &ret {
Ok(output) => NodeResult::from_result_output(output.clone()),
Err(_) => NodeResult::from_output(ActionOutput::failed("Timeout".to_string())),
};
let should_retry = match node_result.status {
NodeExecutionStatus::Failed => true,
_ => false,
};
if should_retry && retry_times > 0 {
retry_times -= 1;
if retry_interval > 0 {
tokio::select! {
_ = ctx.wait_shutdown() => return NodeEvent::Stopped(utils::time::time_millis()),
_ = tokio::time::sleep(Duration::from_millis(retry_interval)) => {}
}
}
let _ = event_queue.send(Event::new(&Message {
pid: ctx.pid(),
nid: nid.clone(),
event: GraphEvent::Node(NodeEvent::Retry),
}));
continue;
}
return match node_result.status {
NodeExecutionStatus::Pending => unreachable!(),
NodeExecutionStatus::Succeeded => {
ctx.add_output(nid.clone(), node_result.outputs);
NodeEvent::Succeeded(end_time)
}
NodeExecutionStatus::Failed => NodeEvent::Error(ErrorReason::Failed(node_result.error.unwrap_or_default())),
NodeExecutionStatus::Exception => NodeEvent::Error(ErrorReason::Exception(node_result.exception.unwrap_or_default())),
NodeExecutionStatus::Stopped => NodeEvent::Stopped(end_time),
NodeExecutionStatus::Paused => NodeEvent::Paused(end_time),
};
}
}
}