Bree

Rust

[dependencies]
bree = { git = "https://github.com/breeso/bree" }

Requires Rust 1.99 or newer and a C++ compiler. For a Laravel Rust application, see Laravel Rust, which builds on everything here.

bree::rules!

mod rules {
    bree::rules!("rules");
}

The path is relative to the crate's Cargo.toml. While the crate compiles, the macro type checks every rule, module and test in the directory and runs every test. Each problem becomes a compile error naming the file and line; see Getting started for what they look like.

When everything passes, it generates:

Item What it is
rules::<rule> a module per rule. billing/refunds becomes rules::billing::refunds
rules::<rule>::Input, Output structs for the rule's types, with every type they use: Country, ServiceLimit, and so on
rules::<rule>::Rule a marker type implementing bree::Rule, for Engine::decide::<Rule>
rules::<rule>::decide(&engine, &input) evaluates the rule; the same as engine.decide::<Rule>(&input)
rules::RULES a bree::Bundle: every rule source, embedded in the binary, and each rule's fingerprint

Structs derive Debug, Clone, PartialEq, Serialize and Deserialize. String unions become enums that also derive Copy, Eq, Hash and Ord, and have as_str() and Display returning the Luau string: Country::Ca.as_str() == "CA". Luau comments become doc comments, so your editor shows them on hover.

The crate rebuilds when a rule file changes. To rebuild when a file is added too, add a build.rs:

fn main() {
    println!("cargo::rerun-if-changed=rules");
}

Loading rules

let engine = bree::Engine::embedded(&rules::RULES)?;

Engine::embedded loads the rules compiled into the binary. Like every engine, it checks and tests them as it loads (a few milliseconds), and returns Err(LoadError) listing every problem if anything fails.

For anything else, use the builder:

use std::time::Duration;

let engine = bree::Engine::builder()
    .bundle(&rules::RULES)                   // generated types: refuse rules whose types changed
    .dir("rules")                            // load from disk instead of the binary
    .reload_every(Duration::from_secs(1))    // and pick up changes; see Reloading
    .limits(bree::Limits {
        max_steps: 1_000_000,
        max_memory_bytes: 16 * 1024 * 1024,
        timeout: Duration::from_secs(1),
    })
    .on_reload(|event| { /* log it */ })
    .build()?;

Engine::open("rules") loads a directory once, without generated types; use it for tools and tests that evaluate by name.

An Engine is cheap to clone and safe to share between threads. Clones share the same rules, and every evaluation runs in its own VM.

Deciding

use rules::free_shipping::{self, Country, Input};

let decision = free_shipping::decide(&engine, &Input {
    order_total_cents: 8_000,
    country: Country::Ca,
})?;

decision.output.free;   // bool
decision.digest;        // "sha256:..."
decision.rule;          // "free_shipping"

For input you already have as JSON, such as a request body, use decide_value. Bree checks the JSON against the rule's Input type, so your handler needs no struct of its own, and the output is still typed:

let decision = engine.decide_value::<free_shipping::Rule>(body)?;

To evaluate by name, with JSON in and out:

let decision = engine.evaluate("free_shipping", &serde_json::json!({
    "order_total_cents": 8000,
    "country": "CA",
}))?;

evaluate_expecting(rule, Some(fingerprint), &input) does the same but fails with types_mismatch unless the loaded rule has that fingerprint. It is for callers that generated their own types from the rules, such as other languages.

Errors

Evaluations fail with a bree::EvalError:

match free_shipping::decide(&engine, &input) {
    Ok(decision) => { /* ... */ }
    Err(e) if e.code == bree::ErrorCode::InvalidInput => {
        for v in &e.violations {
            println!("{}: {}", v.field, v.message);
        }
    }
    Err(e) => return Err(e.into()),
}

EvalError has a code, a message, and violations for invalid_input and invalid_output. It serializes to the JSON every integration uses, and code.http_status() gives the status bree serve would answer with. The codes are listed in The runtime.

Inspecting rules

engine.rules() every loaded rule: name, digest, fingerprint
engine.rule(name) one rule, with its types
engine.reload() look for changes now; Ok(true) if new rules were loaded
engine.last_reload_error() why the latest change was refused, until one is accepted
bree::check_dir(path, limits) check and test a directory without loading it, as bree check does

Edit this page on GitHub