mirror of
https://github.com/gorules/zen.git
synced 2026-11-29 08:06:51 +00:00
fix(engine): accept the string and reference trace modes again (#578)
This commit is contained in:
@@ -5,7 +5,7 @@ use std::ptr;
|
||||
use napi::bindgen_prelude::ToNapiValue;
|
||||
use napi::sys;
|
||||
use napi::sys::{napi_env, napi_value};
|
||||
use zen_engine::{DecisionGraphResponse, EvaluationTrace};
|
||||
use zen_engine::{DecisionGraphResponse, EvaluationTrace, EvaluationTraceKind};
|
||||
use zen_expression::variable::{RcCell, ToVariable};
|
||||
use zen_expression::Variable;
|
||||
|
||||
@@ -82,6 +82,7 @@ impl PortableArena {
|
||||
pub enum TraceField {
|
||||
None,
|
||||
Arena(u32),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
pub struct NodeEvalResponse {
|
||||
@@ -92,7 +93,7 @@ pub struct NodeEvalResponse {
|
||||
}
|
||||
|
||||
impl NodeEvalResponse {
|
||||
pub fn build(response: DecisionGraphResponse) -> Self {
|
||||
pub fn build(response: DecisionGraphResponse, kind: EvaluationTraceKind) -> Self {
|
||||
let mut arena = PortableArena::new();
|
||||
let mut memo = HashMap::new();
|
||||
|
||||
@@ -101,12 +102,31 @@ impl NodeEvalResponse {
|
||||
let trace = match response.trace {
|
||||
None => TraceField::None,
|
||||
Some(EvaluationTrace::Graph(graph)) => {
|
||||
TraceField::Arena(arena.add(&graph.to_variable(), &mut memo))
|
||||
}
|
||||
Some(EvaluationTrace::Policy(policy)) => {
|
||||
let value = serde_json::to_value(&policy).unwrap_or_default();
|
||||
TraceField::Arena(arena.add(&Variable::from(value), &mut memo))
|
||||
let variable = graph.to_variable();
|
||||
match kind {
|
||||
EvaluationTraceKind::None | EvaluationTraceKind::Default => {
|
||||
TraceField::Arena(arena.add(&variable, &mut memo))
|
||||
}
|
||||
EvaluationTraceKind::Reference => {
|
||||
let value =
|
||||
serde_json::to_value(variable.serialize_ref()).unwrap_or_default();
|
||||
TraceField::Arena(arena.add(&Variable::from(value), &mut memo))
|
||||
}
|
||||
EvaluationTraceKind::String => {
|
||||
TraceField::Text(serde_json::to_string(&variable).unwrap_or_default())
|
||||
}
|
||||
EvaluationTraceKind::ReferenceString => TraceField::Text(
|
||||
serde_json::to_string(&variable.serialize_ref()).unwrap_or_default(),
|
||||
),
|
||||
}
|
||||
}
|
||||
Some(EvaluationTrace::Policy(policy)) => match kind.text() {
|
||||
true => TraceField::Text(serde_json::to_string(&policy).unwrap_or_default()),
|
||||
false => {
|
||||
let value = serde_json::to_value(&policy).unwrap_or_default();
|
||||
TraceField::Arena(arena.add(&Variable::from(value), &mut memo))
|
||||
}
|
||||
},
|
||||
Some(EvaluationTrace::V1(document)) => {
|
||||
TraceField::Arena(arena.add(&document.to_variable(), &mut memo))
|
||||
}
|
||||
@@ -228,6 +248,7 @@ impl ToNapiValue for NodeEvalResponse {
|
||||
let trace = match &val.trace {
|
||||
TraceField::None => None,
|
||||
TraceField::Arena(root) => Some(materializer.value(*root)?),
|
||||
TraceField::Text(text) => Some(materializer.string(text)),
|
||||
};
|
||||
|
||||
if let Some(trace) = trace {
|
||||
|
||||
@@ -31,6 +31,7 @@ impl ZenDecision {
|
||||
opts: Option<ZenEvaluateOptions>,
|
||||
) -> napi::Result<NodeEvalResponse> {
|
||||
let decision = self.0.clone();
|
||||
let kind = crate::engine::JsTraceFormat::kind(&opts);
|
||||
let options: zen_engine::EvaluationOptions = opts.unwrap_or_default().try_into()?;
|
||||
let result = spawn_worker(move || async move {
|
||||
let context = zen_engine::Variable::try_from_value(context).map_err(
|
||||
@@ -39,8 +40,8 @@ impl ZenDecision {
|
||||
decision
|
||||
.evaluate_with_opts(context, options)
|
||||
.await
|
||||
.map(NodeEvalResponse::build)
|
||||
.map_err(|e| serde_json::to_value(&*e).unwrap_or_default())
|
||||
.map(|response| NodeEvalResponse::build(response, kind))
|
||||
.map_err(|e| crate::engine::JsTraceFormat::failure(&e, kind))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow!("Hook timed out"))?
|
||||
|
||||
@@ -25,7 +25,9 @@ use crate::types::{ZenEngineHandlerRequest, ZenEngineHandlerResponse};
|
||||
use zen_engine::loader::{DynamicLoader, LoaderConfig};
|
||||
use zen_engine::model::DecisionContent;
|
||||
use zen_engine::trace::TraceFormat;
|
||||
use zen_engine::{DecisionEngine, EvaluationOptions, EvaluationSerializedOptions};
|
||||
use zen_engine::{
|
||||
DecisionEngine, EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind,
|
||||
};
|
||||
|
||||
#[napi]
|
||||
pub struct ZenEngine {
|
||||
@@ -36,8 +38,8 @@ pub struct ZenEngine {
|
||||
http_handler_tsfn: Option<HttpHandlerTsfn>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct JsTraceFormat(pub TraceFormat);
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct JsTraceFormat(pub TraceFormat, pub EvaluationTraceKind);
|
||||
|
||||
impl FromNapiValue for JsTraceFormat {
|
||||
unsafe fn from_napi_value(env: napi_env, napi_val: napi_value) -> napi::Result<Self> {
|
||||
@@ -45,24 +47,74 @@ impl FromNapiValue for JsTraceFormat {
|
||||
|
||||
match js_value.get_type()? {
|
||||
ValueType::Undefined | ValueType::Null => Ok(JsTraceFormat::default()),
|
||||
ValueType::Boolean => Ok(JsTraceFormat(TraceFormat::from(js_value.coerce_to_bool()?))),
|
||||
ValueType::Boolean => Ok(Self::switched(js_value.coerce_to_bool()?)),
|
||||
ValueType::String => {
|
||||
let utf8 = js_value.coerce_to_string()?.into_utf8()?;
|
||||
let format =
|
||||
TraceFormat::from_str(utf8.as_str()?).context("invalid trace format")?;
|
||||
Ok(JsTraceFormat(format))
|
||||
let text = utf8.as_str()?;
|
||||
if let Ok(format) = TraceFormat::from_str(text) {
|
||||
return Ok(match format {
|
||||
TraceFormat::Off => Self::switched(false),
|
||||
format => JsTraceFormat(format, EvaluationTraceKind::Default),
|
||||
});
|
||||
}
|
||||
let kind = EvaluationTraceKind::from_str(text).context("invalid trace format")?;
|
||||
Ok(match kind {
|
||||
EvaluationTraceKind::None => Self::switched(false),
|
||||
EvaluationTraceKind::Default => Self::switched(true),
|
||||
kind => JsTraceFormat(TraceFormat::Legacy, kind),
|
||||
})
|
||||
}
|
||||
_ => Err(anyhow!("Invalid trace setting").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsTraceFormat {
|
||||
fn switched(on: bool) -> Self {
|
||||
match on {
|
||||
true => JsTraceFormat(TraceFormat::from(true), EvaluationTraceKind::Default),
|
||||
false => JsTraceFormat(TraceFormat::Off, EvaluationTraceKind::None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn kind(options: &Option<ZenEvaluateOptions>) -> EvaluationTraceKind {
|
||||
options
|
||||
.as_ref()
|
||||
.and_then(|options| options.trace)
|
||||
.map(|trace| trace.1)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn failure(
|
||||
error: &zen_engine::EvaluationError,
|
||||
kind: EvaluationTraceKind,
|
||||
) -> serde_json::Value {
|
||||
match kind {
|
||||
EvaluationTraceKind::None | EvaluationTraceKind::Default => {
|
||||
serde_json::to_value(error).unwrap_or_default()
|
||||
}
|
||||
kind => error
|
||||
.serialize_with_mode(serde_json::value::Serializer, kind)
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToNapiValue for JsTraceFormat {
|
||||
unsafe fn to_napi_value(env: napi_env, val: Self) -> napi::Result<napi_value> {
|
||||
match val.0 {
|
||||
TraceFormat::Off => ToNapiValue::to_napi_value(env, false),
|
||||
TraceFormat::V1 => ToNapiValue::to_napi_value(env, true),
|
||||
TraceFormat::Legacy => ToNapiValue::to_napi_value(env, "legacy"),
|
||||
match val {
|
||||
JsTraceFormat(TraceFormat::Off, _) => ToNapiValue::to_napi_value(env, false),
|
||||
JsTraceFormat(
|
||||
_,
|
||||
kind @ (EvaluationTraceKind::String
|
||||
| EvaluationTraceKind::Reference
|
||||
| EvaluationTraceKind::ReferenceString),
|
||||
) => {
|
||||
let text: &'static str = kind.into();
|
||||
ToNapiValue::to_napi_value(env, text)
|
||||
}
|
||||
JsTraceFormat(TraceFormat::V1, _) => ToNapiValue::to_napi_value(env, true),
|
||||
JsTraceFormat(TraceFormat::Legacy, _) => ToNapiValue::to_napi_value(env, "legacy"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,7 +123,7 @@ impl ToNapiValue for JsTraceFormat {
|
||||
#[napi(object)]
|
||||
pub struct ZenEvaluateOptions {
|
||||
pub max_depth: Option<u8>,
|
||||
#[napi(ts_type = "boolean | 'v1' | 'legacy'")]
|
||||
#[napi(ts_type = "boolean | 'v1' | 'legacy' | 'string' | 'reference' | 'referenceString'")]
|
||||
pub trace: Option<JsTraceFormat>,
|
||||
#[napi(ts_type = "string | number")]
|
||||
pub now: Option<Either<String, f64>>,
|
||||
@@ -299,6 +351,7 @@ impl ZenEngine {
|
||||
opts: Option<ZenEvaluateOptions>,
|
||||
) -> napi::Result<NodeEvalResponse> {
|
||||
let graph = self.graph.clone();
|
||||
let kind = JsTraceFormat::kind(&opts);
|
||||
let options: EvaluationOptions = opts.unwrap_or_default().try_into()?;
|
||||
let result = spawn_worker(move || async move {
|
||||
let context = zen_engine::Variable::try_from_value(context).map_err(
|
||||
@@ -307,8 +360,8 @@ impl ZenEngine {
|
||||
graph
|
||||
.evaluate_with_opts(key, context, options)
|
||||
.await
|
||||
.map(NodeEvalResponse::build)
|
||||
.map_err(|e| serde_json::to_value(&*e).unwrap_or_default())
|
||||
.map(|response| NodeEvalResponse::build(response, kind))
|
||||
.map_err(|e| JsTraceFormat::failure(&e, kind))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow!("Hook timed out"))?
|
||||
@@ -379,6 +432,7 @@ impl ZenEngine {
|
||||
requests: Vec<EvaluateBatchRequest>,
|
||||
opts: Option<ZenEvaluateOptions>,
|
||||
) -> napi::Result<Vec<EvaluateBatchResult>> {
|
||||
let kind = JsTraceFormat::kind(&opts);
|
||||
let options: EvaluationSerializedOptions = opts.unwrap_or_default().try_into()?;
|
||||
|
||||
let mut handles = Vec::with_capacity(requests.len());
|
||||
@@ -394,8 +448,8 @@ impl ZenEngine {
|
||||
engine
|
||||
.evaluate_with_opts(key, context, eval_opts)
|
||||
.await
|
||||
.map(NodeEvalResponse::build)
|
||||
.map_err(|e| serde_json::to_value(&*e).unwrap_or_default())
|
||||
.map(|response| NodeEvalResponse::build(response, kind))
|
||||
.map_err(|e| JsTraceFormat::failure(&e, kind))
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -198,4 +198,43 @@ describe('Expressions', () => {
|
||||
expect(renderTemplateSync(template, context)).toEqual(result);
|
||||
}
|
||||
});
|
||||
|
||||
it('Serialises traces in the string and reference modes on both engine versions', async () => {
|
||||
const timeless = (value: any): any => {
|
||||
if (Array.isArray(value)) return value.map(timeless);
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => key !== 'performance')
|
||||
.map(([key, inner]) => [key, timeless(inner)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
for (const version of [1, 2] as const) {
|
||||
const engine = new ZenEngine({ loader, version });
|
||||
const input = { input: 12 };
|
||||
const plain: any = await engine.evaluate('table.json', input, { trace: 'legacy' });
|
||||
const text: any = await engine.evaluate('table.json', input, { trace: 'string' });
|
||||
const reference: any = await engine.evaluate('table.json', input, { trace: 'reference' });
|
||||
const referenceText: any = await engine.evaluate('table.json', input, { trace: 'referenceString' });
|
||||
|
||||
expect(typeof plain.trace).toEqual('object');
|
||||
expect(typeof text.trace).toEqual('string');
|
||||
expect(timeless(JSON.parse(text.trace))).toEqual(timeless(plain.trace));
|
||||
expect(typeof reference.trace).toEqual('object');
|
||||
expect(typeof referenceText.trace).toEqual('string');
|
||||
expect(Object.keys(JSON.parse(referenceText.trace)).sort()).toEqual(Object.keys(reference.trace).sort());
|
||||
for (const response of [plain, text, reference, referenceText]) {
|
||||
expect(response.result).toEqual(plain.result);
|
||||
}
|
||||
|
||||
const decision = await engine.getDecision('table.json');
|
||||
const direct: any = await decision.evaluate(input, { trace: 'string' });
|
||||
expect(timeless(JSON.parse(direct.trace))).toEqual(timeless(plain.trace));
|
||||
|
||||
await expect((async () => engine.evaluate('table.json', input, { trace: 'nonsense' as any }))()).rejects.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -961,6 +961,34 @@ impl EvaluationTrace {
|
||||
}
|
||||
|
||||
impl DecisionGraphResponse {
|
||||
pub fn serialize_with_mode<S>(
|
||||
&self,
|
||||
serializer: S,
|
||||
mode: crate::EvaluationTraceKind,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
use serde::ser::SerializeMap;
|
||||
use zen_expression::variable::ToVariable;
|
||||
let mut map = serializer.serialize_map(None)?;
|
||||
map.serialize_entry("performance", &self.performance)?;
|
||||
map.serialize_entry("result", &self.result)?;
|
||||
match &self.trace {
|
||||
None => {}
|
||||
Some(EvaluationTrace::Graph(graph)) => {
|
||||
map.serialize_entry("trace", &mode.serialize_trace(&graph.to_variable()))?;
|
||||
}
|
||||
Some(other) => match mode.text() {
|
||||
true => {
|
||||
map.serialize_entry("trace", &serde_json::to_string(other).unwrap_or_default())?
|
||||
}
|
||||
false => map.serialize_entry("trace", other)?,
|
||||
},
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
|
||||
pub(crate) fn serialized(
|
||||
response: Result<Self, Box<EvaluationError>>,
|
||||
) -> Result<serde_json::Value, serde_json::Value> {
|
||||
|
||||
@@ -77,6 +77,39 @@ impl Default for EvaluationOptions {
|
||||
|
||||
pub type EvaluationSerializedOptions = EvaluationOptions;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::IntoStaticStr)]
|
||||
#[strum(serialize_all = "camelCase")]
|
||||
pub enum EvaluationTraceKind {
|
||||
#[default]
|
||||
None,
|
||||
Default,
|
||||
String,
|
||||
Reference,
|
||||
ReferenceString,
|
||||
}
|
||||
|
||||
impl EvaluationTraceKind {
|
||||
pub fn serialize_trace(&self, trace: &Variable) -> Value {
|
||||
match self {
|
||||
EvaluationTraceKind::None => Value::Null,
|
||||
EvaluationTraceKind::Default => serde_json::to_value(trace).unwrap_or_default(),
|
||||
EvaluationTraceKind::String => {
|
||||
Value::String(serde_json::to_string(trace).unwrap_or_default())
|
||||
}
|
||||
EvaluationTraceKind::Reference => {
|
||||
serde_json::to_value(trace.serialize_ref()).unwrap_or_default()
|
||||
}
|
||||
EvaluationTraceKind::ReferenceString => {
|
||||
Value::String(serde_json::to_string(&trace.serialize_ref()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(&self) -> bool {
|
||||
matches!(self, Self::String | Self::ReferenceString)
|
||||
}
|
||||
}
|
||||
|
||||
impl EvaluationOptions {
|
||||
pub(crate) fn pinned(&self) -> zen_expression::context::Pinned {
|
||||
zen_expression::context::Pinned {
|
||||
|
||||
@@ -77,7 +77,22 @@ pub enum EvaluationError {
|
||||
}
|
||||
|
||||
impl EvaluationError {
|
||||
fn serialize_map<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
pub fn serialize_with_mode<S>(
|
||||
&self,
|
||||
serializer: S,
|
||||
mode: crate::EvaluationTraceKind,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.serialize_traced(serializer, Some(mode))
|
||||
}
|
||||
|
||||
fn serialize_traced<S>(
|
||||
&self,
|
||||
serializer: S,
|
||||
mode: Option<crate::EvaluationTraceKind>,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
@@ -97,7 +112,10 @@ impl EvaluationError {
|
||||
map.serialize_entry("nodeId", &node_id)?;
|
||||
|
||||
if let Some(trace) = &trace {
|
||||
map.serialize_entry("trace", trace)?;
|
||||
match mode {
|
||||
Some(mode) => map.serialize_entry("trace", &mode.serialize_trace(trace))?,
|
||||
None => map.serialize_entry("trace", trace)?,
|
||||
}
|
||||
}
|
||||
}
|
||||
EvaluationError::LoaderError(err) => {
|
||||
@@ -141,7 +159,7 @@ impl Serialize for EvaluationError {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.serialize_map(serializer)
|
||||
self.serialize_traced(serializer, None)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -159,7 +159,9 @@ pub use decision::Decision;
|
||||
pub use decision_graph::{
|
||||
DecisionGraphResponse, DecisionGraphTrace, DecisionGraphValidationError, EvaluationTrace,
|
||||
};
|
||||
pub use engine::{DecisionEngine, EvaluationOptions, EvaluationSerializedOptions};
|
||||
pub use engine::{
|
||||
DecisionEngine, EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind,
|
||||
};
|
||||
pub use error::{CompileFailure, ContentKindError, EvaluationError};
|
||||
pub use workspace::Workspace;
|
||||
pub use zen_expression::Variable;
|
||||
|
||||
@@ -1431,3 +1431,56 @@ fn a_table_output_reads_the_value_its_rule_tested_last() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_serialise_their_trace_in_every_released_mode() {
|
||||
use std::str::FromStr;
|
||||
use zen_engine::EvaluationTraceKind;
|
||||
let graph = table("first", "a", &["> 0"]);
|
||||
let content: DecisionContent = serde_json::from_value(graph).unwrap();
|
||||
let content = Arc::new(content);
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
for version in [EngineVersion::V1, EngineVersion::V2] {
|
||||
let decision = DecisionEngine::default()
|
||||
.with_version(version)
|
||||
.create_decision(content.clone())
|
||||
.unwrap();
|
||||
let options = EvaluationOptions {
|
||||
trace: zen_engine::trace::TraceFormat::Legacy,
|
||||
..Default::default()
|
||||
};
|
||||
let response = runtime
|
||||
.block_on(decision.evaluate_with_opts(Variable::from(json!({"a": 1})), options))
|
||||
.unwrap();
|
||||
let shown = |mode: &str| {
|
||||
let kind = EvaluationTraceKind::from_str(mode).unwrap();
|
||||
response
|
||||
.serialize_with_mode(serde_json::value::Serializer, kind)
|
||||
.unwrap()
|
||||
};
|
||||
let plain = shown("default");
|
||||
assert!(plain["trace"].is_object(), "{version:?}");
|
||||
assert_eq!(
|
||||
plain,
|
||||
serde_json::to_value(&response).unwrap(),
|
||||
"{version:?}"
|
||||
);
|
||||
assert!(shown("none")["trace"].is_null(), "{version:?}");
|
||||
let text: Value = serde_json::from_str(shown("string")["trace"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(text, plain["trace"], "{version:?}");
|
||||
let reference = shown("reference");
|
||||
assert!(reference["trace"].get("$refs").is_some(), "{version:?}");
|
||||
let restored =
|
||||
Variable::deserialize_ref(serde_json::from_value(reference["trace"].clone()).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(restored.to_value(), plain["trace"], "{version:?}");
|
||||
let both = Variable::deserialize_ref(
|
||||
serde_json::from_str(shown("referenceString")["trace"].as_str().unwrap()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(both.to_value(), plain["trace"], "{version:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user