diff --git a/.github/workflows/kotlin.yaml b/.github/workflows/kotlin.yaml new file mode 100644 index 00000000..1bb19853 --- /dev/null +++ b/.github/workflows/kotlin.yaml @@ -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 diff --git a/bindings/kotlin/.gitignore b/bindings/kotlin/.gitignore new file mode 100644 index 00000000..6eb8b6a7 --- /dev/null +++ b/bindings/kotlin/.gitignore @@ -0,0 +1,3 @@ +.idea +.gradle +build/ diff --git a/bindings/kotlin/Cargo.toml b/bindings/kotlin/Cargo.toml new file mode 100644 index 00000000..f2cbea1c --- /dev/null +++ b/bindings/kotlin/Cargo.toml @@ -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"] } \ No newline at end of file diff --git a/bindings/kotlin/build.gradle.kts b/bindings/kotlin/build.gradle.kts new file mode 100644 index 00000000..f48a6cd7 --- /dev/null +++ b/bindings/kotlin/build.gradle.kts @@ -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("mavenJava") { + from(components["java"]) + artifact(tasks["kotlinSourcesJar"]) + } + } + repositories { + mavenLocal() + } +} \ No newline at end of file diff --git a/bindings/kotlin/gradle/wrapper/gradle-wrapper.jar b/bindings/kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a4b76b95 Binary files /dev/null and b/bindings/kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/bindings/kotlin/gradle/wrapper/gradle-wrapper.properties b/bindings/kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9355b415 --- /dev/null +++ b/bindings/kotlin/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/bindings/kotlin/gradlew b/bindings/kotlin/gradlew new file mode 100755 index 00000000..f5feea6d --- /dev/null +++ b/bindings/kotlin/gradlew @@ -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" "$@" diff --git a/bindings/kotlin/gradlew.bat b/bindings/kotlin/gradlew.bat new file mode 100644 index 00000000..9b42019c --- /dev/null +++ b/bindings/kotlin/gradlew.bat @@ -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 diff --git a/bindings/kotlin/settings.gradle.kts b/bindings/kotlin/settings.gradle.kts new file mode 100644 index 00000000..1c7c7abe --- /dev/null +++ b/bindings/kotlin/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "zen_kotlin" \ No newline at end of file diff --git a/bindings/kotlin/src/config.rs b/bindings/kotlin/src/config.rs new file mode 100644 index 00000000..e8095001 --- /dev/null +++ b/bindings/kotlin/src/config.rs @@ -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 +} + +#[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) + } +} \ No newline at end of file diff --git a/bindings/kotlin/src/custom_node.rs b/bindings/kotlin/src/custom_node.rs new file mode 100644 index 00000000..78b732b9 --- /dev/null +++ b/bindings/kotlin/src/custom_node.rs @@ -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; +} + +pub struct NoopCustomNodeCallback; + +#[async_trait::async_trait] +impl ZenCustomNodeCallback for NoopCustomNodeCallback { + async fn handle(&self, key: ZenEngineHandlerRequest) -> Result { + Err(ZenError::Zero) + } +} + +pub struct ZenCustomNodeCallbackWrapper(pub Box); + +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 = result.trace_data.and_then(|trace| trace.try_into().ok()); + + Ok(NodeResponse { + output: Variable::from(output), + trace_data, + }) + } +} diff --git a/bindings/kotlin/src/decision.rs b/bindings/kotlin/src/decision.rs new file mode 100644 index 00000000..fb6f9ad5 --- /dev/null +++ b/bindings/kotlin/src/decision.rs @@ -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>, +} + +impl From> + for ZenDecision +{ + fn from( + value: Decision, + ) -> Self { + Self { + decision: Arc::new(value), + } + } +} + +#[uniffi::export(async_runtime = "tokio")] +impl ZenDecision { + pub async fn evaluate( + &self, + context: JsonBuffer, + options: Option, + ) -> Result { + 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())) + }) + } +} diff --git a/bindings/kotlin/src/engine.rs b/bindings/kotlin/src/engine.rs new file mode 100644 index 00000000..18a36c4d --- /dev/null +++ b/bindings/kotlin/src/engine.rs @@ -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>, +} + +#[derive(uniffi::Record)] +pub struct ZenEvaluateOptions { + pub max_depth: Option, + pub trace: Option, +} + +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>, + custom_node: Option>, + ) -> 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, + ) -> Result { + 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 { + 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 { + 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) + } +} diff --git a/bindings/kotlin/src/error.rs b/bindings/kotlin/src/error.rs new file mode 100644 index 00000000..8d19557d --- /dev/null +++ b/bindings/kotlin/src/error.rs @@ -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) + } +} diff --git a/bindings/kotlin/src/expression.rs b/bindings/kotlin/src/expression.rs new file mode 100644 index 00000000..b38f5cd2 --- /dev/null +++ b/bindings/kotlin/src/expression.rs @@ -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, +) -> Result { + 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 { + 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 { + 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, +) -> Result { + 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 { + 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 { + task::spawn_blocking(move || render_template_sync(template, context)) + .await + .map_err(|e| ZenError::ExecutionTaskSpawnError)? +} diff --git a/bindings/kotlin/src/lib.rs b/bindings/kotlin/src/lib.rs new file mode 100644 index 00000000..9eb2e646 --- /dev/null +++ b/bindings/kotlin/src/lib.rs @@ -0,0 +1,9 @@ +uniffi::setup_scaffolding!(); +mod config; +mod custom_node; +mod decision; +mod engine; +mod error; +mod expression; +mod loader; +mod types; diff --git a/bindings/kotlin/src/loader.rs b/bindings/kotlin/src/loader.rs new file mode 100644 index 00000000..f82c3975 --- /dev/null +++ b/bindings/kotlin/src/loader.rs @@ -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; +} + +pub struct NoopDecisionLoader; + +#[async_trait::async_trait] +impl ZenDecisionLoaderCallback for NoopDecisionLoader { + async fn load(&self, key: String) -> Result { + Err(ZenError::Zero) + } +} + +pub struct ZenDecisionLoaderCallbackWrapper(pub Box); + +impl DecisionLoader for ZenDecisionLoaderCallbackWrapper { + fn load<'a>(&'a self, key: &'a str) -> impl Future + '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)) + } + } +} diff --git a/bindings/kotlin/src/types.rs b/bindings/kotlin/src/types.rs new file mode 100644 index 00000000..9d6aacd5 --- /dev/null +++ b/bindings/kotlin/src/types.rs @@ -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); +uniffi::custom_newtype!(JsonBuffer, Vec); + +impl TryFrom for Value { + type Error = ZenError; + + fn try_from(value: JsonBuffer) -> Result { + serde_json::from_slice(&value.0).map_err(|_| ZenError::JsonDeserializationFailed) + } +} + +impl TryFrom for JsonBuffer { + type Error = ZenError; + + fn try_from(value: Value) -> Result { + 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, + pub trace_data: Option, + pub order: u32, +} + +impl From 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>, +} + +impl From 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, +} + +#[derive(uniffi::Record)] +pub struct DecisionNode { + pub id: String, + pub name: String, + pub kind: String, + pub config: JsonBuffer, +} + +impl From 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, +} diff --git a/bindings/kotlin/uniffi-bindgen.rs b/bindings/kotlin/uniffi-bindgen.rs new file mode 100644 index 00000000..d96eac70 --- /dev/null +++ b/bindings/kotlin/uniffi-bindgen.rs @@ -0,0 +1,3 @@ +fn main() { + uniffi::uniffi_bindgen_main() +} \ No newline at end of file diff --git a/bindings/kotlin/uniffi.toml b/bindings/kotlin/uniffi.toml new file mode 100644 index 00000000..92c060a0 --- /dev/null +++ b/bindings/kotlin/uniffi.toml @@ -0,0 +1,2 @@ +[bindings.kotlin] +package_name = "io.gorules.zen_engine" \ No newline at end of file