feat(bindings)!: add RVM/Program support across FFI and language bindings (#565)

- FFI: add RVM/Program APIs, execution state accessors, HostAwait handling, and buffer/result helpers in rvm.rs, common.rs, engine.rs.
- Compiler: emit HostAwait for __builtin_host_await in function_calls.rs.
- RVM tests: add HostAwait regression cases and extend harness for suspend/resume responses in host_await.yaml and mod.rs.
- C/C++: add RVM tests/examples and wrapper updates in rvm_tests.c, rvm_tests.cpp, regorus.hpp, plus CMake wiring.
- C#: add Program/Rvm bindings, SafeHandle/PInvoke, tests, and example usage in Regorus, RvmProgramTests.cs, Program.cs, and README updates.
- Go: add Program/Rvm bindings, tests, and examples in rvm.go, rvm_test.go, main.go.
- Java: add Program/Rvm bindings, JNI glue, and examples in lib.rs, regorus, Test.java.
- Python: add Program/Rvm bindings and examples in lib.rs, test.py.
- WASM: add Program/Rvm bindings and examples in lib.rs, test.js.
- Tooling: wire binding tests in xtask and ignore generated Java artifacts in .gitignore.

Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
This commit is contained in:
Anand Krishnamoorthi
2026-01-30 23:55:31 +05:30
committed by GitHub
parent 0316ccd90c
commit 3f7a5496dc
50 changed files with 4990 additions and 110 deletions
+31 -10
View File
@@ -63,6 +63,16 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bincode"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740"
dependencies = [
"serde",
"unty",
]
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -120,9 +130,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.2.54"
version = "1.2.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583"
checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -208,9 +218,9 @@ dependencies = [
[[package]]
name = "find-msvc-tools"
version = "0.1.8"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "fluent-uri"
@@ -314,9 +324,9 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "iana-time-zone"
version = "0.1.64"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
@@ -446,6 +456,8 @@ checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
@@ -874,10 +886,12 @@ name = "regorus"
version = "0.9.0"
dependencies = [
"anyhow",
"bincode",
"chrono",
"chrono-tz",
"data-encoding",
"globset",
"indexmap",
"ipnet",
"jsonschema",
"lazy_static",
@@ -903,6 +917,7 @@ dependencies = [
"getrandom 0.2.17",
"getrandom 0.3.4",
"regorus",
"serde",
"serde_json",
"uuid",
"wasm-bindgen",
@@ -1098,6 +1113,12 @@ version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]]
name = "unty"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae"
[[package]]
name = "url"
version = "2.5.8"
@@ -1398,18 +1419,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.34"
version = "0.8.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71ddd76bcebeed25db614f82bf31a9f4222d3fbba300e6fb6c00afa26cbd4d9d"
checksum = "dafd85c832c1b68bbb4ec0c72c7f6f4fc5179627d2bc7c26b30e4c0cc11e76cc"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.34"
version = "0.8.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8187381b52e32220d50b255276aa16a084ec0a9017a0ca2152a1f55c539758d"
checksum = "7cb7e4e8436d9db52fbd6625dbf2f45243ab84994a72882ec8227b99e72b439a"
dependencies = [
"proc-macro2",
"quote",
+2 -1
View File
@@ -37,7 +37,8 @@ ast = ["regorus/ast"]
coverage = ["regorus/coverage"]
[dependencies]
regorus = { path = "../..", default-features = false, features = ["arc"] }
regorus = { path = "../..", default-features = false, features = ["arc", "rvm"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
wasm-bindgen = "0.2.100"
# Specify uuid as a mandatory dependency so as to enable `js` feature which is now required
+194
View File
@@ -3,6 +3,15 @@
#![allow(non_snake_case)]
use regorus::languages::rego::compiler::Compiler;
use regorus::rvm::program::{
generate_assembly_listing, generate_tabular_assembly_listing, AssemblyListingConfig,
DeserializationResult, Program as RvmProgram,
};
use regorus::rvm::vm::{ExecutionMode, RegoVM};
use regorus::{compile_policy_with_entrypoint, PolicyModule, Rc, Value};
use serde::Deserialize;
use std::sync::Arc;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
@@ -11,6 +20,44 @@ pub struct Engine {
engine: regorus::Engine,
}
#[derive(Deserialize)]
struct ModuleSpec {
id: String,
content: String,
}
#[wasm_bindgen]
pub struct Program {
program: Arc<RvmProgram>,
}
#[wasm_bindgen]
pub struct ProgramDeserializationResult {
program: Arc<RvmProgram>,
is_partial: bool,
}
#[wasm_bindgen]
impl ProgramDeserializationResult {
/// Whether the program was partially deserialized.
#[wasm_bindgen(getter)]
pub fn isPartial(&self) -> bool {
self.is_partial
}
/// Get the deserialized program.
pub fn program(&self) -> Program {
Program {
program: self.program.clone(),
}
}
}
#[wasm_bindgen]
pub struct Rvm {
vm: RegoVM,
}
fn error_to_jsvalue<E: std::fmt::Display>(e: E) -> JsValue {
JsValue::from_str(&format!("{e}"))
}
@@ -193,6 +240,153 @@ impl Engine {
}
}
#[wasm_bindgen]
impl Program {
/// Compile an RVM program from modules and entry points.
pub fn compileFromModules(
data_json: String,
modules_json: String,
entry_points_json: String,
) -> Result<Program, JsValue> {
let data = Value::from_json_str(&data_json).map_err(error_to_jsvalue)?;
let modules: Vec<ModuleSpec> =
serde_json::from_str(&modules_json).map_err(error_to_jsvalue)?;
let entry_points: Vec<String> =
serde_json::from_str(&entry_points_json).map_err(error_to_jsvalue)?;
if entry_points.is_empty() {
return Err(error_to_jsvalue(
"entry_points must contain at least one entry",
));
}
let policy_modules: Vec<PolicyModule> = modules
.into_iter()
.map(|module| PolicyModule {
id: Rc::from(module.id.as_str()),
content: Rc::from(module.content.as_str()),
})
.collect();
let entry_points_ref: Vec<&str> = entry_points.iter().map(|s| s.as_str()).collect();
let compiled =
compile_policy_with_entrypoint(data, &policy_modules, Rc::from(entry_points_ref[0]))
.map_err(error_to_jsvalue)?;
let program = Compiler::compile_from_policy(&compiled, &entry_points_ref)
.map_err(error_to_jsvalue)?;
Ok(Program { program })
}
/// Serialize a program to binary format.
pub fn serializeBinary(&self) -> Result<Vec<u8>, JsValue> {
self.program
.serialize_binary()
.map_err(|e| error_to_jsvalue(e.to_string()))
}
/// Deserialize an RVM program from binary format.
pub fn deserializeBinary(data: Vec<u8>) -> Result<ProgramDeserializationResult, JsValue> {
let (program, is_partial) =
match RvmProgram::deserialize_binary(&data).map_err(error_to_jsvalue)? {
DeserializationResult::Complete(program) => (program, false),
DeserializationResult::Partial(program) => (program, true),
};
Ok(ProgramDeserializationResult {
program: Arc::new(program),
is_partial,
})
}
/// Generate a readable assembly listing.
pub fn generateListing(&self) -> Result<String, JsValue> {
Ok(generate_assembly_listing(
self.program.as_ref(),
&AssemblyListingConfig::default(),
))
}
/// Generate a tabular assembly listing.
pub fn generateTabularListing(&self) -> Result<String, JsValue> {
Ok(generate_tabular_assembly_listing(
self.program.as_ref(),
&AssemblyListingConfig::default(),
))
}
}
#[wasm_bindgen]
impl Rvm {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self { vm: RegoVM::new() }
}
/// Load a program into the VM.
pub fn loadProgram(&mut self, program: &Program) {
self.vm.load_program(program.program.clone());
}
/// Set VM data from JSON.
pub fn setDataJson(&mut self, data_json: String) -> Result<(), JsValue> {
let data = Value::from_json_str(&data_json).map_err(error_to_jsvalue)?;
self.vm.set_data(data).map_err(error_to_jsvalue)
}
/// Set VM input from JSON.
pub fn setInputJson(&mut self, input_json: String) -> Result<(), JsValue> {
let input = Value::from_json_str(&input_json).map_err(error_to_jsvalue)?;
self.vm.set_input(input);
Ok(())
}
/// Set execution mode (0 = run-to-completion, 1 = suspendable).
pub fn setExecutionMode(&mut self, mode: u8) -> Result<(), JsValue> {
let mode = match mode {
0 => ExecutionMode::RunToCompletion,
1 => ExecutionMode::Suspendable,
_ => return Err(error_to_jsvalue("invalid execution mode")),
};
self.vm.set_execution_mode(mode);
Ok(())
}
/// Execute the program and return the JSON result.
pub fn execute(&mut self) -> Result<String, JsValue> {
let value = self.vm.execute().map_err(error_to_jsvalue)?;
value.to_json_str().map_err(error_to_jsvalue)
}
/// Execute an entry point by name and return the JSON result.
pub fn executeEntryPoint(&mut self, entry_point: String) -> Result<String, JsValue> {
let value = self
.vm
.execute_entry_point_by_name(&entry_point)
.map_err(error_to_jsvalue)?;
value.to_json_str().map_err(error_to_jsvalue)
}
/// Resume execution with an optional JSON value.
pub fn resume(&mut self, resume_json: Option<String>) -> Result<String, JsValue> {
let value = if let Some(json) = resume_json {
Some(Value::from_json_str(&json).map_err(error_to_jsvalue)?)
} else {
None
};
let result = self.vm.resume(value).map_err(error_to_jsvalue)?;
result.to_json_str().map_err(error_to_jsvalue)
}
/// Get the execution state as a string.
pub fn getExecutionState(&self) -> String {
format!("{:?}", self.vm.execution_state())
}
}
impl Default for Rvm {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use crate::error_to_jsvalue;
+75
View File
@@ -85,3 +85,78 @@ console.log(report);
// Print pretty report.
report = engine.getCoverageReportPretty();
console.log(report);
// RVM regular example
{
const policy = `
package demo
import rego.v1
default allow := false
allow if {
input.user == "alice"
input.active == true
}
`;
const modules = JSON.stringify([
{ id: "demo.rego", content: policy }
]);
const entryPoints = JSON.stringify(["data.demo.allow"]);
const program = regorus.Program.compileFromModules(
"{}",
modules,
entryPoints
);
console.log(program.generateListing());
const binary = program.serializeBinary();
const deserialized = regorus.Program.deserializeBinary(binary);
if (deserialized.isPartial) {
throw new Error("Deserialized program marked partial");
}
const rehydrated = deserialized.program();
const vm = new regorus.Rvm();
vm.loadProgram(rehydrated);
vm.setInputJson('{"user":"alice","active":true}');
console.log(vm.execute());
}
// RVM HostAwait example
{
const policy = `
package demo
import rego.v1
default allow := false
allow if {
input.account.active == true
details := __builtin_host_await(input.account.id, "account")
details.tier == "gold"
}
`;
const modules = JSON.stringify([
{ id: "await.rego", content: policy }
]);
const entryPoints = JSON.stringify(["data.demo.allow"]);
const program = regorus.Program.compileFromModules(
"{}",
modules,
entryPoints
);
const vm = new regorus.Rvm();
vm.setExecutionMode(1);
vm.loadProgram(program);
vm.setInputJson('{"account":{"id":"acct-1","active":true}}');
vm.execute();
console.log(vm.getExecutionState());
console.log(vm.resume('{"tier":"gold"}'));
}