Skip to main content

greentic_flow/add_step/
modes.rs

1use std::path::{Path, PathBuf};
2
3use serde_json::{Map, Value, json};
4
5use crate::{
6    component_catalog::ComponentCatalog, config_flow::run_config_flow, error::Result,
7    loader::load_ygtc_from_str_with_schema,
8};
9
10use super::normalize::normalize_node_map;
11
12#[derive(Debug, Clone)]
13pub enum AddStepModeInput {
14    Default {
15        operation: String,
16        payload: Value,
17        routing: Option<Value>,
18    },
19    Config {
20        config_flow: String,
21        schema_path: Box<Path>,
22        answers: Map<String, Value>,
23        manifest_id: Option<String>,
24        manifest_path: Option<PathBuf>,
25    },
26}
27
28pub fn materialize_node(
29    mode: AddStepModeInput,
30    _catalog: &dyn ComponentCatalog,
31) -> Result<(Option<String>, Value)> {
32    match mode {
33        AddStepModeInput::Default {
34            operation,
35            payload,
36            routing,
37        } => {
38            let mut node = serde_json::Map::new();
39            node.insert(operation.clone(), payload);
40            if let Some(routing) = routing {
41                node.insert("routing".to_string(), routing);
42            } else {
43                node.insert(
44                    "routing".to_string(),
45                    json!([{ "to": crate::splice::NEXT_NODE_PLACEHOLDER }]),
46                );
47            }
48            let value = Value::Object(node.clone());
49            // Ensure shape is valid up front.
50            let normalized = normalize_node_map(value.clone())?;
51            Ok((Some(normalized.operation.clone()), Value::Object(node)))
52        }
53        AddStepModeInput::Config {
54            config_flow,
55            schema_path,
56            answers,
57            manifest_id,
58            manifest_path,
59        } => {
60            let _doc = load_ygtc_from_str_with_schema(&config_flow, &schema_path)?; // schema validation
61            let output = run_config_flow(&config_flow, &schema_path, &answers, manifest_id)?;
62            let normalized = normalize_node_map(output.node.clone())?;
63            let mut hint = Some(output.node_id.clone());
64            if normalized.operation.is_empty() {
65                hint = None;
66            }
67            let _ = manifest_path;
68            Ok((hint, output.node))
69        }
70    }
71}