pub struct Engine<Ctx: MaybeSync + ?Sized + 'static> { /* private fields */ }
Expand description
Rules engine for registering fetchers/operators and parsing rules.
§Type Parameters
Ctx
: The context type that rules will be evaluated against
§Example
struct User {
name: String,
age: u32,
roles: Vec<String>,
}
let mut engine = Engine::new();
engine.register_fetcher("name", |user: &User, _args| {
Ok(Value::from(&user.name))
});
engine.register_fetcher("age", |user: &User, _args| {
Ok(Value::from(user.age))
});
engine.register_fetcher("has_role", |user: &User, args| {
let role = args.first().ok_or("Role name required")?;
Ok(Value::from(user.roles.contains(&role)))
});
let rule = engine.compile_rule(&json!([
{"age": {">=": 18}},
{"has_role(admin)": true}
])).unwrap();
Implementations§
Source§impl<Ctx: MaybeSync + ?Sized> Engine<Ctx>
impl<Ctx: MaybeSync + ?Sized> Engine<Ctx>
Sourcepub fn register_fetcher(
&mut self,
name: &str,
func: FetcherFn<Ctx>,
) -> &mut Fetcher<Ctx>
pub fn register_fetcher( &mut self, name: &str, func: FetcherFn<Ctx>, ) -> &mut Fetcher<Ctx>
Registers a synchronous fetcher with its name and function, using the default matcher.
A fetcher is a function that extracts values from the context type. The fetcher name is used
in rule definitions to reference this fetcher. By default, the DefaultMatcher
is used, which
supports basic equality and comparison operations.
§Returns
A mutable reference to the created Fetcher
, allowing you to customize it (e.g., change the matcher)
Sourcepub fn register_async_fetcher(
&mut self,
name: &str,
func: AsyncFetcherFn<Ctx>,
) -> &mut Fetcher<Ctx>
pub fn register_async_fetcher( &mut self, name: &str, func: AsyncFetcherFn<Ctx>, ) -> &mut Fetcher<Ctx>
Registers an async fetcher with its name and function, using the default matcher.
See Self::register_fetcher
for more details.
Sourcepub fn register_operator<O>(&mut self, name: &str, op: O)where
O: ToOperator<Ctx> + 'static,
pub fn register_operator<O>(&mut self, name: &str, op: O)where
O: ToOperator<Ctx> + 'static,
Registers a custom operator
Sourcepub fn compile_rule(&self, value: &JsonValue) -> Result<Rule<Ctx>, Error>
pub fn compile_rule(&self, value: &JsonValue) -> Result<Rule<Ctx>, Error>
Compiles a JSON value into a Rule::All
using the registered fetchers and operators.
Sourcepub fn validate_rule<'a>(
&self,
value: &'a JsonValue,
) -> StdResult<(), ValidationError<'a>>
Available on crate feature validation
only.
pub fn validate_rule<'a>( &self, value: &'a JsonValue, ) -> StdResult<(), ValidationError<'a>>
validation
only.Validates a JSON rule against dynamically generated JSON Schema of this engine.
Sourcepub fn json_schema(&self) -> JsonValue
pub fn json_schema(&self) -> JsonValue
Builds a JSON Schema for rules, including dynamic properties.