use crate::{Error, Result};
use serde::Deserialize;
use serde_json::{Map, Value};
use super::function_parser::FunctionCall;
use super::functions::execute_function;
use super::budget::RunBudget;
use super::evaluator::evaluate_arg;
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::enum_variant_names)]
pub enum ModifierVariant {
OverwriteBeta,
DefaultBeta,
DefineBeta,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ModifierSpec {
pub variant: ModifierVariant,
pub spec: Value,
}
impl ModifierSpec {
#[cfg(test)]
pub fn new(variant: ModifierVariant, spec: Value) -> Self {
Self { variant, spec }
}
pub fn deserialize_default_beta<'de, D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let spec = Value::deserialize(deserializer)?;
Ok(Self {
variant: ModifierVariant::DefaultBeta,
spec,
})
}
pub fn deserialize_define_beta<'de, D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let spec = Value::deserialize(deserializer)?;
Ok(Self {
variant: ModifierVariant::DefineBeta,
spec,
})
}
pub fn apply(&self, mut input: Value) -> Result<Value> {
let context = input.get("context").cloned();
let root = input.clone();
let mut budget = RunBudget::default();
self.apply_spec_to_value(
&mut input,
&root,
&self.spec,
context.as_ref(),
&mut Vec::new(),
&mut budget,
)?;
Ok(input)
}
fn should_write(&self, target: &Value, key: &str) -> bool {
match self.variant {
ModifierVariant::OverwriteBeta => true,
ModifierVariant::DefaultBeta => matches!(target.get(key), None | Some(Value::Null)),
ModifierVariant::DefineBeta => target.get(key).is_none(),
}
}
fn should_replace_with_object(&self, target: &Value) -> bool {
match self.variant {
ModifierVariant::OverwriteBeta => true,
ModifierVariant::DefaultBeta => target.is_null(),
ModifierVariant::DefineBeta => false,
}
}
fn fits_array_walk(element: &Value, spec: &Value) -> bool {
match element {
Value::Null | Value::Object(_) => true,
Value::Array(_) => spec.get("*").is_some(),
_ => false,
}
}
fn is_wildcard_only(spec: &Value) -> bool {
spec.as_object()
.is_some_and(|map| map.len() == 1 && map.contains_key("*"))
}
fn apply_spec_to_value(
&self,
target: &mut Value,
root: &Value,
spec: &Value,
context: Option<&Value>,
path: &mut Vec<String>,
budget: &mut RunBudget,
) -> Result<()> {
match spec {
Value::Object(spec_map) => {
if Self::is_wildcard_only(spec) && !target.is_object() && !target.is_array() {
return Ok(());
}
let walks_array = target.is_array() && spec_map.contains_key("*");
if !target.is_object() && !walks_array {
if !self.should_replace_with_object(target) {
return Ok(());
}
budget.charge_value(&Value::Object(Map::new()))?;
*target = Value::Object(Map::new());
}
let literals = spec_map.iter().filter(|(key, _)| key.as_str() != "*");
for (key, value) in literals.chain(spec_map.get_key_value("*")) {
if key == "*" {
if value.is_object() {
let target_keys: Vec<String> = if let Some(obj) = target.as_object() {
obj.iter()
.filter(|(key, member)| {
member.is_object()
|| !spec_map
.get(key.as_str())
.is_some_and(|literal| !literal.is_object())
})
.map(|(key, _)| key.clone())
.collect()
} else if let Some(arr) = target.as_array() {
(0..arr.len()).map(|i| i.to_string()).collect()
} else {
vec![]
};
for child_key in target_keys {
let child_target = if target.is_array() {
let idx: usize = child_key.parse().unwrap_or(0);
target
.as_array_mut()
.unwrap()
.get_mut(idx)
.filter(|element| Self::fits_array_walk(element, value))
} else {
target.as_object_mut().unwrap().get_mut(&child_key)
};
if let Some(child) = child_target {
path.push(child_key);
self.apply_spec_to_value(
child, root, value, context, path, budget,
)?;
path.pop();
}
}
}
continue;
}
if target.is_array() {
continue;
}
match &value {
Value::String(s) if s.starts_with('=') => {
let function_call = FunctionCall::parse(s)?;
if !self.should_write(target, key) {
continue;
}
let mut evaluated_args = Vec::new();
for arg in &function_call.args {
let evaluated =
evaluate_arg(arg, target, root, context, path, budget)?;
evaluated_args.push(evaluated);
}
let result = execute_function(&function_call.name, &evaluated_args)?;
budget.charge_entry(target, key, &result)?;
let target_map = target.as_object_mut().unwrap();
target_map.insert(key.clone(), result);
}
Value::Object(_) => {
if target.get(key).is_none() {
if Self::is_wildcard_only(value) {
continue;
}
budget.charge_entry(target, key, &Value::Object(Map::new()))?;
}
let target_map = target.as_object_mut().unwrap();
let nested_target = target_map
.entry(key.clone())
.or_insert(Value::Object(Map::new()));
path.push(key.clone());
self.apply_spec_to_value(
nested_target,
root,
value,
context,
path,
budget,
)?;
path.pop();
}
_ => {
if self.should_write(target, key) {
budget.charge_entry(target, key, value)?;
let target_map = target.as_object_mut().unwrap();
target_map.insert(key.clone(), value.clone());
}
}
}
}
Ok(())
}
_ => {
Err(Error::ParseError(format!(
"Modifier spec must be an object, got: {:?}",
spec
)))
}
}
}
}
impl<'de> Deserialize<'de> for ModifierSpec {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
Ok(ModifierSpec {
variant: ModifierVariant::OverwriteBeta,
spec: value,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::budget::MAX_RUN_BYTES;
use serde_json::json;
#[test]
fn test_budget_stops_wildcard_amplification() {
let elements = (MAX_RUN_BYTES / 50_000) + 1;
let input = json!({ "name": "x".repeat(50_000), "items": vec![json!({}); elements] });
let spec = json!({ "items": { "*": { "x": "=concat(@(3,name))" } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(
result,
Err(Error::ModifierBudgetLimit {
max: MAX_RUN_BYTES,
..
})
),
"got {result:?}"
);
}
#[test]
fn test_budget_allows_output_under_the_limit() {
let input = json!({ "name": "x".repeat(50_000), "items": vec![json!({}); 100] });
let spec = json!({ "items": { "*": { "x": "=concat(@(3,name))" } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec)
.apply(input)
.unwrap();
assert_eq!(result["items"][99]["x"].as_str().unwrap().len(), 50_000);
}
#[test]
fn test_budget_charges_arguments_when_the_result_is_small() {
let elements = (MAX_RUN_BYTES / 500_000) + 1;
let input = json!({ "date": "x".repeat(500_000), "items": vec![json!({}); elements] });
let spec = json!({ "items": { "*": { "y": "=substring(@(3,date),0,4)" } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_budget_charges_nested_function_arguments() {
let elements = (MAX_RUN_BYTES / 500_000) + 1;
let input = json!({ "date": "x".repeat(500_000), "items": vec![json!({}); elements] });
let spec = json!({ "items": { "*": { "y": "=substring(=trim(@(3,date)),0,4)" } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_budget_charges_created_parent_objects() {
let elements = MAX_RUN_BYTES / 1_000;
let input = json!({ "items": vec![json!({}); elements] });
let spec = json!({ "items": { "*": { "m": { "n": { "o": {} } } } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_budget_charges_long_keys_on_the_path() {
let key = "k".repeat(1024 * 1024);
let elements = (MAX_RUN_BYTES / key.len()) + 1;
let input =
json!({ "items": { key: { "v": "1", "list": vec![json!({"a": 1}); elements] } } });
let spec = json!({ "items": { "*": { "list": { "*": { "x": "=concat(@(3,v))" } } } } });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_budget_charges_context_arguments() {
let input = json!({ "context": { "k": "x".repeat(MAX_RUN_BYTES) } });
let spec = json!({ "y": "=substring(^k,0,1)" });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_budget_charges_identifier_arguments() {
let input = json!({ "date": "x".repeat(MAX_RUN_BYTES) });
let spec = json!({ "y": "=substring(date,0,1)" });
let result = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec).apply(input);
assert!(
matches!(result, Err(Error::ModifierBudgetLimit { .. })),
"got {result:?}"
);
}
#[test]
fn test_kept_value_is_not_charged() {
let mut budget = RunBudget::default();
let modifier = ModifierSpec::new(ModifierVariant::DefineBeta, json!({ "a": "new" }));
let mut target = json!({ "a": "old" });
modifier
.apply_spec_to_value(
&mut target,
&json!({}),
&modifier.spec,
None,
&mut Vec::new(),
&mut budget,
)
.unwrap();
assert_eq!(budget.used, 0);
}
#[test]
fn test_simple_concat() {
let input = json!({
"name": ["John", "Doe"]
});
let spec = json!({
"fullName": "=concat(@(1,name[0]),' ',@(1,name[1]))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["fullName"], json!("John Doe"));
assert_eq!(result["name"], json!(["John", "Doe"]));
}
#[test]
fn test_to_lower() {
let input = json!({
"text": "HELLO WORLD"
});
let spec = json!({
"lower": "=toLower(@(1,text))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["lower"], json!("hello world"));
}
#[test]
fn test_nested_spec() {
let input = json!({
"string": "the QuIcK brOwn fox"
});
let spec = json!({
"lower": {
"leading": "=toLower(@(2,string))"
}
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["lower"]["leading"], json!("the quick brown fox"));
}
#[test]
fn test_nested_function_call() {
let input = json!({
"text": "hello world"
});
let spec = json!({
"result": "=toUpper(=toLower(@(1,text)))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["result"], json!("HELLO WORLD"));
}
#[test]
fn test_substring_with_numeric_args() {
let input = json!({
"date": "20250605"
});
let spec = json!({
"year": "=substring(@(1,date),0,4)",
"month": "=substring(@(1,date),4,6)",
"day": "=substring(@(1,date),6,8)"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["year"], json!("2025"));
assert_eq!(result["month"], json!("06"));
assert_eq!(result["day"], json!("05"));
}
#[test]
fn test_nested_concat_substring() {
let input = json!({
"date": "20250605"
});
let spec = json!({
"formatted": "=concat(=substring(@(1,date),0,4),'-',=substring(@(1,date),4,6),'-',=substring(@(1,date),6,8))"
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["formatted"], json!("2025-06-05"));
}
#[test]
fn test_wildcard_object_iteration() {
let input = json!({
"entries": {
"0": { "date": "20250101" },
"1": { "date": "20251231" }
}
});
let spec = json!({
"entries": {
"*": {
"formatted": "=concat(=substring(@(1,date),0,4),'-',=substring(@(1,date),4,6),'-',=substring(@(1,date),6,8))"
}
}
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(result["entries"]["0"]["formatted"], json!("2025-01-01"));
assert_eq!(result["entries"]["1"]["formatted"], json!("2025-12-31"));
}
#[test]
fn test_wildcard_nested_object() {
let input = json!({
"temp": {
"entry": {
"0": { "resource": { "started": "20000101" } },
"1": { "resource": { "started": "20241225" } }
}
}
});
let spec = json!({
"temp": {
"entry": {
"*": {
"resource": {
"started": "=concat(=substring(@(1,started),0,4),'-',=substring(@(1,started),4,6),'-',=substring(@(1,started),6,8))"
}
}
}
}
});
let modifier = ModifierSpec::new(ModifierVariant::OverwriteBeta, spec);
let result = modifier.apply(input).unwrap();
assert_eq!(
result["temp"]["entry"]["0"]["resource"]["started"],
json!("2000-01-01")
);
assert_eq!(
result["temp"]["entry"]["1"]["resource"]["started"],
json!("2024-12-25")
);
}
}