gadk_engine/workflow/
workflow.rs1use std::sync::Arc;
20
21use gadk_agent::{Context, ContextDelta, EventStream, InvocationContext};
22use gadk_session::Session;
23use serde_json::{Map, Value};
24
25use crate::error::{WorkflowError, WorkflowErrorKind};
26use crate::workflow::base_node::compile_schema;
27use crate::workflow::graph::Graph;
28use crate::workflow::route::go_quote;
29use crate::workflow::scheduler::Scheduler;
30use crate::workflow::state::RunState;
31use crate::workflow::validation::{validate_nodes, validate_sub_workflow_names, validate_workflow};
32use crate::workflow::{Edge, START};
33
34#[derive(Clone, Default)]
37pub struct WorkflowOptions {
38 pub root_wrapper: bool,
41 pub max_concurrency: Option<usize>,
43 pub state_schema: Option<Value>,
45}
46
47impl WorkflowOptions {
48 pub fn with_root_wrapper(mut self) -> Self {
52 self.root_wrapper = true;
53 self
54 }
55
56 pub fn with_max_concurrency(mut self, n: usize) -> Self {
60 self.max_concurrency = Some(n);
61 self
62 }
63
64 pub fn with_state_schema(mut self, s: Value) -> Self {
66 self.state_schema = Some(s);
67 self
68 }
69}
70
71pub struct Workflow {
73 pub(crate) graph: Arc<Graph>,
75 pub(crate) name: String,
77 pub(crate) max_concurrency: usize,
79 #[allow(dead_code)] pub(crate) state_schema: Option<Value>,
82 pub(crate) is_root_wrapper: bool,
84}
85
86impl Workflow {
87 pub fn new(
89 name: &str,
90 edges: Vec<Edge>,
91 opts: WorkflowOptions,
92 ) -> Result<Arc<Workflow>, WorkflowError> {
93 validate_nodes(&edges)?;
94 validate_sub_workflow_names(name, &edges)?;
95 let compiled_state = compile_schema(opts.state_schema.clone()).map_err(|e| {
98 WorkflowError::new(
99 WorkflowErrorKind::Other,
100 format!(
101 "resolving state schema for workflow {}: {e}",
102 go_quote(name)
103 ),
104 )
105 })?;
106 let mut graph = Graph::new(edges);
107 graph.is_root_wrapper = opts.root_wrapper;
108 validate_workflow(&graph, compiled_state.as_deref())?;
109 Ok(Arc::new(Workflow {
110 graph: Arc::new(graph),
111 name: name.to_owned(),
112 max_concurrency: opts.max_concurrency.unwrap_or(0),
113 state_schema: opts.state_schema,
114 is_root_wrapper: opts.root_wrapper,
115 }))
116 }
117
118 pub fn name(&self) -> &str {
120 &self.name
121 }
122}
123
124impl Workflow {
125 pub fn run(self: &Arc<Self>, ctx: InvocationContext) -> EventStream {
128 let c = ctx.into_context();
129 let c = if !self.is_root_wrapper && !self.name.is_empty() {
130 let parent = c.path();
131 let wf_path = if parent.is_empty() {
132 format!("{}@1", self.name)
133 } else {
134 format!("{parent}/{}@1", self.name)
135 };
136 let ancestors = c.output_for_ancestors();
137 c.with_delta(ContextDelta {
138 path: Some(wf_path),
139 run_id: Some("1".to_string()),
140 output_for_ancestors: Some(ancestors),
141 sub_scheduler: Some(None),
142 ..ContextDelta::default()
143 })
144 } else {
145 c
146 };
147 let input = user_input(&c);
148 self.run_node(c, input)
149 }
150
151 pub fn run_node(self: &Arc<Self>, ctx: Context, input: Value) -> EventStream {
155 let wf = Arc::clone(self);
156 Box::pin(async_stream::stream! {
157 let mut s = Scheduler::new(ctx.clone(), Arc::clone(&wf.graph), wf.max_concurrency);
158 s.workflow_name = wf.name.clone();
159 let input = (!input.is_null()).then_some(input);
160 s.state.ensure_node(START.name()).input = input.clone();
161 s.schedule_node(Arc::clone(&START), input, String::new(), ctx.branch());
162 while let Some(item) = s.next().await {
163 yield item;
164 }
165 })
166 }
167}
168
169impl Workflow {
170 pub fn reconstruct_run_state(
173 &self,
174 session: &dyn Session,
175 invocation_id: &str,
176 ) -> Result<Option<RunState>, WorkflowError> {
177 crate::workflow::persistence::reconstruct_run_state(self, session, invocation_id)
178 }
179
180 pub fn resume(
183 self: &Arc<Self>,
184 ctx: Context,
185 state: RunState,
186 responses: Map<String, Value>,
187 ) -> EventStream {
188 crate::workflow::resume::resume_stream(Arc::clone(self), ctx, state, responses)
189 }
190}
191
192fn user_input(ctx: &Context) -> Value {
194 match ctx.user_content() {
195 None => Value::Null,
196 Some(uc) => Value::String(uc.parts.iter().map(|p| p.text.as_str()).collect()),
197 }
198}