Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
84 changes: 84 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions datadog-ffe/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ md5 = { version = "0.7.0", default-features = false }
regex = "1.10.4"
serde-bool = { version = "0.1.3", default-features = false }
serde_with = { version = "3.11.0", default-features = false, features = ["base64", "hex", "macros"] }
thiserror = "2.0.3"
url = "2.5.0"
thiserror = { version = "2.0.3", default-features = false }
url = { version = "2.5.0", default-features = false, features = ["std"] }
pyo3 = { version = "0.25", optional = true, default-features = false, features = ["macros"] }

[dev-dependencies]
env_logger = "0.10"
Expand All @@ -31,3 +32,6 @@ criterion = { version = "0.5", features = ["html_reports"] }
name = "ffe-eval"
harness = false
path = "benches/eval.rs"

[features]
pyo3 = ["dep:pyo3"]
3 changes: 3 additions & 0 deletions datadog-ffe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

pub mod rules_based;

#[cfg(feature = "pyo3")]
pub mod pyo3;
14 changes: 14 additions & 0 deletions datadog-ffe/src/pyo3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

use pyo3::prelude::*;

use crate::rules_based::{Assignment, AssignmentReason};

/// Initialize FFE Python classes under the given module.
pub fn init(m: &Bound<PyModule>) -> PyResult<()> {
m.add_class::<AssignmentReason>()?;
m.add_class::<Assignment>()?;

Ok(())
}
66 changes: 54 additions & 12 deletions datadog-ffe/src/rules_based/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use crate::rules_based::Str;
/// Attribute for evaluation context. See `From` implementations for initialization.
#[derive(Debug, Clone, PartialEq, PartialOrd, derive_more::From, Serialize, Deserialize)]
#[from(f64, bool, Str, String, &str, Arc<str>, Arc<String>, Cow<'_, str>)]
pub struct Attribute(AttributeValueImpl);
pub struct Attribute(AttributeImpl);
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize, derive_more::From)]
#[serde(untagged)]
enum AttributeValueImpl {
enum AttributeImpl {
#[from]
Number(f64),
#[from(forward)]
Expand All @@ -26,7 +26,7 @@ enum AttributeValueImpl {

impl Attribute {
pub(crate) fn is_null(&self) -> bool {
self == &Attribute(AttributeValueImpl::Null)
self == &Attribute(AttributeImpl::Null)
}

/// Try coercing attribute to a number.
Expand All @@ -35,8 +35,8 @@ impl Attribute {
/// number.
pub(crate) fn coerce_to_number(&self) -> Option<f64> {
match &self.0 {
AttributeValueImpl::Number(v) => Some(*v),
AttributeValueImpl::String(s) => s.parse().ok(),
AttributeImpl::Number(v) => Some(*v),
AttributeImpl::String(s) => s.parse().ok(),
_ => None,
}
}
Expand All @@ -46,19 +46,61 @@ impl Attribute {
/// String attributes are returned as is. Number and boolean attributes are converted to string.
pub(crate) fn coerce_to_string(&self) -> Option<Cow<'_, str>> {
match &self.0 {
AttributeValueImpl::String(s) => Some(Cow::Borrowed(s)),
AttributeValueImpl::Number(v) => Some(Cow::Owned(v.to_string())),
AttributeValueImpl::Boolean(v) => {
Some(Cow::Borrowed(if *v { "true" } else { "false" }))
}
AttributeValueImpl::Null => None,
AttributeImpl::String(s) => Some(Cow::Borrowed(s)),
AttributeImpl::Number(v) => Some(Cow::Owned(v.to_string())),
AttributeImpl::Boolean(v) => Some(Cow::Borrowed(if *v { "true" } else { "false" })),
AttributeImpl::Null => None,
}
}

pub(crate) fn as_str(&self) -> Option<&Str> {
match self {
Attribute(AttributeValueImpl::String(s)) => Some(s),
Attribute(AttributeImpl::String(s)) => Some(s),
_ => None,
}
}
}

#[cfg(feature = "pyo3")]
mod pyo3_impl {
use super::*;

use pyo3::{
exceptions::PyTypeError,
prelude::*,
types::{PyBool, PyFloat, PyInt, PyString},
};

/// Convert Python value to Attribute.
///
/// The following types are currently supported:
/// - `str`
/// - `int`
/// - `float`
/// - `bool`
/// - `NoneType`
///
/// Note that nesting is not currently supported and will throw an error.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

impl<'py> FromPyObject<'py> for Attribute {
#[inline]
fn extract_bound(value: &Bound<'py, PyAny>) -> PyResult<Self> {
if let Ok(s) = value.downcast::<PyString>() {
return Ok(Attribute(AttributeImpl::String(s.to_cow()?.into())));
}
// In Python, Bool inherits from Int, so it must be checked first here.
if let Ok(s) = value.downcast::<PyBool>() {
return Ok(Attribute(AttributeImpl::Boolean(s.is_true())));
}
if let Ok(s) = value.downcast::<PyFloat>() {
return Ok(Attribute(AttributeImpl::Number(s.value())));
}
if let Ok(s) = value.downcast::<PyInt>() {
return Ok(Attribute(AttributeImpl::Number(s.extract::<f64>()?)));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i64 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really. We only support float attributes, so ints are squashed to floats here

}
if value.is_none() {
return Ok(Attribute(AttributeImpl::Null));
}
Err(PyTypeError::new_err("invalid type for attribute"))
}
}
}
57 changes: 57 additions & 0 deletions datadog-ffe/src/rules_based/eval/evaluation_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,60 @@ impl EvaluationContext {
None
}
}

#[cfg(feature = "pyo3")]
mod pyo3_impl {
use super::*;

use pyo3::{intern, prelude::*, types::PyDict};

/// Accepts either a dict with `"targeting_key"` and `"attributes"` items, or any object with
/// `targeting_key` and `attributes` attributes.
///
/// # Examples
///
/// ```python
/// {"targeting_key": "user1", "attributes": {"attr1": 42}}
/// ```
///
/// ```python
/// @dataclass
/// class EvaluationContext:
/// targeting_key: Optional[str]
/// attributes: dict[str, Any]
///
/// EvaluationContext(targeting_key="user1", attributes={"attr1": 42})
/// ```
impl<'py> FromPyObject<'py> for EvaluationContext {
Comment on lines +59 to +76
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@avara1986 for evaluation context, either a dict or an object with targeting_key/attributes is accepted. (We can technically pass OF's EvaluationContext if we filter out unsupported attributes.)

#[inline]
fn extract_bound(value: &Bound<'py, PyAny>) -> PyResult<Self> {
let py = value.py();

let (targeting_key, attributes) = if let Ok(dict) = value.downcast::<PyDict>() {
(
dict.get_item(intern!(py, "targeting_key"))?,
dict.get_item(intern!(py, "attributes"))?,
)
} else {
(
value.getattr_opt(intern!(py, "targeting_key"))?,
value.getattr_opt(intern!(py, "attributes"))?,
)
};

let context = EvaluationContext {
targeting_key: targeting_key
.map(|it| it.extract())
.transpose()?
.unwrap_or_else(|| Str::from_static_str("").into()),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

confirming empty strings are acceptable input

attributes: attributes
.map(|it| it.extract())
.transpose()?
.map(Arc::new)
.unwrap_or_default(),
};

Ok(context)
}
}
}
28 changes: 28 additions & 0 deletions datadog-ffe/src/rules_based/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,31 @@ impl log::kv::ToValue for Str {
log::kv::Value::from_display(self)
}
}

#[cfg(feature = "pyo3")]
mod pyo3_impl {
use std::convert::Infallible;

use super::*;

use pyo3::{prelude::*, types::PyString};

impl<'py> FromPyObject<'py> for Str {
#[inline]
fn extract_bound(value: &Bound<'py, PyAny>) -> PyResult<Self> {
let s = value.downcast::<PyString>()?;
Ok(Str::from(s.to_cow()?))
}
}

impl<'py> IntoPyObject<'py> for &Str {
type Target = PyString;
type Output = Bound<'py, PyString>;
type Error = Infallible;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyString::new(py, self.as_str()))
}
}
}
Loading
Loading