diff --git a/.github/workflows/uniffi-version-bump.yaml b/.github/workflows/uniffi-version-bump.yaml new file mode 100644 index 00000000..ef62d63e --- /dev/null +++ b/.github/workflows/uniffi-version-bump.yaml @@ -0,0 +1,56 @@ +name: "Release: Uniffi" + +env: + WORKING_DIRECTORY: bindings/uniffi + +on: + workflow_dispatch: + inputs: + version: + description: 'Version' + required: true + default: 'patch' + type: choice + options: + - patch + - minor + - major + +permissions: + contents: write + +jobs: + publish: + name: Version + runs-on: ubuntu-latest + defaults: + run: + working-directory: ${{ env.WORKING_DIRECTORY }} + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Set Git author + run: | + git config user.name "Bot" + git config user.email "bot@gorules.io" + + - uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: 'Install dependencies' + run: pip install --upgrade bump2version + + - name: Bumpversion + run: bumpversion ${{ github.event.inputs.version }} --allow-dirty --tag-name "uniffi-v{new_version}" + env: + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Push changes + uses: ad-m/github-push-action@v0.6.0 + with: + github_token: ${{ secrets.PAT}} diff --git a/.github/workflows/uniffi.yaml b/.github/workflows/uniffi.yaml new file mode 100644 index 00000000..9e994745 --- /dev/null +++ b/.github/workflows/uniffi.yaml @@ -0,0 +1,137 @@ +name: UniFFI +env: + UNIFFI_DIRECTORY: bindings/uniffi + +on: + push: + branches: + - master + tags-ignore: + - '**' + paths: + - '../../bindings/uniffi/**' + - 'core/**' + - 'test-data/**' + - '.github/workflows/uniffi.yaml' + pull_request: + paths: + - '../../bindings/uniffi/**' + - 'core/**' + - 'test-data/**' + - '.github/workflows/uniffi.yaml' + +jobs: + build: + if: "!contains(github.event.head_commit.message, 'skip ci')" + env: + OUTPUT_NAME: zen_uniffi + + strategy: + fail-fast: true + matrix: + settings: + - host: windows-latest + target: 'x86_64-pc-windows-msvc' + output: '{0}.dll' + lib_dir: 'win32-x86-64' + - host: macos-latest + target: 'x86_64-apple-darwin' + output: 'lib{0}.dylib' + lib_dir: 'darwin-x86-64' + - host: macos-latest + target: 'aarch64-apple-darwin' + output: 'lib{0}.dylib' + lib_dir: 'darwin-aarch64' + - host: ubuntu-latest + target: 'x86_64-unknown-linux-gnu' + output: 'lib{0}.so' + lib_dir: 'linux-x86-64' + - host: ubuntu-latest + target: 'aarch64-unknown-linux-gnu' + output: 'lib{0}.so' + lib_dir: 'linux-aarch64' + + name: UniFFI - ${{ matrix.settings.target }} + runs-on: ${{ matrix.settings.host }} + + steps: + - uses: actions/checkout@v3 + + - name: Setup Rust Toolchain + uses: dtolnay/rust-toolchain@stable + with: + target: ${{ matrix.settings.target }} + + - name: Build + uses: houseabsolute/actions-rust-cross@v1 + with: + working-directory: ${{ env.UNIFFI_DIRECTORY }} + target: ${{ matrix.settings.target }} + args: '--lib --release' + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.settings.lib_dir }} + path: target/${{ matrix.settings.target }}/release/${{ format(matrix.settings.output, env.OUTPUT_NAME) }} + if-no-files-found: error + + release-java-kotlin: + runs-on: ubuntu-latest + needs: [ build ] + if: "startsWith(github.event.head_commit.message, 'chore(release): publish uniffi')" + defaults: + run: + working-directory: ${{ env.UNIFFI_DIRECTORY }} + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Setup Rust Toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Validate Gradle wrapper jar + uses: gradle/actions/wrapper-validation@v3 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Download all artifacts + uses: actions/download-artifact@v4 + with: + path: build/generated/resources + + - name: Move artifacts + run: mv ../../build ./ + + - name: Generate Kotlin sources + run: | + cargo run --bin uniffi-bindgen -- generate \ + --library build/generated/resources/darwin-x86-64/libzen_uniffi.dylib \ + --language kotlin \ + --out-dir build/generated/kotlin + + - name: Install uniffi-bindgen-java + run: cargo install uniffi-bindgen-java + + - name: Generate Java sources + run: | + uniffi-bindgen-java generate \ + --library build/generated/resources/darwin-x86-64/libzen_uniffi.dylib \ + --out-dir build/generated/java + + - name: Print directory tree + run: tree build + + - name: Publish Maven Artifact + env: + SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} + GPG_SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }} + GPG_SIGNING_PASSPHRASE: ${{ secrets.GPG_SIGNING_PASSPHRASE }} + run: ./gradlew publishAllPublicationsToCentralPortal diff --git a/bindings/uniffi/.bumpversion.cfg b/bindings/uniffi/.bumpversion.cfg new file mode 100644 index 00000000..2eb98ac5 --- /dev/null +++ b/bindings/uniffi/.bumpversion.cfg @@ -0,0 +1,7 @@ +[bumpversion] +current_version = 0.1.10 +commit = True +tag = True +message = chore(release): publish uniffi + +[bumpversion:file:Cargo.toml] \ No newline at end of file diff --git a/bindings/uniffi/.gitignore b/bindings/uniffi/.gitignore new file mode 100644 index 00000000..6eb8b6a7 --- /dev/null +++ b/bindings/uniffi/.gitignore @@ -0,0 +1,3 @@ +.idea +.gradle +build/ diff --git a/bindings/uniffi/Cargo.toml b/bindings/uniffi/Cargo.toml new file mode 100644 index 00000000..b45005d0 --- /dev/null +++ b/bindings/uniffi/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "zen-uniffi" +version = "0.1.10" +edition = "2024" +license = "MIT" +publish = false + +[lib] +crate-type = ["cdylib"] + +[[bin]] +name = "uniffi-bindgen" +path = "uniffi-bindgen.rs" + +[dependencies] +uniffi = { version = "0.29", features = ["tokio", "cli"] } +serde_json = { workspace = true } +zen-engine = { path = "../../core/engine" } +zen-expression = { path = "../../core/expression" } +serde = { workspace = true, features = ["derive"] } +async-trait = "0.1" +tokio = "1.46" + +[build-dependencies] +uniffi = { version = "0.29", features = ["build"] } \ No newline at end of file diff --git a/bindings/uniffi/Makefile b/bindings/uniffi/Makefile new file mode 100644 index 00000000..b44dbe8f --- /dev/null +++ b/bindings/uniffi/Makefile @@ -0,0 +1,25 @@ +# Just for local testing, at the moment it relies on .dylib (Mac), feel free to change below +build: + cargo build --lib --release + @mkdir -p build/generated/resources + cp -f ../../target/release/libzen_uniffi.dylib build/generated/resources/libzen_uniffi.dylib + +generate-java: + uniffi-bindgen-java generate \ + --library build/generated/resources/libzen_uniffi.dylib \ + --out-dir build/generated/java + +generate-kotlin: + cargo run --bin uniffi-bindgen generate \ + --library build/generated/resources/libzen_uniffi.dylib \ + --language kotlin \ + --out-dir build/generated/kotlin + +generate-csharp: + uniffi-bindgen-cs \ + --library build/generated/resources/libzen_uniffi.dylib \ + --out-dir build/generated/csharp + +all: build generate-java generate-kotlin generate-csharp + +.PHONY: all build generate-java generate-kotlin generate-csharp \ No newline at end of file diff --git a/bindings/uniffi/build.gradle.kts b/bindings/uniffi/build.gradle.kts new file mode 100644 index 00000000..45de6658 --- /dev/null +++ b/bindings/uniffi/build.gradle.kts @@ -0,0 +1,234 @@ +import org.jetbrains.dokka.gradle.DokkaTask +import org.tomlj.Toml +import java.util.* + +group = "io.gorules" +version = loadCargoVersion() + +buildscript { + dependencies { + classpath("org.tomlj:tomlj:1.1.1") + } +} + +plugins { + kotlin("jvm") version "2.1.0" + id("maven-publish") + id("signing") + id("org.jetbrains.dokka") version "2.0.0" + id("org.jetbrains.dokka-javadoc") version "2.0.0" + id("com.gradleup.nmcp") version "0.0.9" +} + +repositories { + mavenCentral() +} + +sourceSets { + val java by creating { + java { + srcDirs("lib/java", "build/generated/java") + } + resources { + srcDirs("build/generated/resources") + } + + compileClasspath += sourceSets["main"].compileClasspath + runtimeClasspath += sourceSets["main"].runtimeClasspath + } + + val kotlin by creating { + kotlin { + srcDirs("lib/kotlin", "build/generated/kotlin") + } + resources { + srcDirs("build/generated/resources") + } + + compileClasspath += sourceSets["main"].compileClasspath + runtimeClasspath += sourceSets["main"].runtimeClasspath + } +} + + +dependencies { + implementation("net.java.dev.jna:jna:5.17.0") + "kotlinImplementation"("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") +} + + +tasks { + val generateJavaJar by creating(Jar::class) { + archiveBaseName.set("zen_engine") + from(sourceSets["java"].output) + dependsOn(sourceSets["java"].classesTaskName) + } + + val generateJavaSourcesJar by creating(Jar::class) { + archiveBaseName.set("zen_engine") + archiveClassifier.set("sources") + from(sourceSets["java"].allJava) + } + + val generateKotlinJar by creating(Jar::class) { + archiveBaseName.set("zen_engine_kotlin") + from(sourceSets["kotlin"].output) + dependsOn(sourceSets["kotlin"].classesTaskName) + } + + val generateKotlinSourcesJar by creating(Jar::class) { + archiveBaseName.set("zen_engine_kotlin") + archiveClassifier.set("sources") + from(sourceSets["kotlin"].kotlin) + } + + val dokkaJavadocJava by creating(DokkaTask::class) { + outputDirectory.set(layout.buildDirectory.dir("dokka/java")) + dokkaSourceSets { named("java") } + + } + + val dokkaJavadocKotlin by creating(DokkaTask::class) { + outputDirectory.set(layout.buildDirectory.dir("dokka/kotlin")) + dokkaSourceSets { named("kotlin") } + } + + val javadocJarJava by creating(Jar::class) { + dependsOn(dokkaGeneratePublicationJavadoc) + archiveBaseName.set("zen_engine") + archiveClassifier.set("javadoc") + + from(dokkaGeneratePublicationJavadoc.get()) + } + + val javadocJarKotlin by creating(Jar::class) { + dependsOn(dokkaGeneratePublicationJavadoc) + archiveBaseName.set("zen_engine_kotlin") + archiveClassifier.set("javadoc") + + from(dokkaGeneratePublicationJavadoc.get()) + } +} + +publishing { + publications { + create("mavenJava") { + groupId = "io.gorules" + artifactId = "zen-engine" + artifact(tasks["generateJavaJar"]) + artifact(tasks["generateJavaSourcesJar"]) + artifact(tasks["javadocJarJava"]) + + configurePom { + dependency("net.java.dev.jna:jna:5.17.0") + } + } + + create("mavenKotlin") { + groupId = "io.gorules" + artifactId = "zen-engine-kotlin" + artifact(tasks["generateKotlinJar"]) + artifact(tasks["generateKotlinSourcesJar"]) + artifact(tasks["javadocJarKotlin"]) + + configurePom { + dependency("net.java.dev.jna:jna:5.17.0") + } + } + } + repositories { + mavenLocal() + } +} + +signing { + val signingKeyBase64 = providers.environmentVariable("GPG_SIGNING_KEY") + val signingPassphrase = providers.environmentVariable("GPG_SIGNING_PASSPHRASE") + + if (signingKeyBase64.isPresent and signingPassphrase.isPresent) { + val signingKey = Base64.getDecoder().decode(signingKeyBase64.get()).toString(Charsets.UTF_8) + + useInMemoryPgpKeys(signingKey, signingPassphrase.get()) + sign(publishing.publications["mavenJava"], publishing.publications["mavenKotlin"]) + } +} + +nmcp { + publishAllPublications { + publicationType = "USER_MANAGED" + + val remoteUsername = providers.environmentVariable("SONATYPE_USERNAME") + val remotePassword = providers.environmentVariable("SONATYPE_PASSWORD") + + if (remoteUsername.isPresent && remotePassword.isPresent) { + username.set(remoteUsername.get()) + password.set(remotePassword.get()) + } + } +} + +fun loadCargoVersion(): String { + val cargoFile = file("${projectDir}/Cargo.toml") + val result = Toml.parse(cargoFile.toPath()) + return result.getTable("package")?.getString("version") + ?: throw GradleException("Version not found in Cargo.toml") +} + +fun MavenPublication.configurePom(dependencyConfig: PomDependencyBuilder.() -> Unit) { + val depBuilder = PomDependencyBuilder() + depBuilder.dependencyConfig() + + pom { + name = "GoRules ZEN Engine" + description = "GoRules ZEN Engine is a cross-platform, Open-Source Business Rules Engine (BRE)" + url = "https://gorules.io" + + licenses { + license { + name = "MIT License" + url = "https://github.com/gorules/zen/blob/master/LICENSE" + } + } + + developers { + developer { + id = "gorules" + name = "GoRules Team" + email = "hi@gorules.io" + } + organization { + name = "GoRules" + url = "https://gorules.io" + } + } + + scm { + url = "https://github.com/gorules/zen" + } + + withXml { + val dependenciesNode = asNode().appendNode("dependencies") + depBuilder.addToXml(dependenciesNode) + } + } +} + +class PomDependencyBuilder { + private val dependencies = mutableListOf>() + + fun dependency(notation: String) { + val parts = notation.split(":") + require(parts.size == 3) { "Dependency notation must be 'group:artifact:version'" } + dependencies.add(Triple(parts[0], parts[1], parts[2])) + } + + fun addToXml(dependenciesNode: groovy.util.Node) { + dependencies.forEach { (groupId, artifactId, version) -> + val dependencyNode = dependenciesNode.appendNode("dependency") + dependencyNode.appendNode("groupId", groupId) + dependencyNode.appendNode("artifactId", artifactId) + dependencyNode.appendNode("version", version) + dependencyNode.appendNode("scope", "runtime") + } + } +} \ No newline at end of file diff --git a/bindings/uniffi/gradle.properties b/bindings/uniffi/gradle.properties new file mode 100644 index 00000000..66c172fb --- /dev/null +++ b/bindings/uniffi/gradle.properties @@ -0,0 +1,2 @@ +org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled +org.jetbrains.dokka.experimental.gradle.pluginMode.noWarn=true \ No newline at end of file diff --git a/bindings/uniffi/gradle/wrapper/gradle-wrapper.jar b/bindings/uniffi/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a4b76b95 Binary files /dev/null and b/bindings/uniffi/gradle/wrapper/gradle-wrapper.jar differ diff --git a/bindings/uniffi/gradle/wrapper/gradle-wrapper.properties b/bindings/uniffi/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9355b415 --- /dev/null +++ b/bindings/uniffi/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/uniffi/gradlew b/bindings/uniffi/gradlew new file mode 100755 index 00000000..f5feea6d --- /dev/null +++ b/bindings/uniffi/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/uniffi/gradlew.bat b/bindings/uniffi/gradlew.bat new file mode 100644 index 00000000..9b42019c --- /dev/null +++ b/bindings/uniffi/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/uniffi/lib/java/io/gorules/zen_engine/JsonBuffer.java b/bindings/uniffi/lib/java/io/gorules/zen_engine/JsonBuffer.java new file mode 100644 index 00000000..c4570c72 --- /dev/null +++ b/bindings/uniffi/lib/java/io/gorules/zen_engine/JsonBuffer.java @@ -0,0 +1,17 @@ +package io.gorules.zen_engine; + +import org.jetbrains.annotations.NotNull; + +import java.nio.charset.StandardCharsets; + +public record JsonBuffer(byte[] value) { + public JsonBuffer(String value) { + this(value.getBytes(StandardCharsets.UTF_8)); + } + + @NotNull + @Override + public String toString() { + return new String(value, StandardCharsets.UTF_8); + } +} \ No newline at end of file diff --git a/bindings/uniffi/lib/kotlin/io/gorules/zen_engine/kotlin/JsonBuffer.kt b/bindings/uniffi/lib/kotlin/io/gorules/zen_engine/kotlin/JsonBuffer.kt new file mode 100644 index 00000000..2c2fa3e9 --- /dev/null +++ b/bindings/uniffi/lib/kotlin/io/gorules/zen_engine/kotlin/JsonBuffer.kt @@ -0,0 +1,9 @@ +package io.gorules.zen_engine.kotlin + +@JvmInline +value class JsonBuffer(val value: ByteArray) { + constructor(json: String) : this(json.toByteArray(Charsets.UTF_8)) + + override fun toString(): String = value.toString(Charsets.UTF_8) + fun toByteArray(): ByteArray = value +} \ No newline at end of file diff --git a/bindings/uniffi/settings.gradle.kts b/bindings/uniffi/settings.gradle.kts new file mode 100644 index 00000000..874dd844 --- /dev/null +++ b/bindings/uniffi/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "zen-engine" \ No newline at end of file diff --git a/bindings/uniffi/src/config.rs b/bindings/uniffi/src/config.rs new file mode 100644 index 00000000..b87b251f --- /dev/null +++ b/bindings/uniffi/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) + } +} diff --git a/bindings/uniffi/src/custom_node.rs b/bindings/uniffi/src/custom_node.rs new file mode 100644 index 00000000..6f402e7c --- /dev/null +++ b/bindings/uniffi/src/custom_node.rs @@ -0,0 +1,56 @@ +use crate::error::ZenError; +use crate::types::{DecisionNode, 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; + +#[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, + _: 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 + .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: Variable = 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, trace_data }) + } +} diff --git a/bindings/uniffi/src/decision.rs b/bindings/uniffi/src/decision.rs new file mode 100644 index 00000000..b94cb937 --- /dev/null +++ b/bindings/uniffi/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, 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::try_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/uniffi/src/engine.rs b/bindings/uniffi/src/engine.rs new file mode 100644 index 00000000..df796fed --- /dev/null +++ b/bindings/uniffi/src/engine.rs @@ -0,0 +1,122 @@ +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, ZenEngineResponse}; +use serde_json::Value; +use std::sync::Arc; +use tokio::runtime::Handle; +use tokio::task; +use zen_engine::{DecisionEngine, EvaluationOptions}; + +#[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::try_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/uniffi/src/error.rs b/bindings/uniffi/src/error.rs new file mode 100644 index 00000000..3a9c28eb --- /dev/null +++ b/bindings/uniffi/src/error.rs @@ -0,0 +1,63 @@ +use serde_json::json; +use std::fmt::Formatter; +use zen_expression::IsolateError; + +#[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) + } +} + +impl From for ZenError { + fn from(error: IsolateError) -> Self { + ZenError::EvaluationError( + serde_json::to_string(&error).unwrap_or_else(|_| error.to_string()), + ) + } +} diff --git a/bindings/uniffi/src/expression.rs b/bindings/uniffi/src/expression.rs new file mode 100644 index 00000000..76cf930a --- /dev/null +++ b/bindings/uniffi/src/expression.rs @@ -0,0 +1,75 @@ +use crate::error::ZenError; +use crate::types::JsonBuffer; +use zen_expression::expression::{Standard, Unary}; +use zen_expression::{Expression, Variable}; + +#[uniffi::export] +pub fn evaluate_expression( + expression: String, + context: Option, +) -> Result { + let ctx: Variable = context + .map(Variable::try_from) + .transpose()? + .unwrap_or(Variable::Null); + + zen_expression::evaluate_expression(expression.as_str(), ctx).map(JsonBuffer::try_from)? +} + +#[allow(dead_code)] +#[uniffi::export] +pub fn evaluate_unary_expression( + expression: String, + context: JsonBuffer, +) -> Result { + let ctx: Variable = context.try_into()?; + + Ok(zen_expression::evaluate_unary_expression( + expression.as_str(), + ctx, + )?) +} + +#[derive(uniffi::Object)] +pub(crate) struct ZenExpression { + expression: Expression, +} + +#[uniffi::export] +impl ZenExpression { + #[uniffi::constructor] + pub fn compile(expression: String) -> Result { + zen_expression::compile_expression(expression.as_str()) + .map_err(|err| ZenError::IsolateError(err.to_string())) + .map(|expression| Self { expression }) + } + + pub fn evaluate(&self, context: Option) -> Result { + let ctx: Variable = context + .map(Variable::try_from) + .transpose()? + .unwrap_or(Variable::Null); + + self.expression.evaluate(ctx).map(JsonBuffer::try_from)? + } +} + +#[derive(uniffi::Object)] +pub(crate) struct ZenExpressionUnary { + expression: Expression, +} + +#[uniffi::export] +impl ZenExpressionUnary { + #[uniffi::constructor] + pub fn compile(expression: String) -> Result { + zen_expression::compile_unary_expression(expression.as_str()) + .map_err(|err| ZenError::IsolateError(err.to_string())) + .map(|expression| Self { expression }) + } + + pub fn evaluate(&self, context: JsonBuffer) -> Result { + let ctx: Variable = context.try_into()?; + Ok(self.expression.evaluate(ctx)?) + } +} diff --git a/bindings/uniffi/src/lib.rs b/bindings/uniffi/src/lib.rs new file mode 100644 index 00000000..9eb2e646 --- /dev/null +++ b/bindings/uniffi/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/uniffi/src/loader.rs b/bindings/uniffi/src/loader.rs new file mode 100644 index 00000000..e21b2e07 --- /dev/null +++ b/bindings/uniffi/src/loader.rs @@ -0,0 +1,54 @@ +use crate::error::ZenError; +use crate::types::JsonBuffer; +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; + +#[uniffi::export(callback_interface)] +#[async_trait::async_trait] +pub trait ZenDecisionLoaderCallback: Send + Sync { + async fn load(&self, key: String) -> Result, ZenError>; +} + +pub struct NoopDecisionLoader; + +#[async_trait::async_trait] +impl ZenDecisionLoaderCallback for NoopDecisionLoader { + async fn load(&self, _: String) -> Result, ZenError> { + 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_json_buffer = match self.0.load(key.into()).await { + Ok(r) => r, + Err(error) => { + return Err(Box::new(LoaderError::Internal { + key: key.to_string(), + source: anyhow!(error), + })); + } + }; + + let Some(json_buffer) = maybe_json_buffer else { + return Err(Box::new(LoaderError::NotFound(key.to_string()))); + }; + + let decision_content: DecisionContent = + serde_json::from_slice(json_buffer.0.as_slice()).map_err(|e| { + LoaderError::Internal { + key: key.to_string(), + source: anyhow!(e), + } + })?; + + Ok(Arc::new(decision_content)) + } + } +} diff --git a/bindings/uniffi/src/types.rs b/bindings/uniffi/src/types.rs new file mode 100644 index 00000000..ba2ccd21 --- /dev/null +++ b/bindings/uniffi/src/types.rs @@ -0,0 +1,129 @@ +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}; +use zen_expression::Variable; + +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 Variable { + 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) + } +} + +impl TryFrom for JsonBuffer { + type Error = ZenError; + + fn try_from(var: Variable) -> Result { + serde_json::to_vec(&var) + .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 TryFrom for ZenEngineTrace { + type Error = ZenError; + + fn try_from(value: DecisionGraphTrace) -> Result { + Ok(Self { + id: value.id, + name: value.name, + input: JsonBuffer::try_from(value.input)?, + output: JsonBuffer::try_from(value.output)?, + performance: value.performance, + trace_data: value.trace_data.map(JsonBuffer::try_from).transpose()?, + order: value.order, + }) + } +} + +#[derive(uniffi::Record)] +pub struct ZenEngineResponse { + pub performance: String, + pub result: JsonBuffer, + pub trace: Option>, +} + +impl TryFrom for ZenEngineResponse { + type Error = ZenError; + + fn try_from(value: DecisionGraphResponse) -> Result { + Ok(Self { + performance: value.performance, + result: JsonBuffer::try_from(value.result)?, + trace: value + .trace + .map(|opt| { + opt.into_iter() + .map(|(key, value)| Ok((key, ZenEngineTrace::try_from(value)?))) + .collect::>() + }) + .transpose()?, + }) + } +} + +#[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/uniffi/uniffi-bindgen.rs b/bindings/uniffi/uniffi-bindgen.rs new file mode 100644 index 00000000..f6cff6cf --- /dev/null +++ b/bindings/uniffi/uniffi-bindgen.rs @@ -0,0 +1,3 @@ +fn main() { + uniffi::uniffi_bindgen_main() +} diff --git a/bindings/uniffi/uniffi.toml b/bindings/uniffi/uniffi.toml new file mode 100644 index 00000000..ed2a9997 --- /dev/null +++ b/bindings/uniffi/uniffi.toml @@ -0,0 +1,26 @@ +# Kotlin +[bindings.kotlin] +package_name = "io.gorules.zen_engine.kotlin" +generate_immutable_records = true + +[bindings.kotlin.custom_types.JsonBuffer] +into_custom = "JsonBuffer({})" +from_custom = "{}.value" + +# Java +[bindings.java] +package_name = 'io.gorules.zen_engine' +generate_immutable_records = true + +[bindings.java.custom_types.JsonBuffer] +into_custom = "{}" +from_custom = "{}" + +# C# +[bindings.csharp] +namespace = "GoRules.ZenEngine" +cdylib_name = "Libs/zen_uniffi" + +[bindings.csharp.custom_types.JsonBuffer] +into_custom = "new JsonBuffer({})" +from_custom = "{}.Value" \ No newline at end of file