use std::sync::Arc;
use gadk_agent::{Context, ContextDelta, EventStream, InvocationContext};
use gadk_session::Session;
use serde_json::{Map, Value};
use crate::error::{WorkflowError, WorkflowErrorKind};
use crate::workflow::base_node::compile_schema;
use crate::workflow::graph::Graph;
use crate::workflow::route::go_quote;
use crate::workflow::scheduler::Scheduler;
use crate::workflow::state::RunState;
use crate::workflow::validation::{validate_nodes, validate_sub_workflow_names, validate_workflow};
use crate::workflow::{Edge, START};
#[derive(Clone, Default)]
pub struct WorkflowOptions {
pub root_wrapper: bool,
pub max_concurrency: Option<usize>,
pub state_schema: Option<Value>,
}
impl WorkflowOptions {
pub fn with_root_wrapper(mut self) -> Self {
self.root_wrapper = true;
self
}
pub fn with_max_concurrency(mut self, n: usize) -> Self {
self.max_concurrency = Some(n);
self
}
pub fn with_state_schema(mut self, s: Value) -> Self {
self.state_schema = Some(s);
self
}
}
pub struct Workflow {
pub(crate) graph: Arc<Graph>,
pub(crate) name: String,
pub(crate) max_concurrency: usize,
#[allow(dead_code)] pub(crate) state_schema: Option<Value>,
pub(crate) is_root_wrapper: bool,
}
impl Workflow {
pub fn new(
name: &str,
edges: Vec<Edge>,
opts: WorkflowOptions,
) -> Result<Arc<Workflow>, WorkflowError> {
validate_nodes(&edges)?;
validate_sub_workflow_names(name, &edges)?;
let compiled_state = compile_schema(opts.state_schema.clone()).map_err(|e| {
WorkflowError::new(
WorkflowErrorKind::Other,
format!(
"resolving state schema for workflow {}: {e}",
go_quote(name)
),
)
})?;
let mut graph = Graph::new(edges);
graph.is_root_wrapper = opts.root_wrapper;
validate_workflow(&graph, compiled_state.as_deref())?;
Ok(Arc::new(Workflow {
graph: Arc::new(graph),
name: name.to_owned(),
max_concurrency: opts.max_concurrency.unwrap_or(0),
state_schema: opts.state_schema,
is_root_wrapper: opts.root_wrapper,
}))
}
pub fn name(&self) -> &str {
&self.name
}
}
impl Workflow {
pub fn run(self: &Arc<Self>, ctx: InvocationContext) -> EventStream {
let c = ctx.into_context();
let c = if !self.is_root_wrapper && !self.name.is_empty() {
let parent = c.path();
let wf_path = if parent.is_empty() {
format!("{}@1", self.name)
} else {
format!("{parent}/{}@1", self.name)
};
let ancestors = c.output_for_ancestors();
c.with_delta(ContextDelta {
path: Some(wf_path),
run_id: Some("1".to_string()),
output_for_ancestors: Some(ancestors),
sub_scheduler: Some(None),
..ContextDelta::default()
})
} else {
c
};
let input = user_input(&c);
self.run_node(c, input)
}
pub fn run_node(self: &Arc<Self>, ctx: Context, input: Value) -> EventStream {
let wf = Arc::clone(self);
Box::pin(async_stream::stream! {
let mut s = Scheduler::new(ctx.clone(), Arc::clone(&wf.graph), wf.max_concurrency);
s.workflow_name = wf.name.clone();
let input = (!input.is_null()).then_some(input);
s.state.ensure_node(START.name()).input = input.clone();
s.schedule_node(Arc::clone(&START), input, String::new(), ctx.branch());
while let Some(item) = s.next().await {
yield item;
}
})
}
}
impl Workflow {
pub fn reconstruct_run_state(
&self,
session: &dyn Session,
invocation_id: &str,
) -> Result<Option<RunState>, WorkflowError> {
crate::workflow::persistence::reconstruct_run_state(self, session, invocation_id)
}
pub fn resume(
self: &Arc<Self>,
ctx: Context,
state: RunState,
responses: Map<String, Value>,
) -> EventStream {
crate::workflow::resume::resume_stream(Arc::clone(self), ctx, state, responses)
}
}
fn user_input(ctx: &Context) -> Value {
match ctx.user_content() {
None => Value::Null,
Some(uc) => Value::String(uc.parts.iter().map(|p| p.text.as_str()).collect()),
}
}