Laravel Rust
bree-laravel adds Bree to a Laravel Rust application. Rules are compiled into the application with bree::rules! and evaluated inside its process, so there is no Bree server to deploy and no network hop on the request path.
It works with laravel-rust 0.1.4 and later 0.1 releases. This repository builds and tests against 0.1.5.
Run the example
examples/laravel-rust is a Laravel Rust application with one route, POST /api/shipments/eligibility, that asks the shipment_eligibility rule whether a parcel can ship. Its rule and tests are in examples/laravel-rust/rules.
Requires Rust 1.99+ and a C++ compiler. From the repository root:
cd examples/laravel-rust
cp .env.example .env
cargo run -- key:generate
cargo run -- serveThe application listens on http://127.0.0.1:8000 (--port changes it). In another terminal:
$ curl -s -X POST http://127.0.0.1:8000/api/shipments/eligibility \
-H 'Content-Type: application/json' -H 'Accept: application/json' \
-d '{"origin_postal_prefix":"M5V","destination_postal_prefix":"H2X","weight_grams":22000,"service":"express","service_limits":[{"service":"express","max_weight_grams":30000,"origin_prefixes":["M"],"destination_prefixes":["H","M"]}]}'
{"eligible":false,"reason":"overweight","digest":"sha256:101d5f62411af7044de482d4ad188fdc991faf6c3d1d4d7881527e6d2859b9ee"}Express parcels are capped at 20 kg by the rule, below the carrier's 30 kg. Input the rule's types do not allow gets a 422 naming the field:
{"error":{"code":"invalid_input","message":"the input does not match the Input type of shipment_eligibility","violations":[{"field":"service","message":"must be one of \"standard\", \"express\", \"overnight\""}]}}and so does input the rule rejects with invalid:
{"error":{"code":"invalid_input","message":"the input was rejected","violations":[{"field":"origin_postal_prefix","message":"must be 1 to 5 upper-case letters or digits, such as M5V"}]}}The example's .env.example sets BREE_RULES=rules, so the running application watches rules/ (Reloading). Raise EXPRESS_MAX_GRAMS to 25000 in rules/shipment_eligibility.luau while it runs, and the log says why nothing changed:
WARN bree_laravel: bree: kept the previous rules because the rules have 1 problem:
rules/shipment_eligibility.test.luau:42: test "express is capped at 20 kg, below the carrier's 30 kg" failed
expected { eligible = false, reason = "overweight" }
got { eligible = true, reason = "eligible" }Update that test to match (a 26 kg parcel, "capped at 25 kg") and the change goes live within a second, with no rebuild:
INFO bree_laravel: bree: loaded shipment_eligibility rule=shipment_eligibility digest=sha256:2b50dc723edf6457f50e9ce8ce341909ad39047783b552944e365c32756e88b3{"eligible":true,"reason":"eligible","digest":"sha256:2b50dc723edf6457f50e9ce8ce341909ad39047783b552944e365c32756e88b3"}The next cargo build compiles the new rule in. Put the files back with git checkout examples/laravel-rust/rules.
The example's tests send requests through the application: cargo test -p bree-example-laravel-rust.
Add Bree to your application
1. Dependencies
[dependencies]
bree = { git = "https://github.com/breeso/bree" }
bree-laravel = { git = "https://github.com/breeso/bree" }2. Compile the rules in
Put your rules in rules/ next to Cargo.toml (bree init starts one), and in src/lib.rs:
/// The rules in `rules/`, type checked and tested when this crate compiles.
pub mod rules {
bree::rules!("rules");
}Add a build.rs so the crate rebuilds when a rule file is added:
fn main() {
println!("cargo::rerun-if-changed=rules");
}3. Register the provider
In src/app.rs:
use crate::rules;
pub fn configure() -> ApplicationBuilder {
Application::configure()
.with_providers(|providers| {
providers.add(bree_laravel::BreeServiceProvider::new(&rules::RULES));
})
// ...
}The provider registers a Bree singleton and loads the rules while the application boots. If they do not load, because a test fails or a rule's types no longer match the ones compiled in, the application does not start.
4. Decide in a handler
Take Inject<Bree>. It derefs to bree::Engine, so everything in Rust works on it. For a request body, decide_value checks the raw JSON against the rule's Input type, so the client gets every problem at once, named by field:
use bree_laravel::{Bree, error_response};
use laravel::prelude::*;
use serde::Serialize;
use crate::rules::shipment_eligibility::{self, Reason};
#[derive(Debug, Serialize)]
pub struct Eligibility {
pub eligible: bool,
pub reason: Reason,
/// Which version of the rule decided: a digest of its source.
pub digest: String,
}
pub async fn eligibility(bree: Inject<Bree>, request: Request) -> laravel::Result<Response> {
let input: serde_json::Value = request.json()?;
Ok(
match bree.decide_value::<shipment_eligibility::Rule>(input) {
Ok(decision) => Json(Eligibility {
eligible: decision.output.eligible,
reason: decision.output.reason,
digest: decision.digest,
})
.into_response(),
Err(error) => error_response(&error),
},
)
}and route it in src/routes/api.rs:
route.post("/shipments/eligibility", shipments::eligibility);When your code builds the input itself, call the generated function instead: shipment_eligibility::decide(&bree, &input).
error_response renders an error the way the HTTP API does: {"error": {"code", "message", "violations"}} with the code's status, such as 422 for invalid_input. A body that is not JSON never reaches Bree: request.json() fails first, and Laravel answers with its own 400.
Configuration
| Variable | Default | |
|---|---|---|
BREE_RULES |
(empty) | A rules directory to load and watch, relative to where the application runs. Empty uses the rules compiled in. |
BREE_RELOAD_INTERVAL_MS |
1000 |
How often to look for changes in BREE_RULES. 0 loads once at startup. |
Reloads and refused changes are logged through tracing, as above.
Testing
Tests built with #[laravel::test] boot the whole application, rules included. Set BREE_RULES to empty in your testing configuration so tests use the rules compiled in, as the example does in src/testing.rs:
.with_envs([
("APP_ENV", "testing"),
("BREE_RULES", ""),
// ...
])Deploying
With BREE_RULES empty, the rules are part of the binary: deploy the application as usual, and every rule change goes through your build, its tests and your review. If you set BREE_RULES in production, ship the rules directory with the application; changes made there are used once they pass, and logged either way.