use std::collections::BTreeMap;
use std::fmt;
use serde_json::Value;
pub const MAX_OPS: usize = 100;
pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
pub const NESTING_DEPTH_LIMIT: usize = 64;
pub use khive_types::RESERVED_ENVELOPE_ARGS;
pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
while let Some((v, depth)) = stack.pop() {
match v {
Value::Array(items) => {
let next_depth = depth + 1;
if next_depth > max_depth {
return false;
}
stack.extend(items.iter().map(|item| (item, next_depth)));
}
Value::Object(map) => {
let next_depth = depth + 1;
if next_depth > max_depth {
return false;
}
stack.extend(map.values().map(|item| (item, next_depth)));
}
_ => {}
}
}
true
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionMode {
Single,
Parallel,
Chain,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
Value(Value),
PrevRef { path: String },
Array(Vec<ArgValue>),
Object(Vec<(String, ArgValue)>),
}
impl ArgValue {
pub fn as_value(&self) -> Option<&Value> {
match self {
ArgValue::Value(v) => Some(v),
ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
}
}
pub fn is_prev_ref(&self) -> bool {
matches!(self, ArgValue::PrevRef { .. })
}
pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
let ArgValue::PrevRef { path } = self else {
return None;
};
if path.is_empty() {
return Some(prev_result);
}
let mut cur = prev_result;
for segment in crate::parser::split_path(path) {
cur = crate::parser::apply_path_segment(cur, segment)?;
}
Some(cur)
}
pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
match self {
ArgValue::Value(v) => Some(v.clone()),
ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
ArgValue::Array(elements) => {
let mut out = Vec::with_capacity(elements.len());
for el in elements {
out.push(el.resolve_all(prev_result)?);
}
Some(Value::Array(out))
}
ArgValue::Object(pairs) => {
let mut map = serde_json::Map::with_capacity(pairs.len());
for (key, val) in pairs {
map.insert(key.clone(), val.resolve_all(prev_result)?);
}
Some(Value::Object(map))
}
}
}
pub fn find_prev_failure(&self, prev_result: &Value) -> Option<PrevFailure> {
self.find_prev_failure_at("", prev_result)
}
fn find_prev_failure_at(&self, arg_path: &str, prev_result: &Value) -> Option<PrevFailure> {
match self {
ArgValue::Value(_) => None,
ArgValue::PrevRef { path } => {
if path.is_empty() {
return None;
}
let mut cur = prev_result;
let mut resolved_prefix = String::new();
for seg in crate::parser::split_path(path) {
match seg {
crate::parser::PathSegment::Field(key) => match cur {
Value::Object(map) => match map.get(key) {
Some(v) => {
cur = v;
if !resolved_prefix.is_empty() {
resolved_prefix.push('.');
}
resolved_prefix.push_str(key);
}
None => {
let mut available: Vec<String> = map.keys().cloned().collect();
available.sort_unstable();
return Some(PrevFailure::NotFound {
arg_path: arg_path.to_string(),
prev_path: render_prev_path(path),
resolved_prefix: prev_path_prefix(&resolved_prefix),
missing: key.to_string(),
available,
});
}
},
other => {
return Some(PrevFailure::WrongType {
arg_path: arg_path.to_string(),
prev_path: render_prev_path(path),
resolved_prefix: prev_path_prefix(&resolved_prefix),
segment: key.to_string(),
expected: "object",
found: json_type_name(other),
});
}
},
crate::parser::PathSegment::Index(idx) => match cur {
Value::Array(arr) => match arr.get(idx) {
Some(v) => {
cur = v;
resolved_prefix.push_str(&format!("[{idx}]"));
}
None => {
return Some(PrevFailure::NotFound {
arg_path: arg_path.to_string(),
prev_path: render_prev_path(path),
resolved_prefix: prev_path_prefix(&resolved_prefix),
missing: format!("[{idx}]"),
available: vec![format!(
"array has {} element(s)",
arr.len()
)],
});
}
},
other => {
return Some(PrevFailure::WrongType {
arg_path: arg_path.to_string(),
prev_path: render_prev_path(path),
resolved_prefix: prev_path_prefix(&resolved_prefix),
segment: format!("[{idx}]"),
expected: "array",
found: json_type_name(other),
});
}
},
crate::parser::PathSegment::Malformed(raw) => {
return Some(PrevFailure::Unsupported {
arg_path: arg_path.to_string(),
prev_path: render_prev_path(path),
segment: raw.to_string(),
});
}
}
}
None
}
ArgValue::Array(elements) => elements.iter().enumerate().find_map(|(i, el)| {
el.find_prev_failure_at(&format!("{arg_path}[{i}]"), prev_result)
}),
ArgValue::Object(pairs) => pairs.iter().find_map(|(k, v)| {
let sub = if arg_path.is_empty() {
k.clone()
} else {
format!("{arg_path}.{k}")
};
v.find_prev_failure_at(&sub, prev_result)
}),
}
}
}
fn render_prev_path(path: &str) -> String {
format!("$prev.{path}").replace(".[", "[")
}
fn prev_path_prefix(resolved_prefix: &str) -> String {
if resolved_prefix.is_empty() {
"$prev".to_string()
} else {
format!("$prev.{resolved_prefix}")
}
}
fn json_type_name(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum PrevFailure {
NotFound {
arg_path: String,
prev_path: String,
resolved_prefix: String,
missing: String,
available: Vec<String>,
},
WrongType {
arg_path: String,
prev_path: String,
resolved_prefix: String,
segment: String,
expected: &'static str,
found: &'static str,
},
Unsupported {
arg_path: String,
prev_path: String,
segment: String,
},
}
impl fmt::Display for PrevFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn arg_ref(arg_path: &str) -> String {
if arg_path.is_empty() {
String::new()
} else {
format!(" (at {arg_path})")
}
}
match self {
PrevFailure::NotFound {
arg_path,
prev_path,
resolved_prefix,
missing,
available,
} => {
write!(
f,
"{prev_path}{arg}: {resolved_prefix} has no {missing:?}. \
Available top-level fields: [{}]",
available.join(", "),
arg = arg_ref(arg_path),
)
}
PrevFailure::WrongType {
arg_path,
prev_path,
resolved_prefix,
segment,
expected,
found,
} => {
write!(
f,
"{prev_path}{arg}: {resolved_prefix} is a {found}, not an {expected}, so \
{segment:?} cannot be applied to it",
arg = arg_ref(arg_path),
)
}
PrevFailure::Unsupported {
arg_path,
prev_path,
segment,
} => {
write!(
f,
"{prev_path}{arg}: {segment:?} is not a supported $prev path segment; \
array indices must be a plain non-negative integer, e.g. $prev.items[0]",
arg = arg_ref(arg_path),
)
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedOp {
pub tool: String,
pub args: BTreeMap<String, ArgValue>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedRequest {
pub ops: Vec<ParsedOp>,
pub mode: ExecutionMode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TypedJsonOp {
pub tool: String,
pub args: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum DslError {
Empty,
TooManyOps {
count: usize,
max: usize,
},
InputTooLarge {
len: usize,
max: usize,
},
NestingTooDeep {
pos: usize,
depth: usize,
max: usize,
},
UnexpectedChar {
pos: usize,
found: char,
expected: &'static str,
},
UnexpectedEof {
expected: &'static str,
},
InvalidIdentifier {
pos: usize,
},
DuplicateArg {
name: String,
},
InvalidValue {
pos: usize,
error: String,
},
InvalidJson {
error: String,
},
UnclosedString,
UnclosedBracket {
kind: char,
},
PrevRefOutsideChain {
pos: usize,
},
PrevRefInJsonForm {
arg_name: String,
},
MixedSeparators,
EmptyBatch,
UnsupportedVerbNesting {
pos: usize,
},
WriteKeyConflict {
id: String,
first_op: String,
second_op: String,
},
ReservedEnvelopeArg {
arg_name: String,
verb: String,
},
TrailingComma {
pos: usize,
},
}
impl fmt::Display for DslError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DslError::Empty => write!(f, "request is empty"),
DslError::TooManyOps { count, max } => {
write!(f, "batch has {count} ops; max is {max}")
}
DslError::InputTooLarge { len, max } => {
write!(f, "ops input is {len} bytes; max is {max} bytes")
}
DslError::NestingTooDeep { pos, depth, max } => {
write!(
f,
"at position {pos}: container nesting depth {depth} exceeds max {max}"
)
}
DslError::UnexpectedChar {
pos,
found,
expected,
} => {
write!(f, "at position {pos}: expected {expected}, found {found:?}")
}
DslError::UnexpectedEof { expected } => {
write!(f, "unexpected end of input; expected {expected}")
}
DslError::InvalidIdentifier { pos } => {
write!(
f,
"at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
)
}
DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
DslError::InvalidValue { pos, error } => {
write!(f, "at position {pos}: invalid value: {error}")
}
DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
DslError::UnclosedString => write!(f, "unterminated string literal"),
DslError::UnclosedBracket { kind } => {
write!(f, "unclosed bracket: {kind:?} has no matching close")
}
DslError::PrevRefOutsideChain { pos } => {
write!(
f,
"at position {pos}: $prev reference is only valid in chain (|) mode; \
use function-call form with '|' to chain ops"
)
}
DslError::PrevRefInJsonForm { arg_name } => {
write!(
f,
"argument {arg_name:?}: $prev substitution requires the function-call DSL \
with the chain (|) operator; JSON form does not support chains. \
Use: verb1(...) | verb2({arg_name}=$prev.id)"
)
}
DslError::MixedSeparators => {
write!(
f,
"cannot mix ',' (parallel) and '|' (chain) separators in one request; \
a parallel batch cannot contain a chain. Split the work into two `request` \
calls: put independent ops in one `[...]` batch and dependent ops in a \
separate `a() | b(arg=$prev.id)` chain"
)
}
DslError::EmptyBatch => {
write!(f, "empty batch not allowed; provide at least one op")
}
DslError::UnsupportedVerbNesting { pos } => {
write!(
f,
"at position {pos}: only single-level dotted verb names are supported \
(e.g. brain.state); use a shorter name or register a pack alias"
)
}
DslError::WriteKeyConflict {
id,
first_op,
second_op,
} => {
write!(
f,
"write-key conflict: id {id:?} is targeted by both {first_op:?} and \
{second_op:?} in the same batch; split into separate requests"
)
}
DslError::ReservedEnvelopeArg { arg_name, verb } => {
write!(
f,
"argument {arg_name:?} in verb {verb:?} is reserved for the request \
envelope; pass it at the envelope level, not inside verb args"
)
}
DslError::TrailingComma { pos } => {
write!(
f,
"at position {pos}: trailing comma before ']' — a batch cannot end with \
an empty element; remove the comma or add another op after it"
)
}
}
}
}
impl std::error::Error for DslError {}