136 lines
6.1 KiB
Markdown
136 lines
6.1 KiB
Markdown
# HeroModels Rhai Engine (`engine`)
|
|
|
|
The `engine` crate provides a central Rhai scripting engine for the HeroModels project. It offers a unified way to interact with various HeroModels modules (like Calendar, Flow, Legal, etc.) through Rhai scripts, leveraging a shared database connection.
|
|
|
|
## Overview
|
|
|
|
This crate facilitates:
|
|
|
|
1. **Centralized Engine Creation**: A function `create_heromodels_engine` to instantiate a Rhai engine pre-configured with common settings and all enabled HeroModels modules.
|
|
2. **Modular Registration**: HeroModels modules (Calendar, Flow, etc.) can be registered with a Rhai engine based on feature flags.
|
|
3. **Script Evaluation Utilities**: Helper functions for compiling Rhai scripts into Abstract Syntax Trees (ASTs) and for evaluating scripts or ASTs.
|
|
4. **Mock Database**: Includes a `mock_db` module for testing and running examples without needing a live database.
|
|
|
|
## Core Components & Usage
|
|
|
|
### Library (`src/lib.rs`)
|
|
|
|
- **`create_heromodels_engine(db: Arc<OurDB>) -> Engine`**:
|
|
Creates and returns a new `rhai::Engine` instance. This engine is configured with default settings (e.g., max expression depths, string/array/map sizes) and then all available HeroModels modules (controlled by feature flags) are registered with it, using the provided `db` (an `Arc<OurDB>`) instance.
|
|
|
|
- **`register_all_modules(engine: &mut Engine, db: Arc<OurDB>)`**:
|
|
Registers all HeroModels modules for which features are enabled (e.g., `calendar`, `flow`, `legal`, `projects`, `biz`) with the given Rhai `engine`. Each module is passed the shared `db` instance.
|
|
|
|
- **`eval_script(engine: &Engine, script: &str) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>>`**:
|
|
A utility function to directly evaluate a Rhai script string using the provided `engine`.
|
|
|
|
- **`compile_script(engine: &Engine, script: &str) -> Result<AST, Box<rhai::EvalAltResult>>`**:
|
|
Compiles a Rhai script string into an `AST` (Abstract Syntax Tree) for potentially faster repeated execution.
|
|
|
|
- **`run_ast(engine: &Engine, ast: &AST, scope: &mut Scope) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>>`**:
|
|
Runs a pre-compiled `AST` with a given `scope` using the provided `engine`.
|
|
|
|
- **`mock_db` module**:
|
|
Provides `create_mock_db()` which returns an `Arc<OurDB>` instance suitable for testing and examples. This allows scripts that interact with database functionalities to run without external database dependencies.
|
|
|
|
### Basic Usage
|
|
|
|
```rust
|
|
use std::sync::Arc;
|
|
use engine::{create_heromodels_engine, eval_script};
|
|
use engine::mock_db::create_mock_db; // For example usage
|
|
use heromodels::db::hero::OurDB; // Actual DB type
|
|
|
|
// Create a mock database (or connect to a real one)
|
|
let db: Arc<OurDB> = create_mock_db();
|
|
|
|
// Create the Rhai engine with all enabled modules registered
|
|
let engine = create_heromodels_engine(db);
|
|
|
|
// Run a Rhai script
|
|
let script = r#"
|
|
// Example: Assuming 'calendar' feature is enabled
|
|
let cal = new_calendar("My Test Calendar");
|
|
cal.set_description("This is a test.");
|
|
print(`Created calendar: ${cal.get_name()}`);
|
|
cal.get_id() // Return the ID
|
|
"#;
|
|
|
|
match eval_script(&engine, script) {
|
|
Ok(val) => println!("Script returned: {:?}", val),
|
|
Err(err) => eprintln!("Script error: {}", err),
|
|
}
|
|
```
|
|
|
|
### Using Specific Modules Manually
|
|
|
|
If you need more fine-grained control or only want specific modules (and prefer not to rely solely on feature flags at compile time for `create_heromodels_engine`), you can initialize an engine and register modules manually:
|
|
|
|
```rust
|
|
use std::sync::Arc;
|
|
use rhai::Engine;
|
|
use engine::mock_db::create_mock_db; // For example usage
|
|
use heromodels::db::hero::OurDB;
|
|
// Import the specific module registration function
|
|
use heromodels::models::calendar::register_calendar_rhai_module;
|
|
|
|
|
|
// Create a mock database
|
|
let db: Arc<OurDB> = create_mock_db();
|
|
|
|
// Create a new Rhai engine
|
|
let mut engine = Engine::new();
|
|
|
|
// Register only the calendar module
|
|
register_calendar_rhai_module(&mut engine, db.clone());
|
|
|
|
// Now you can use calendar-related functions in your scripts
|
|
let result = engine.eval::<String>(r#" let c = new_calendar("Solo Cal"); c.get_name() "#);
|
|
match result {
|
|
Ok(name) => println!("Calendar name: {}", name),
|
|
Err(err) => eprintln!("Error: {}", err),
|
|
}
|
|
```
|
|
|
|
## Examples
|
|
|
|
This crate includes several examples demonstrating how to use different HeroModels modules with Rhai. Each example typically requires its corresponding feature to be enabled.
|
|
|
|
- `calendar_example`: Working with calendars, events, and attendees (requires `calendar` feature).
|
|
- `flow_example`: Working with flows, steps, and signature requirements (requires `flow` feature).
|
|
- `finance_example`: Working with financial models (requires `finance` feature).
|
|
- *(Additional examples for `legal`, `projects`, `biz` would follow the same pattern if present).*
|
|
|
|
To run an example (e.g., `calendar_example`):
|
|
|
|
```bash
|
|
cargo run --example calendar_example --features calendar
|
|
```
|
|
*(Note: Examples in `Cargo.toml` already specify `required-features`, so simply `cargo run --example calendar_example` might suffice if those features are part of the default set or already enabled.)*
|
|
|
|
## Features
|
|
|
|
The crate uses feature flags to control which HeroModels modules are compiled and registered:
|
|
|
|
- `calendar`: Enables the Calendar module.
|
|
- `finance`: Enables the Finance module.
|
|
- `flow`: Enables the Flow module.
|
|
- `legal`: Enables the Legal module.
|
|
- `projects`: Enables the Projects module.
|
|
- `biz`: Enables the Business module.
|
|
|
|
The `default` features are `["calendar", "finance"]`. You can enable other modules by specifying them during the build or in your project's `Cargo.toml` if this `engine` crate is a dependency.
|
|
|
|
## Dependencies
|
|
|
|
Key dependencies include:
|
|
- `rhai`: The Rhai scripting engine.
|
|
- `heromodels`: Provides the core data models and database interaction logic, including the Rhai registration functions for each module.
|
|
- `heromodels_core`: Core utilities for HeroModels.
|
|
- `chrono`: For date/time utilities.
|
|
- `heromodels-derive`: Procedural macros used by HeroModels.
|
|
|
|
## License
|
|
|
|
This crate is part of the HeroModels project and shares its license.
|