Skip to main content

khive_request/
plan.rs

1//! Syntax and catalog inspection without dispatch or admission.
2
3use std::collections::BTreeMap;
4
5use serde_json::{json, Map, Value};
6
7use crate::parser::parse_request;
8use crate::types::{ArgValue, ExecutionMode, MAX_OPS, MAX_OPS_INPUT_LEN, NESTING_DEPTH_LIMIT};
9
10/// Parses a request and describes its stages using a verb-to-pack catalog.
11///
12/// Catalog membership does not grant permission to dispatch a verb. Previous
13/// result references remain literal strings and are never resolved.
14pub fn plan_request(ops: &str, catalog: &BTreeMap<String, String>) -> Value {
15    let limits = json!({
16        "max_ops": MAX_OPS,
17        "max_depth": NESTING_DEPTH_LIMIT,
18        "max_input_len": MAX_OPS_INPUT_LEN,
19    });
20    let request = match parse_request(ops) {
21        Ok(request) => request,
22        Err(error) => return json!({"parsed": false, "error": error.to_string(), "limits": limits}),
23    };
24    let mode = match request.mode {
25        ExecutionMode::Single => "single",
26        ExecutionMode::Parallel => "parallel",
27        ExecutionMode::Chain => "chain",
28    };
29    let unit_index_of: Vec<usize> = request
30        .ranges
31        .iter()
32        .enumerate()
33        .flat_map(|(unit_index, range)| range.clone().map(move |_| unit_index))
34        .collect();
35    let stages: Vec<Value> = request
36        .ops
37        .into_iter()
38        .enumerate()
39        .map(|(index, op)| {
40            let mut prev_refs = Vec::new();
41            let args: Map<String, Value> = op
42                .args
43                .into_iter()
44                .map(|(name, arg)| (name, literal_arg(arg, &mut prev_refs)))
45                .collect();
46            let pack = catalog.get(&op.tool);
47            json!({
48                "index": index,
49                "verb": op.tool,
50                "pack": pack,
51                "known": pack.is_some(),
52                "args": args,
53                "prev_refs": prev_refs,
54                "unit_index": unit_index_of.get(index),
55            })
56        })
57        .collect();
58    let units: Vec<Value> = request
59        .ranges
60        .iter()
61        .map(|range| json!({"start": range.start, "end": range.end}))
62        .collect();
63    json!({
64        "parsed": true,
65        "mode": mode,
66        "stage_count": stages.len(),
67        "stages": stages,
68        "units": units,
69        "limits": limits,
70    })
71}
72
73fn literal_arg(arg: ArgValue, prev_refs: &mut Vec<String>) -> Value {
74    match arg {
75        ArgValue::Value(value) => value,
76        ArgValue::PrevRef { path } => {
77            let literal_path = path.replace(".[", "[");
78            let literal = if path.is_empty() || path.starts_with('[') {
79                format!("$prev{literal_path}")
80            } else {
81                format!("$prev.{literal_path}")
82            };
83            prev_refs.push(path);
84            Value::String(literal)
85        }
86        ArgValue::Array(items) => Value::Array(
87            items
88                .into_iter()
89                .map(|item| literal_arg(item, prev_refs))
90                .collect(),
91        ),
92        ArgValue::Object(pairs) => Value::Object(
93            pairs
94                .into_iter()
95                .map(|(name, value)| (name, literal_arg(value, prev_refs)))
96                .collect(),
97        ),
98    }
99}