feat: add support for kotlin bindings

This commit is contained in:
Lars Werkman
2025-07-25 07:28:30 +02:00
committed by Stefan
parent 141e1810a3
commit 47ec992056
20 changed files with 1143 additions and 0 deletions
+139
View File
@@ -0,0 +1,139 @@
name: Kotlin
env:
WORKING_DIRECTORY: bindings/kotlin
on:
push:
branches:
- master
tags-ignore:
- '**'
paths:
- 'bindings/kotlin/**'
- 'core/**'
- 'test-data/**'
- '.github/workflows/kotlin.yaml'
pull_request:
paths:
- 'bindings/kotlin/**'
- 'core/**'
- 'test-data/**'
- '.github/workflows/kotlin.yaml'
jobs:
build:
if: "!contains(github.event.head_commit.message, 'skip ci')"
strategy:
fail-fast: true
matrix:
settings:
- host: windows-latest
target: 'x86_64-pc-windows-msvc'
extension: "dll"
lib_dir: TODO
- host: macos-13
target: 'x86_64-apple-darwin'
extension: "dylib"
lib_dir: TODO
- host: macos-14
target: 'aarch64-apple-darwin'
extension: "dylib"
lib_dir: 'darwin-aarch64'
- host: ubuntu-latest
target: 'x86_64-unknown-linux-gnu'
extension: "so"
lib_dir: TODO
- host: ubuntu-latest
target: 'aarch64-unknown-linux-gnu'
extension: ".so"
lib_dir: TODO
name: stable - ${{ matrix.settings.target }} - kotlin@17
runs-on: ${{ matrix.settings.host }}
defaults:
run:
working-directory: ${{ env.WORKING_DIRECTORY }}
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
target: ${{ matrix.settings.target }}
- name: Cache cargo registry
uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
.cargo-cache
key: ${{ matrix.settings.target }}-cargo-registry
- name: Build
shell: bash
run: cargo build --lib --release --target ${{ matrix.settings.target }}
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.settings.lib_dir }}
path: ./../target/release/libzen_kotlin.${{ matrix.settings.extension }}
release:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ env.WORKING_DIRECTORY }}
needs: [build]
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
target: ${{ matrix.settings.target }}
- name: Cache cargo registry
uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
.cargo-cache
key: ${{ matrix.settings.target }}-cargo-registry
- name: Validate Gradle wrapper jar
uses: gradle/wrapper-validation-action@v1
- name: Setup Gradle
uses: gradle/gradle-build-action@v2
- name: Download all artifacts
uses: actions/download-artifact@v3
with:
path: build/generated/main/resources
- name: Generate Kotlin sources
run: |
cargo run \
--bin uniffi-bindgen \
--features "uniffi/cli" \
-- generate \
--library build/generated/resources/libs/libzen_kotlin.dylib \
--language kotlin \
--out-dir build/generated/main/kotlin
# TODO
# - name: Setup Maven Repository credentials
# run:
- name: Publish Maven Artifact
run: ./gradlew publish
+3
View File
@@ -0,0 +1,3 @@
.idea
.gradle
build/
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "zen-kotlin"
version = "0.34.1"
edition = "2021"
license = "MIT"
publish = false
[lib]
crate-type = ["cdylib"]
[[bin]]
name = "uniffi-bindgen"
path = "uniffi-bindgen.rs"
[dependencies]
uniffi = { version = "0.28.3", features = ["tokio"] }
serde_json = { workspace = true }
zen-engine = { path = "../../core/engine" }
zen-expression = { path = "../../core/expression" }
zen-tmpl = { path = "../../core/template" }
serde = { workspace = true, features = ["derive"] }
async-trait = "0.1.83"
tokio = "1.42.0"
[build-dependencies]
uniffi = { version = "0.28.3", features = ["build"] }
+39
View File
@@ -0,0 +1,39 @@
plugins {
kotlin("jvm") version "2.1.0"
id("maven-publish")
}
group = "io.gorules"
version = "0.36.1"
dependencies {
implementation("net.java.dev.jna:jna:5.15.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
}
repositories {
mavenCentral()
}
sourceSets {
main {
kotlin {
srcDirs("build/generated/main/kotlin")
}
resources {
srcDirs("build/generated/main/resources")
}
}
}
publishing {
publications {
create<MavenPublication>("mavenJava") {
from(components["java"])
artifact(tasks["kotlinSourcesJar"])
}
}
repositories {
mavenLocal()
}
}
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1
View File
@@ -0,0 +1 @@
rootProject.name = "zen_kotlin"
+14
View File
@@ -0,0 +1,14 @@
use std::sync::atomic::Ordering;
use zen_engine::ZEN_CONFIG;
#[derive(uniffi::Record)]
pub struct ZenConfig {
pub nodes_in_context: Option<bool>
}
#[uniffi::export]
pub fn override_config(config: ZenConfig) {
if let Some(val) = config.nodes_in_context {
ZEN_CONFIG.nodes_in_context.store(val, Ordering::Relaxed)
}
}
+58
View File
@@ -0,0 +1,58 @@
use crate::error::ZenError;
use crate::types::{DecisionNode, JsonBuffer, ZenEngineHandlerRequest, ZenEngineHandlerResponse};
use serde_json::Value;
use uniffi::deps::anyhow::anyhow;
use zen_engine::handler::custom_node_adapter::{CustomNodeAdapter, CustomNodeRequest};
use zen_engine::handler::node::{NodeResponse, NodeResult};
use zen_expression::Variable;
use crate::loader::ZenDecisionLoaderCallback;
#[uniffi::export(callback_interface)]
#[async_trait::async_trait]
pub trait ZenCustomNodeCallback: Send + Sync {
async fn handle(
&self,
key: ZenEngineHandlerRequest,
) -> Result<ZenEngineHandlerResponse, ZenError>;
}
pub struct NoopCustomNodeCallback;
#[async_trait::async_trait]
impl ZenCustomNodeCallback for NoopCustomNodeCallback {
async fn handle(&self, key: ZenEngineHandlerRequest) -> Result<ZenEngineHandlerResponse, ZenError> {
Err(ZenError::Zero)
}
}
pub struct ZenCustomNodeCallbackWrapper(pub Box<dyn ZenCustomNodeCallback>);
impl CustomNodeAdapter for ZenCustomNodeCallbackWrapper {
async fn handle(&self, request: CustomNodeRequest) -> NodeResult {
let input = request
.input
.to_value()
.try_into()
.map_err(|err: ZenError| anyhow!(err))?;
let node = DecisionNode::from(request.node);
let result = self
.0
.handle(ZenEngineHandlerRequest { input, node })
.await
.map_err(|err| anyhow!(err.details()))?;
let output: Value = result
.output
.try_into()
.map_err(|err: ZenError| anyhow!(err))?;
let trace_data: Option<Value> = result.trace_data.and_then(|trace| trace.try_into().ok());
Ok(NodeResponse {
output: Variable::from(output),
trace_data,
})
}
}
+72
View File
@@ -0,0 +1,72 @@
use crate::custom_node::ZenCustomNodeCallbackWrapper;
use crate::engine::ZenEvaluateOptions;
use crate::error::ZenError;
use crate::loader::ZenDecisionLoaderCallbackWrapper;
use crate::types::{JsonBuffer, ZenEngineResponse};
use serde_json::Value;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::task;
use zen_engine::{Decision, DecisionGraphValidationError, EvaluationOptions};
#[derive(uniffi::Object)]
pub struct ZenDecision {
decision: Arc<Decision<ZenDecisionLoaderCallbackWrapper, ZenCustomNodeCallbackWrapper>>,
}
impl From<Decision<ZenDecisionLoaderCallbackWrapper, ZenCustomNodeCallbackWrapper>>
for ZenDecision
{
fn from(
value: Decision<ZenDecisionLoaderCallbackWrapper, ZenCustomNodeCallbackWrapper>,
) -> Self {
Self {
decision: Arc::new(value),
}
}
}
#[uniffi::export(async_runtime = "tokio")]
impl ZenDecision {
pub async fn evaluate(
&self,
context: JsonBuffer,
options: Option<ZenEvaluateOptions>,
) -> Result<ZenEngineResponse, ZenError> {
let options = options.unwrap_or_default();
let context: Value = context.try_into()?;
let decision = self.decision.clone();
let evaluation_options = EvaluationOptions {
max_depth: options.max_depth,
trace: options.trace,
};
// Use spawn_blocking to run the non-Send code synchronously
let response = task::spawn_blocking(move || {
// The blocking code that uses non-Send types
Handle::current().block_on(async move {
decision
.evaluate_with_opts(context.into(), evaluation_options)
.await
.map(|response| ZenEngineResponse::from(response))
.map_err(|err| {
ZenError::EvaluationError(
serde_json::to_string(&err.as_ref())
.unwrap_or_else(|_| err.to_string()),
)
})
})
})
.await
.map_err(|e| ZenError::EvaluationError(format!("Task failed: {:?}", e)))??;
Ok(response)
}
pub fn validate(&self) -> Result<(), ZenError> {
self.decision.validate().map_err(|e| {
ZenError::ValidationError(serde_json::to_string(&e).unwrap_or_else(|_| e.to_string()))
})
}
}
+132
View File
@@ -0,0 +1,132 @@
use crate::custom_node::{NoopCustomNodeCallback, ZenCustomNodeCallback, ZenCustomNodeCallbackWrapper};
use crate::decision::ZenDecision;
use crate::error::ZenError;
use crate::loader::{
NoopDecisionLoader, ZenDecisionLoaderCallback, ZenDecisionLoaderCallbackWrapper,
};
use crate::types::{
JsonBuffer, ZenEngineHandlerRequest, ZenEngineHandlerResponse, ZenEngineResponse,
};
use async_trait::async_trait;
use serde_json::Value;
use std::future::Future;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::task;
use uniffi::deps::anyhow::anyhow;
use zen_engine::handler::custom_node_adapter::{
CustomNodeAdapter, CustomNodeRequest, NoopCustomNode,
};
use zen_engine::handler::node::NodeResult;
use zen_engine::loader::{DecisionLoader, NoopLoader};
use zen_engine::model::DecisionContent;
use zen_engine::{DecisionEngine, EvaluationOptions};
use zen_expression::parser::Node;
#[derive(uniffi::Object)]
pub(crate) struct ZenEngine {
engine: Arc<DecisionEngine<ZenDecisionLoaderCallbackWrapper, ZenCustomNodeCallbackWrapper>>,
}
#[derive(uniffi::Record)]
pub struct ZenEvaluateOptions {
pub max_depth: Option<u8>,
pub trace: Option<bool>,
}
impl Default for ZenEvaluateOptions {
fn default() -> Self {
Self {
max_depth: Some(5),
trace: Some(false),
}
}
}
#[uniffi::export(async_runtime = "tokio")]
impl ZenEngine {
#[uniffi::constructor]
pub fn new(
loader: Option<Box<dyn ZenDecisionLoaderCallback>>,
custom_node: Option<Box<dyn ZenCustomNodeCallback>>,
) -> Self {
Self {
engine: Arc::new(DecisionEngine::new(
Arc::new(ZenDecisionLoaderCallbackWrapper(
loader.unwrap_or_else(|| Box::new(NoopDecisionLoader)),
)),
Arc::new(ZenCustomNodeCallbackWrapper(
custom_node.unwrap_or_else(|| Box::new(NoopCustomNodeCallback))
)),
)),
}
}
pub async fn evaluate(
&self,
key: String,
context: JsonBuffer,
options: Option<ZenEvaluateOptions>,
) -> Result<ZenEngineResponse, ZenError> {
let options = options.unwrap_or_default();
let context: Value = context.try_into()?;
let engine = self.engine.clone();
let evaluation_options = EvaluationOptions {
max_depth: options.max_depth,
trace: options.trace,
};
// Use spawn_blocking to run the non-Send code synchronously
let response = task::spawn_blocking(move || {
// The blocking code that uses non-Send types
Handle::current().block_on(async move {
engine
.evaluate_with_opts(key, context.into(), evaluation_options)
.await
.map(|response| ZenEngineResponse::from(response))
.map_err(|err| {
ZenError::EvaluationError(
serde_json::to_string(&err.as_ref())
.unwrap_or_else(|_| err.to_string()),
)
})
})
})
.await
.map_err(|e| ZenError::EvaluationError(format!("Task failed: {:?}", e)))??;
Ok(response)
}
pub fn create_decision(&self, content: JsonBuffer) -> Result<ZenDecision, ZenError> {
let decision = self.engine.create_decision(Arc::new(
serde_json::from_slice(&content.0).map_err(|_| ZenError::JsonDeserializationFailed)?,
));
Ok(ZenDecision::from(decision))
}
pub async fn get_decision(&self, key: String) -> Result<ZenDecision, ZenError> {
let engine = self.engine.clone();
// Use spawn_blocking to run the non-Send code synchronously
let decision = task::spawn_blocking(move || {
// The blocking code that uses non-Send types
Handle::current().block_on(async move {
engine
.get_decision(&key)
.await
.map_err(|e| ZenError::LoaderInternalError {
key,
details: e.to_string(),
})
.map(ZenDecision::from)
})
})
.await
.map_err(|e| ZenError::EvaluationError(format!("Task failed: {:?}", e)))??;
Ok(decision)
}
}
+54
View File
@@ -0,0 +1,54 @@
use serde_json::json;
use std::fmt::Formatter;
#[allow(dead_code)]
#[derive(Debug, uniffi::Error)]
pub enum ZenError {
Zero,
InvalidArgument,
StringNullError,
StringUtf8Error,
JsonSerializationFailed,
JsonDeserializationFailed,
ExecutionTaskSpawnError,
IsolateError(String),
EvaluationError(String),
ValidationError(String),
LoaderKeyNotFound { key: String },
LoaderInternalError { key: String, details: String },
TemplateEngineError { template: String, details: String },
}
impl ZenError {
pub fn details(&self) -> String {
match &self {
ZenError::IsolateError(error) => error.to_string(),
ZenError::EvaluationError(error) => error.to_string(),
ZenError::ValidationError(error) => error.to_string(),
ZenError::LoaderKeyNotFound { key } => json!({ "key": key }).to_string(),
ZenError::LoaderInternalError { key, details } => {
json!({ "key": key, "details": details }).to_string()
}
ZenError::TemplateEngineError { template, details } => {
json!({ "template": template, "details": details }).to_string()
}
ZenError::Zero => String::from("Zero"),
ZenError::InvalidArgument => String::from("InvalidArgument"),
ZenError::StringNullError => String::from("StringNullError"),
ZenError::StringUtf8Error => String::from("StringUtf8Error"),
ZenError::JsonSerializationFailed => String::from("JsonSerializationFailed"),
ZenError::JsonDeserializationFailed => String::from("JsonDeserializationFailed"),
ZenError::ExecutionTaskSpawnError => String::from("ExecutionTaskSpawnError"),
}
}
}
impl std::fmt::Display for ZenError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.details().fmt(f)
}
}
+92
View File
@@ -0,0 +1,92 @@
use crate::error::ZenError;
use crate::types::JsonBuffer;
use serde_json::Value;
use tokio::task;
use uniffi::deps::anyhow::anyhow;
#[uniffi::export()]
pub fn evaluate_expression_sync(
expression: String,
context: Option<JsonBuffer>,
) -> Result<JsonBuffer, ZenError> {
let ctx: Value = context
.and_then(|v| v.try_into().ok())
.unwrap_or(Value::Null);
Ok(
zen_expression::evaluate_expression(expression.as_str(), ctx.into())
.map_err(|e| {
ZenError::EvaluationError(
serde_json::to_string(&e).unwrap_or_else(|_| e.to_string()),
)
})?
.to_value()
.try_into()?,
)
}
#[allow(dead_code)]
#[uniffi::export()]
pub fn evaluate_unary_expression_sync(
expression: String,
context: JsonBuffer,
) -> Result<bool, ZenError> {
let ctx: Value = context.try_into()?;
Ok(
zen_expression::evaluate_unary_expression(expression.as_str(), ctx.into()).map_err(
|e| {
ZenError::EvaluationError(
serde_json::to_string(&e).unwrap_or_else(|_| e.to_string()),
)
},
)?,
)
}
#[allow(dead_code)]
#[uniffi::export()]
pub fn render_template_sync(template: String, context: JsonBuffer) -> Result<JsonBuffer, ZenError> {
let ctx: Value = context.try_into()?;
Ok(zen_tmpl::render(template.as_str(), ctx.into())
.map_err(|e| ZenError::TemplateEngineError {
template,
details: serde_json::to_string(&e).unwrap_or_else(|_| e.to_string()),
})?
.to_value()
.try_into()?)
}
#[allow(dead_code)]
#[uniffi::export(async_runtime = "tokio")]
pub async fn evaluate_expression(
expression: String,
context: Option<JsonBuffer>,
) -> Result<JsonBuffer, ZenError> {
task::spawn_blocking(move || evaluate_expression_sync(expression, context))
.await
.map_err(|e| ZenError::ExecutionTaskSpawnError)?
}
#[allow(dead_code)]
#[uniffi::export(async_runtime = "tokio")]
pub async fn evaluate_unary_expression(
expression: String,
context: JsonBuffer,
) -> Result<bool, ZenError> {
task::spawn_blocking(move || evaluate_unary_expression_sync(expression, context))
.await
.map_err(|e| ZenError::ExecutionTaskSpawnError)?
}
#[allow(dead_code)]
#[uniffi::export(async_runtime = "tokio")]
pub async fn render_template(
template: String,
context: JsonBuffer,
) -> Result<JsonBuffer, ZenError> {
task::spawn_blocking(move || render_template_sync(template, context))
.await
.map_err(|e| ZenError::ExecutionTaskSpawnError)?
}
+9
View File
@@ -0,0 +1,9 @@
uniffi::setup_scaffolding!();
mod config;
mod custom_node;
mod decision;
mod engine;
mod error;
mod expression;
mod loader;
mod types;
+43
View File
@@ -0,0 +1,43 @@
use crate::error::ZenError;
use std::future::Future;
use std::sync::Arc;
use uniffi::deps::anyhow::anyhow;
use zen_engine::loader::{DecisionLoader, LoaderError, LoaderResponse};
use zen_engine::model::DecisionContent;
use crate::types::JsonBuffer;
#[uniffi::export(callback_interface)]
#[async_trait::async_trait]
pub trait ZenDecisionLoaderCallback: Send + Sync {
async fn load(&self, key: String) -> Result<JsonBuffer, ZenError>;
}
pub struct NoopDecisionLoader;
#[async_trait::async_trait]
impl ZenDecisionLoaderCallback for NoopDecisionLoader {
async fn load(&self, key: String) -> Result<JsonBuffer, ZenError> {
Err(ZenError::Zero)
}
}
pub struct ZenDecisionLoaderCallbackWrapper(pub Box<dyn ZenDecisionLoaderCallback>);
impl DecisionLoader for ZenDecisionLoaderCallbackWrapper {
fn load<'a>(&'a self, key: &'a str) -> impl Future<Output = LoaderResponse> + 'a {
async move {
let maybe_raw = self.0.load(key.into()).await;
if maybe_raw.is_err() {
return Err(LoaderError::NotFound(key.to_string()).into());
}
let decision_content: DecisionContent = serde_json::from_slice(&maybe_raw.unwrap().0)
.map_err(|e| LoaderError::Internal {
key: key.to_string(),
source: anyhow!(e),
})?;
Ok(Arc::new(decision_content))
}
}
}
+103
View File
@@ -0,0 +1,103 @@
use crate::error::ZenError;
use serde_json::Value;
use std::collections::HashMap;
use zen_engine::handler::custom_node_adapter::CustomDecisionNode;
use zen_engine::{DecisionGraphResponse, DecisionGraphTrace};
pub struct JsonBuffer(pub Vec<u8>);
uniffi::custom_newtype!(JsonBuffer, Vec<u8>);
impl TryFrom<JsonBuffer> for Value {
type Error = ZenError;
fn try_from(value: JsonBuffer) -> Result<Self, Self::Error> {
serde_json::from_slice(&value.0).map_err(|_| ZenError::JsonDeserializationFailed)
}
}
impl TryFrom<Value> for JsonBuffer {
type Error = ZenError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
serde_json::to_vec(&value)
.map(|v| JsonBuffer(v))
.map_err(|_| ZenError::JsonSerializationFailed)
}
}
#[derive(uniffi::Record)]
pub struct ZenEngineTrace {
pub id: String,
pub name: String,
pub input: JsonBuffer,
pub output: JsonBuffer,
pub performance: Option<String>,
pub trace_data: Option<JsonBuffer>,
pub order: u32,
}
impl From<DecisionGraphTrace> for ZenEngineTrace {
fn from(value: DecisionGraphTrace) -> Self {
Self {
id: value.id,
name: value.name,
input: value.input.to_value().try_into().unwrap(),
output: value.output.to_value().try_into().unwrap(),
performance: value.performance,
trace_data: value.trace_data.map(|data| data.try_into().unwrap()),
order: value.order,
}
}
}
#[derive(uniffi::Record)]
pub struct ZenEngineResponse {
pub performance: String,
pub result: JsonBuffer,
pub trace: Option<HashMap<String, ZenEngineTrace>>,
}
impl From<DecisionGraphResponse> for ZenEngineResponse {
fn from(value: DecisionGraphResponse) -> Self {
Self {
performance: value.performance,
result: value.result.to_value().try_into().unwrap(),
trace: value.trace.map(|opt| {
opt.into_iter()
.map(|(key, value)| (key, ZenEngineTrace::from(value)))
.collect()
}),
}
}
}
#[derive(uniffi::Record)]
pub struct ZenEngineHandlerResponse {
pub output: JsonBuffer,
pub trace_data: Option<JsonBuffer>,
}
#[derive(uniffi::Record)]
pub struct DecisionNode {
pub id: String,
pub name: String,
pub kind: String,
pub config: JsonBuffer,
}
impl From<CustomDecisionNode> for DecisionNode {
fn from(value: CustomDecisionNode) -> Self {
Self {
id: value.id,
name: value.name,
kind: value.kind,
config: JsonBuffer(serde_json::to_vec(&value.config).unwrap()),
}
}
}
#[derive(uniffi::Record)]
pub struct ZenEngineHandlerRequest {
pub input: JsonBuffer,
pub node: DecisionNode,
}
+3
View File
@@ -0,0 +1,3 @@
fn main() {
uniffi::uniffi_bindgen_main()
}
+2
View File
@@ -0,0 +1,2 @@
[bindings.kotlin]
package_name = "io.gorules.zen_engine"