Skip to content

Commit

Permalink
Merge pull request #5 from superwall/develop
Browse files Browse the repository at this point in the history
WASM support & Android publishing
  • Loading branch information
ianrumac authored Sep 12, 2024
2 parents 6cc5ad6 + 71c84bb commit 76d961d
Show file tree
Hide file tree
Showing 24 changed files with 21,896 additions and 40 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
./wasm/pkg
**/node_modules
.DS_Store
**/.DS_Store
**/.so
Expand All @@ -17,7 +19,6 @@
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

Expand Down
9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.htmlž
[lib]
name = "cel_eval"
crate-type = ["staticlib","cdylib"]
crate-type = ["staticlib","cdylib", "rlib"]
path = "src/lib.rs"

[dependencies]
cel-interpreter = "0.8.1"
Expand All @@ -15,7 +16,9 @@ uniffi = { version = "0.28" }
serde = { version = "1.0", features = ["serde_derive"] }
serde_json = { version = "1.0" }
async-trait = "0.1.81"
smol = "2.0.1"
wasm-bindgen-futures = "0.4.43"
futures-lite = "2.3.0"


[dev-dependencies]
tokio = { version = "^1.20", features = ["rt-multi-thread", "macros"] }
Expand All @@ -33,3 +36,5 @@ codegen-units = 1
panic = "abort"
strip=true

[workspace]
members = ["wasm"]
23 changes: 23 additions & 0 deletions build_wasm.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/bin/bash

set -e

echo "0% - Building for WASM(browser,node):"
cargo build --lib --release --target wasm32-unknown-unknown
echo " 25% - WASM build successful ✅"
echo " 25% - Ensuring WASM wrapper is built"
cd wasm
cargo build --lib --release --target wasm32-unknown-unknown
echo "50% - WASM wrapper build successful ✅"

echo "50% - Building JS bundles"
mkdir -p ./target/browser
mkdir -p ./target/node
npm run build

echo "75% - Build done - ✅"
echo "75% - Installing to example project"
cd example/browser/
npm install ../../target/browser

echo "100% - Done - ✅"
86 changes: 49 additions & 37 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(not(target_arch = "wasm32"))]
uniffi::include_scaffolding!("cel");
mod ast;
mod models;
Expand All @@ -11,16 +12,34 @@ use cel_interpreter::extractors::This;
use cel_interpreter::objects::{Key, Map, TryIntoValue};
use cel_interpreter::{Context, ExecutionError, Expression, FunctionContext, Program, Value};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, mpsc, Mutex};
use std::thread::spawn;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;
#[cfg(not(target_arch = "wasm32"))]
use futures_lite::future::block_on;
/**
* Host context trait that defines the methods that the host context should implement,
* i.e. iOS or Android calling code. This trait is used to resolve dynamic properties in the
* CEL expression during evaluation, such as `platform.daysSinceEvent("event_name")` or similar.
*/

#[async_trait]
pub trait AsyncHostContext: Send + Sync {
async fn computed_property(&self, name: String, args: String) -> String;
}

#[cfg(target_arch = "wasm32")]
pub trait HostContext: Send + Sync {
fn computed_property(&self, name: String, args: String) -> String;
}

#[cfg(not(target_arch = "wasm32"))]
#[async_trait]
pub trait HostContext: Send + Sync {
async fn computed_property(&self, name: String, args: String) -> String;
Expand All @@ -33,7 +52,7 @@ pub trait HostContext: Send + Sync {
* @return The result of the evaluation, either "true" or "false"
*/
pub fn evaluate_ast_with_context(definition: String, host: Arc<dyn HostContext>) -> String {
let data: ASTExecutionContext = serde_json::from_str(definition.as_str()).unwrap();
let data: ASTExecutionContext = serde_json::from_str(definition.as_str()).expect("Invalid context definition for AST Execution");
let host = host.clone();
execute_with(
AST(data.expression.into()),
Expand All @@ -49,7 +68,7 @@ pub fn evaluate_ast_with_context(definition: String, host: Arc<dyn HostContext>)
* @return The result of the evaluation, either "true" or "false"
*/
pub fn evaluate_ast(ast: String) -> String {
let data: JSONExpression = serde_json::from_str(ast.as_str()).unwrap();
let data: JSONExpression = serde_json::from_str(ast.as_str()).expect("Invalid definition for AST Execution");
let ctx = Context::default();
let res = ctx.resolve(&data.into()).unwrap();
let res = DisplayableValue(res.clone());
Expand All @@ -71,8 +90,7 @@ pub fn evaluate_with_context(definition: String, host: Arc<dyn HostContext>) ->
panic!("Error: {}", e.to_string());
}
};
let compiled = Program::compile(data.expression.as_str()).unwrap();
println!("{}", data.platform.is_some());
let compiled = Program::compile(data.expression.as_str()).expect("Failed to compile expression");
execute_with(
CompiledProgram(compiled),
data.variables,
Expand Down Expand Up @@ -110,34 +128,55 @@ fn execute_with(
variables
.map
.iter()
.for_each(|it| ctx.add_variable(it.0.as_str(), it.1.to_cel()).unwrap());
.for_each(|it| ctx.add_variable(it.0.as_str(), it.1.to_cel())
.expect(format!("Failed to add variable locally - {}", it.0).as_str()));
// Add maybe function
ctx.add_function("maybe", maybe);

// This function is used to extract the value of a property from the host context
// As UniFFi doesn't support recursive enums yet, we have to pass it in as a
// JSON serialized string of a PassableValue from Host and deserialize it here
#[cfg(not(target_arch = "wasm32"))]
fn prop_for(
name: Arc<String>,
args: Option<Vec<PassableValue>>,
ctx: &Arc<dyn HostContext>,
) -> Option<PassableValue> {
// Get computed property
let val = smol::block_on(async move {
let val = futures_lite::future::block_on(async move {
let ctx = ctx.clone();

ctx.computed_property(
name.clone().to_string(),
serde_json::to_string(&args).unwrap(),
serde_json::to_string(&args).expect("Failed to serialize args for computed property"),
)
.await
});
// Deserialize the value
let passable: Option<PassableValue> = serde_json::from_str(val.as_str()).unwrap_or(None);
let passable: Option<PassableValue> = serde_json::from_str(val.as_str()).unwrap_or(Some(PassableValue::Null));

passable
}

#[cfg(target_arch = "wasm32")]
fn prop_for(
name: Arc<String>,
args: Option<Vec<PassableValue>>,
ctx: &Arc<dyn HostContext>,
) -> Option<PassableValue> {
let ctx = ctx.clone();

let val = ctx.computed_property(
name.clone().to_string(),
serde_json::to_string(&args).expect("Failed to serialize args for computed property"),
);
// Deserialize the value
let passable: Option<PassableValue> = serde_json::from_str(val.as_str()).unwrap_or(Some(PassableValue::Null));

passable
}


let platform = platform.unwrap_or(HashMap::new()).clone();

// Create platform properties as a map of keys and function names
Expand Down Expand Up @@ -230,7 +269,6 @@ pub struct DisplayableError(ExecutionError);

impl fmt::Display for DisplayableValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Assuming Value is an enum with variants Integer, Float, and Str
match &self.0 {
Value::Int(i) => write!(f, "{}", i),
Value::Float(x) => write!(f, "{}", x),
Expand Down Expand Up @@ -272,35 +310,9 @@ impl fmt::Display for DisplayableValue {
}
}
}

impl fmt::Display for DisplayableError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Assuming Value is an enum with variants Integer, Float, and Str
match &self.0 {
ExecutionError::InvalidArgumentCount { .. } => write!(f, "InvalidArgumentCount"),
ExecutionError::UnsupportedTargetType { .. } => write!(f, "UnsupportedTargetType"),
ExecutionError::NotSupportedAsMethod { .. } => write!(f, "NotSupportedAsMethod"),
ExecutionError::UnsupportedKeyType(_) => write!(f, "UnsupportedKeyType"),
ExecutionError::UnexpectedType { .. } => write!(f, "UnexpectedType"),
ExecutionError::NoSuchKey(_) => write!(f, "NoSuchKey"),
ExecutionError::UndeclaredReference(_) => write!(f, "UndeclaredReference"),
ExecutionError::MissingArgumentOrTarget => write!(f, "MissingArgumentOrTarget"),
ExecutionError::ValuesNotComparable(_, _) => write!(f, "ValuesNotComparable"),
ExecutionError::UnsupportedUnaryOperator(_, _) => write!(f, "UnsupportedUnaryOperator"),
ExecutionError::UnsupportedBinaryOperator(_, _, _) => {
write!(f, "UnsupportedBinaryOperator")
}
ExecutionError::UnsupportedMapIndex(_) => write!(f, "UnsupportedMapIndex"),
ExecutionError::UnsupportedListIndex(_) => write!(f, "UnsupportedListIndex"),
ExecutionError::UnsupportedIndex(_, _) => write!(f, "UnsupportedIndex"),
ExecutionError::UnsupportedFunctionCallIdentifierType(_) => {
write!(f, "UnsupportedFunctionCallIdentifierType")
}
ExecutionError::UnsupportedFieldsConstruction(_) => {
write!(f, "UnsupportedFieldsConstruction")
}
ExecutionError::FunctionError { .. } => write!(f, "FunctionError"),
}
write!(f,"{}",self.0.to_string().as_str())
}
}

Expand Down
3 changes: 3 additions & 0 deletions uniffi.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[bindings.kotlin]
package_name = 'com.superwall.supercel'
android = true
23 changes: 23 additions & 0 deletions wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "supercel-wasm"
version = "0.1.0"
edition = "2021"
publish = false


[lib]
crate-type = ["cdylib"]

[dependencies]
cel-eval = { path = ".." }
wasm-bindgen = "0.2.93"
wasm-bindgen-futures = "0.4.43"
futures = "0.3.30"
console_error_panic_hook = "0.1.7"

[profile.release]
lto = true
opt-level = "z" # Optimize for size.
codegen-units = 1
panic = "abort"
strip=true
48 changes: 48 additions & 0 deletions wasm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Supercel WASM Module

This project demonstrates how to use WebAssembly (WASM) with Rust and JavaScript to create a dynamic expression evaluator. The evaluator can call host environment functions and compute dynamic properties.

## Getting Started

### Prerequisites

- [Node.js](https://nodejs.org/)
- [wasm-pack](https://rustwasm.github.io/wasm-pack/installer/)
- [Cargo & Rust](https://www.rust-lang.org/tools/install)
- [wasm-pack](https://github.com/rustwasm/wasm-pack/)


### Setup
- Install the prerequisites
- Run `rustup target add wasm32-unknown-unknown` to add the WASM target

### Building the Project

To build the project, you need to:

- Run `./build_wasm.sh`

**OR**

- Build the WASM project for the first time: `cargo build --lib --target wasm32-unknown-unknown`

Then use:
```bash
npm run build
```

This will generate targets in the `.target/` directory
* `./target/browser` for browser environments
* `./target/node` for Node.js environments


### Running the Project

For **browsers**:

- Open `./example/browser/` and run `npm install ../../target/browser && npm run start`

For **node**:
- Open `./example/` and run `node test_node.js`


23 changes: 23 additions & 0 deletions wasm/example/browser/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
46 changes: 46 additions & 0 deletions wasm/example/browser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).


## Setup

- Run `./build_wasm.sh` to build the wasm module.
- Run `npm install ../../target/browser` to install the dependencies.

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.

The page will reload when you make changes.\
You may also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can't go back!**

If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.

You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
Loading

0 comments on commit 76d961d

Please sign in to comment.