Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert CEL values to JSON #77

Merged
merged 9 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ jobs:
- name: Clippy
run: cargo clippy --all-features --all-targets -- -D warnings
- name: Run tests
run: cargo test --verbose
run: |
cargo test --verbose
cargo test --verbose --features json
8 changes: 7 additions & 1 deletion example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ axum = { version = "0.7.5", default-features = false, features = [
"json",
"tokio",
] }
cel-interpreter = { path = "../interpreter" }
cel-interpreter = { path = "../interpreter", features = ["json"] }
chrono = "0.4.26"
serde = { version = "1.0.196", features = ["derive"] }
serde_json = "1.0.124"
thiserror = { version = "1.0.61", default-features = false }
tokio = { version = "1.38.0", default-features = false, features = [
"macros",
Expand Down Expand Up @@ -42,3 +43,8 @@ path = "src/serde.rs"
[[bin]]
name = "axum"
path = "src/axum.rs"

[[bin]]
name = "json"
path = "src/json.rs"

12 changes: 12 additions & 0 deletions example/src/json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use cel_interpreter::{Context, Program};

fn main() {
// Create a CEL program that returns a JSON object
let program = Program::compile("{'foo': true}").unwrap();
let value = program.execute(&Context::default()).unwrap();

// Convert the return type to JSON and cast to object
let json = value.json().unwrap();
let object = json.as_object().unwrap();
assert_eq!(Some(&serde_json::Value::Bool(true)), object.get("foo"));
}
4 changes: 1 addition & 3 deletions example/src/serde.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cel_interpreter::{to_value, Context, Program};
use cel_interpreter::{Context, Program};
use serde::Serialize;

// An example struct that derives Serialize
Expand All @@ -16,8 +16,6 @@ fn main() {
context
.add_variable("foo", MyStruct { a: 1, b: 1 })
.unwrap();
// To explicitly serialize structs use to_value()
let _cel_value = to_value(MyStruct { a: 2, b: 2 }).unwrap();

let value = program.execute(&context).unwrap();
assert_eq!(value, true.into());
Expand Down
6 changes: 6 additions & 0 deletions interpreter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ nom = "7.1.3"
paste = "1.0.14"
serde = "1.0.196"
regex = "1.10.5"
serde_json = { version = "1.0.124", optional = true }
base64 = { version = "0.22.1", optional = true }

[dev-dependencies]
criterion = { version = "0.5.1", features = ["html_reports"] }
Expand All @@ -24,3 +26,7 @@ serde_bytes = "0.11.14"
[[bench]]
name = "runtime"
harness = false

[features]
json = ["dep:base64", "dep:serde_json"]

92 changes: 92 additions & 0 deletions interpreter/src/json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use crate::duration::format_duration;
use crate::Value;
use thiserror::Error;

/// Error converting a CEL value to a JSON value.
#[derive(Debug, Clone, Error)]
#[error("unable to convert value to json: {0:?}")]
pub struct ConvertToJsonError<'a>(&'a Value);

impl Value {
/// Converts a CEL value to a JSON value.
///
/// # Example
/// ```
/// use cel_interpreter::{Context, Program};
///
/// let program = Program::compile("null").unwrap();
/// let value = program.execute(&Context::default()).unwrap();
/// let result = value.json().unwrap();
///
/// assert_eq!(result, serde_json::Value::Null);
/// ```
pub fn json(&self) -> Result<serde_json::Value, ConvertToJsonError> {
use base64::prelude::*;
Ok(match *self {
Value::List(ref vec) => serde_json::Value::Array(
vec.iter()
.map(|v| v.json())
.collect::<Result<Vec<_>, _>>()?,
),
Value::Map(ref map) => {
let mut obj = serde_json::Map::new();
for (k, v) in map.map.iter() {
obj.insert(k.to_string(), v.json()?);
}
serde_json::Value::Object(obj)
}
Value::Int(i) => i.into(),
Value::UInt(u) => u.into(),
Value::Float(f) => f.into(),
Value::String(ref s) => s.to_string().into(),
Value::Bool(b) => b.into(),
Value::Timestamp(ref dt) => dt.to_rfc3339().into(),
Value::Bytes(ref b) => BASE64_STANDARD.encode(b.as_slice()).to_string().into(),
Value::Null => serde_json::Value::Null,
Value::Duration(v) => format_duration(&v).to_string().into(),
clarkmcc marked this conversation as resolved.
Show resolved Hide resolved
_ => return Err(ConvertToJsonError(self)),
})
}
}

#[cfg(test)]
mod tests {
use crate::objects::Map;
use crate::Value as CelValue;
use chrono::Duration;
use serde_json::json;
use std::collections::HashMap;

#[test]
fn test_cel_value_to_json() {
let tests = [
(json!("hello"), CelValue::String("hello".to_string().into())),
(json!(42), CelValue::Int(42)),
(json!(42.0), CelValue::Float(42.0)),
(json!(true), CelValue::Bool(true)),
(json!(null), CelValue::Null),
(json!("1s"), CelValue::Duration(Duration::seconds(1))),
(
json!([true, null]),
CelValue::List(vec![CelValue::Bool(true), CelValue::Null].into()),
),
(
json!({"hello": "world"}),
CelValue::Map(Map::from(HashMap::from([(
"hello".to_string(),
CelValue::String("world".to_string().into()),
)]))),
),
];

for (expected, value) in tests.iter() {
assert_eq!(
value.json().unwrap(),
*expected,
"{:?}={:?}",
value,
expected
);
}
}
}
4 changes: 4 additions & 0 deletions interpreter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ pub mod objects;
mod resolvers;
mod ser;
pub use ser::to_value;

#[cfg(feature = "json")]
mod json;
#[cfg(test)]
mod testing;

use magic::FromContext;

pub mod extractors {
Expand Down
21 changes: 15 additions & 6 deletions interpreter/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ impl Serialize for Key {
}
}

impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Key::Int(v) => write!(f, "{}", v),
Key::Uint(v) => write!(f, "{}", v),
Key::Bool(v) => write!(f, "{}", v),
Key::String(v) => write!(f, "{}", v),
}
}
}

/// Implement conversions from [`Key`] into [`Value`]

impl TryInto<Key> for Value {
Expand Down Expand Up @@ -514,10 +525,9 @@ impl<'a> Value {
let value = Value::resolve(v, ctx)?;
map.insert(key, value);
}
Value::Map(Map {
Ok(Value::Map(Map {
map: Arc::from(map),
})
.into()
}))
}
Expression::Ident(name) => ctx.get_variable(&***name),
Expression::FunctionCall(name, target, args) => {
Expand Down Expand Up @@ -570,10 +580,9 @@ impl<'a> Value {
.into(),
(Value::String(str), Value::Int(idx)) => {
match str.get(idx as usize..(idx + 1) as usize) {
None => Value::Null,
Some(str) => Value::String(str.to_string().into()),
None => Ok(Value::Null),
Some(str) => Ok(Value::String(str.to_string().into())),
}
.into()
}
(Value::Map(map), Value::String(property)) => map
.get(&property.into())
Expand Down
Loading