|
| 1 | +use cel_interpreter::objects::{Key, TryIntoValue}; |
| 2 | +use cel_interpreter::{Context, Program, Value}; |
| 3 | +use log::debug; |
| 4 | +use pyo3::exceptions::PyValueError; |
| 5 | +use pyo3::prelude::*; |
| 6 | +use pyo3::types::{PyDict, PyList}; |
| 7 | +use std::collections::HashMap; |
| 8 | +use std::error::Error; |
| 9 | +use std::fmt; |
| 10 | + |
| 11 | +#[derive(Debug)] |
| 12 | +struct RustyCelType(Value); |
| 13 | + |
| 14 | +impl IntoPy<PyObject> for RustyCelType { |
| 15 | + fn into_py(self, py: Python<'_>) -> PyObject { |
| 16 | + // Just use the native rust type's existing |
| 17 | + // IntoPy implementation |
| 18 | + match self { |
| 19 | + // Primitive Types |
| 20 | + RustyCelType(Value::Null) => py.None(), |
| 21 | + RustyCelType(Value::Bool(b)) => b.into_py(py), |
| 22 | + RustyCelType(Value::Int(i64)) => i64.into_py(py), |
| 23 | + RustyCelType(Value::UInt(u64)) => u64.into_py(py), |
| 24 | + RustyCelType(Value::Float(f)) => f.into_py(py), |
| 25 | + RustyCelType(Value::Timestamp(ts)) => ts.into_py(py), |
| 26 | + RustyCelType(Value::String(arcStr)) => arcStr.as_ref().into_py(py), |
| 27 | + RustyCelType(Value::List(val)) => { |
| 28 | + let list = val |
| 29 | + .as_ref() |
| 30 | + .into_iter() |
| 31 | + .map(|v| RustyCelType(v.clone()).into_py(py)) |
| 32 | + .collect::<Vec<PyObject>>(); |
| 33 | + list.into_py(py) |
| 34 | + } |
| 35 | + RustyCelType(Value::Bytes(val)) => { |
| 36 | + let bytes = val; |
| 37 | + bytes.as_ref().as_slice().into_py(py) |
| 38 | + } |
| 39 | + RustyCelType(Value::Duration(d)) => d.into_py(py), |
| 40 | + |
| 41 | + RustyCelType(Value::Map(val)) => { |
| 42 | + // Create a PyDict with the converted Python key and values. |
| 43 | + let python_dict = PyDict::new_bound(py); |
| 44 | + |
| 45 | + val.map.as_ref().into_iter().for_each(|(k, v)| { |
| 46 | + // Key is an enum with String, Uint, Int and Bool variants. Value is any RustyCelType |
| 47 | + let key = match k { |
| 48 | + Key::String(arcStr) => arcStr.as_ref().into_py(py), |
| 49 | + Key::Uint(u64) => u64.into_py(py), |
| 50 | + Key::Int(i64) => i64.into_py(py), |
| 51 | + Key::Bool(b) => b.into_py(py), |
| 52 | + _ => panic!("Invalid key type in Map"), |
| 53 | + }; |
| 54 | + let value = RustyCelType(v.clone()).into_py(py); |
| 55 | + python_dict |
| 56 | + .set_item(key, value) |
| 57 | + .expect("Failed to set item in Python dict"); |
| 58 | + }); |
| 59 | + |
| 60 | + python_dict.into() |
| 61 | + } |
| 62 | + |
| 63 | + // Turn everything else into a String: |
| 64 | + nonprimitive => format!("{:?}", nonprimitive).into_py(py), |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +#[derive(Debug)] |
| 70 | +struct RustyPyType<'a>(&'a PyAny); |
| 71 | + |
| 72 | +#[derive(Debug, PartialEq, Clone)] |
| 73 | +pub enum CelError { |
| 74 | + ConversionError(String) |
| 75 | +} |
| 76 | + |
| 77 | +impl fmt::Display for CelError { |
| 78 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 79 | + write!(f, "Cel Error") |
| 80 | + } |
| 81 | +} |
| 82 | +impl Error for CelError {} |
| 83 | + |
| 84 | +/// We can't implement TryIntoValue for PyAny, so we implement for our wrapper type |
| 85 | +impl TryIntoValue for RustyPyType<'_> { |
| 86 | + type Error = CelError; |
| 87 | + |
| 88 | + fn try_into_value(self) -> Result<Value, Self::Error> { |
| 89 | + let val = match self { |
| 90 | + RustyPyType(pyobject) => { |
| 91 | + if let Ok(value) = pyobject.extract::<i64>() { |
| 92 | + Ok(Value::Int(value)) |
| 93 | + } else if let Ok(value) = pyobject.extract::<f64>() { |
| 94 | + Ok(Value::Float(value)) |
| 95 | + } else if let Ok(value) = pyobject.extract::<bool>() { |
| 96 | + Ok(Value::Bool(value)) |
| 97 | + } else if let Ok(value) = pyobject.extract::<String>() { |
| 98 | + Ok(Value::String(value.into())) |
| 99 | + |
| 100 | + // TODO Deal with container types (List, Dict etc) |
| 101 | + |
| 102 | + // } else if let Ok(value) = pyobject.extract::<PyList>() { |
| 103 | + // let list = value |
| 104 | + // .iter() |
| 105 | + // .map(|item| RustyPyType((*item)).try_into_value().expect("Failed to convert PyList to Value")) |
| 106 | + // .collect::<Vec<Value>>(); |
| 107 | + // Ok(Value::List(list.into())) |
| 108 | + // } else if let Ok(value) = pyobject.extract::<PyDict>() { |
| 109 | + // let mut map:HashMap<Key, Value> = HashMap::new(); |
| 110 | + // for (key, value) in value.into_iter() { |
| 111 | + // let key = key.extract::<String>()?; |
| 112 | + // |
| 113 | + // map.insert(Key::String(key.into()), RustyPyType(*value).try_into_value().expect("Failed to convert PyDict to Value")); |
| 114 | + // } |
| 115 | + // Ok(Value::Map(map.into())) |
| 116 | + } else { |
| 117 | + Err(CelError::ConversionError("Failed to convert PyAny to Value".to_string())) |
| 118 | + } |
| 119 | + } |
| 120 | + }; |
| 121 | + val |
| 122 | + |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +/// Evaluate a CEL expression |
| 127 | +/// Returns a String representation of the result |
| 128 | +#[pyfunction] |
| 129 | +fn evaluate(src: String, context: Option<&PyDict>) -> PyResult<RustyCelType> { |
| 130 | + debug!("Evaluating CEL expression: {}", src); |
| 131 | + debug!("Context: {:?}", context); |
| 132 | + |
| 133 | + let program = Program::compile(src.as_str()); |
| 134 | + |
| 135 | + // Handle the result of the compilation |
| 136 | + match program { |
| 137 | + Err(compile_error) => { |
| 138 | + println!("An error occurred during compilation"); |
| 139 | + println!("compile_error: {:?}", compile_error); |
| 140 | + // compile_error |
| 141 | + // .into_iter() |
| 142 | + // .for_each(|e| println!("Parse error: {:?}", e)); |
| 143 | + return Err(PyValueError::new_err("Parse Error")); |
| 144 | + } |
| 145 | + Ok(program) => { |
| 146 | + let mut environment = Context::default(); |
| 147 | + environment.add_function("add", |a: i64, b: i64| a + b); |
| 148 | + |
| 149 | + // Add any variables from the passed in Dict context |
| 150 | + if let Some(context) = context { |
| 151 | + for (key, value) in context { |
| 152 | + let key = key.extract::<String>().unwrap(); |
| 153 | + // Each value is of type PyAny, we need to try to extract into a Value |
| 154 | + // and then add it to the CEL context |
| 155 | + |
| 156 | + |
| 157 | + let wrapped_value = RustyPyType(value); |
| 158 | + match wrapped_value.try_into_value() { |
| 159 | + Ok(value) => { |
| 160 | + environment |
| 161 | + .add_variable(key, value) |
| 162 | + .expect("Failed to add variable to context"); |
| 163 | + } |
| 164 | + Err(error) => { |
| 165 | + println!("An error occurred during conversion"); |
| 166 | + println!("Conversion error: {:?}", error); |
| 167 | + return Err(PyValueError::new_err("Conversion Error")); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + // This direct way is a bit hacky, need to find a better way to do this with traits |
| 172 | + // if let Ok(value) = value.extract::<i64>() { |
| 173 | + // environment |
| 174 | + // .add_variable(key, Value::Int(value)) |
| 175 | + // .expect("Failed to add variable to context"); |
| 176 | + // } else if let Ok(value) = value.extract::<f64>() { |
| 177 | + // environment |
| 178 | + // .add_variable(key, value) |
| 179 | + // .expect("Failed to add variable to context"); |
| 180 | + // } else if let Ok(value) = value.extract::<bool>() { |
| 181 | + // environment |
| 182 | + // .add_variable(key, value) |
| 183 | + // .expect("Failed to add variable to context"); |
| 184 | + // } else if let Ok(value) = value.extract::<String>() { |
| 185 | + // environment |
| 186 | + // .add_variable(key, value) |
| 187 | + // .expect("Failed to add variable to context"); |
| 188 | + // } |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + let result = program.execute(&environment); |
| 193 | + match result { |
| 194 | + Err(error) => { |
| 195 | + println!("An error occurred during execution"); |
| 196 | + println!("Execution error: {:?}", error); |
| 197 | + // errors |
| 198 | + // .into_iter() |
| 199 | + // .for_each(|e| println!("Execution error: {:?}", e)); |
| 200 | + Err(PyValueError::new_err("Execution Error")) |
| 201 | + } |
| 202 | + |
| 203 | + Ok(value) => return Ok(RustyCelType(value)), |
| 204 | + } |
| 205 | + } |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +/// A Python module implemented in Rust. |
| 210 | +#[pymodule] |
| 211 | +fn cel(_py: Python, m: &PyModule) -> PyResult<()> { |
| 212 | + m.add_function(wrap_pyfunction!(evaluate, m)?)?; |
| 213 | + Ok(()) |
| 214 | +} |
0 commit comments