1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde_json::Value;
5
6pub const MAX_OPS: usize = 100;
8
9pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
13
14pub const NESTING_DEPTH_LIMIT: usize = 64;
18
19pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
21
22pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
28 let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
29 while let Some((v, depth)) = stack.pop() {
30 match v {
31 Value::Array(items) => {
32 let next_depth = depth + 1;
33 if next_depth > max_depth {
34 return false;
35 }
36 stack.extend(items.iter().map(|item| (item, next_depth)));
37 }
38 Value::Object(map) => {
39 let next_depth = depth + 1;
40 if next_depth > max_depth {
41 return false;
42 }
43 stack.extend(map.values().map(|item| (item, next_depth)));
44 }
45 _ => {}
46 }
47 }
48 true
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ExecutionMode {
54 Single,
56 Parallel,
58 Chain,
60}
61
62#[derive(Debug, Clone, PartialEq)]
66pub enum ArgValue {
67 Value(Value),
69 PrevRef { path: String },
71 Array(Vec<ArgValue>),
73 Object(Vec<(String, ArgValue)>),
75}
76
77impl ArgValue {
78 pub fn as_value(&self) -> Option<&Value> {
80 match self {
81 ArgValue::Value(v) => Some(v),
82 ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
83 }
84 }
85
86 pub fn is_prev_ref(&self) -> bool {
88 matches!(self, ArgValue::PrevRef { .. })
89 }
90
91 pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
96 let ArgValue::PrevRef { path } = self else {
97 return None;
98 };
99 if path.is_empty() {
100 return Some(prev_result);
101 }
102 let mut cur = prev_result;
103 for segment in crate::parser::split_path(path) {
104 cur = crate::parser::apply_path_segment(cur, segment)?;
105 }
106 Some(cur)
107 }
108
109 pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
111 match self {
112 ArgValue::Value(v) => Some(v.clone()),
113 ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
114 ArgValue::Array(elements) => {
115 let mut out = Vec::with_capacity(elements.len());
116 for el in elements {
117 out.push(el.resolve_all(prev_result)?);
118 }
119 Some(Value::Array(out))
120 }
121 ArgValue::Object(pairs) => {
122 let mut map = serde_json::Map::with_capacity(pairs.len());
123 for (key, val) in pairs {
124 map.insert(key.clone(), val.resolve_all(prev_result)?);
125 }
126 Some(Value::Object(map))
127 }
128 }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq)]
134pub struct ParsedOp {
135 pub tool: String,
136 pub args: BTreeMap<String, ArgValue>,
137}
138
139#[derive(Debug, Clone, PartialEq)]
141pub struct ParsedRequest {
142 pub ops: Vec<ParsedOp>,
143 pub mode: ExecutionMode,
144}
145
146#[derive(Debug, Clone, PartialEq)]
153pub enum DslError {
154 Empty,
155 TooManyOps {
156 count: usize,
157 max: usize,
158 },
159 InputTooLarge {
161 len: usize,
162 max: usize,
163 },
164 NestingTooDeep {
166 pos: usize,
167 depth: usize,
168 max: usize,
169 },
170 UnexpectedChar {
171 pos: usize,
172 found: char,
173 expected: &'static str,
174 },
175 UnexpectedEof {
176 expected: &'static str,
177 },
178 InvalidIdentifier {
179 pos: usize,
180 },
181 DuplicateArg {
182 name: String,
183 },
184 InvalidValue {
185 pos: usize,
186 error: String,
187 },
188 InvalidJson {
189 error: String,
190 },
191 UnclosedString,
192 UnclosedBracket {
193 kind: char,
194 },
195 PrevRefOutsideChain {
197 pos: usize,
198 },
199 PrevRefInJsonForm {
201 arg_name: String,
202 },
203 MixedSeparators,
205 EmptyBatch,
207 UnsupportedVerbNesting {
209 pos: usize,
210 },
211 WriteKeyConflict {
213 id: String,
215 first_op: String,
217 second_op: String,
219 },
220 ReservedEnvelopeArg {
222 arg_name: String,
223 verb: String,
224 },
225}
226
227impl fmt::Display for DslError {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 DslError::Empty => write!(f, "request is empty"),
231 DslError::TooManyOps { count, max } => {
232 write!(f, "batch has {count} ops; max is {max}")
233 }
234 DslError::InputTooLarge { len, max } => {
235 write!(f, "ops input is {len} bytes; max is {max} bytes")
236 }
237 DslError::NestingTooDeep { pos, depth, max } => {
238 write!(
239 f,
240 "at position {pos}: container nesting depth {depth} exceeds max {max}"
241 )
242 }
243 DslError::UnexpectedChar {
244 pos,
245 found,
246 expected,
247 } => {
248 write!(f, "at position {pos}: expected {expected}, found {found:?}")
249 }
250 DslError::UnexpectedEof { expected } => {
251 write!(f, "unexpected end of input; expected {expected}")
252 }
253 DslError::InvalidIdentifier { pos } => {
254 write!(
255 f,
256 "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
257 )
258 }
259 DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
260 DslError::InvalidValue { pos, error } => {
261 write!(f, "at position {pos}: invalid value: {error}")
262 }
263 DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
264 DslError::UnclosedString => write!(f, "unterminated string literal"),
265 DslError::UnclosedBracket { kind } => {
266 write!(f, "unclosed bracket: {kind:?} has no matching close")
267 }
268 DslError::PrevRefOutsideChain { pos } => {
269 write!(
270 f,
271 "at position {pos}: $prev reference is only valid in chain (|) mode; \
272 use function-call form with '|' to chain ops"
273 )
274 }
275 DslError::PrevRefInJsonForm { arg_name } => {
276 write!(
277 f,
278 "argument {arg_name:?}: $prev substitution requires the function-call DSL \
279 with the chain (|) operator; JSON form does not support chains. \
280 Use: verb1(...) | verb2({arg_name}=$prev.id)"
281 )
282 }
283 DslError::MixedSeparators => {
284 write!(
285 f,
286 "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
287 )
288 }
289 DslError::EmptyBatch => {
290 write!(f, "empty batch not allowed; provide at least one op")
291 }
292 DslError::UnsupportedVerbNesting { pos } => {
293 write!(
294 f,
295 "at position {pos}: only single-level dotted verb names are supported \
296 (e.g. brain.state); use a shorter name or register a pack alias"
297 )
298 }
299 DslError::WriteKeyConflict {
300 id,
301 first_op,
302 second_op,
303 } => {
304 write!(
305 f,
306 "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
307 {second_op:?} in the same batch; split into separate requests"
308 )
309 }
310 DslError::ReservedEnvelopeArg { arg_name, verb } => {
311 write!(
312 f,
313 "argument {arg_name:?} in verb {verb:?} is reserved for the request \
314 envelope; pass it at the envelope level, not inside verb args"
315 )
316 }
317 }
318 }
319}
320
321impl std::error::Error for DslError {}