db/heromodels/examples/finance_rhai/example.rs
2025-05-22 03:57:03 +03:00

110 lines
3.6 KiB
Rust

use rhai::{Engine, Scope, EvalAltResult};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::fs;
// Import the models and the registration function
use heromodels::models::finance::account::Account;
use heromodels::models::finance::asset::{Asset};
use heromodels::models::finance::marketplace::{Listing};
use heromodels::models::finance::rhai::register_rhai_engine_functions;
// Define a simple in-memory mock database for the example
#[derive(Clone, Debug)]
pub struct MockDb {
pub accounts: Arc<Mutex<HashMap<u32, Account>>>,
pub assets: Arc<Mutex<HashMap<u32, Asset>>>,
pub listings: Arc<Mutex<HashMap<u32, Listing>>>,
// Bids are often part of Listings, so a separate HashMap for Bids might not be needed
// unless we want to query bids globally by a unique bid ID.
}
impl MockDb {
fn new() -> Self {
Self {
accounts: Arc::new(Mutex::new(HashMap::new())),
assets: Arc::new(Mutex::new(HashMap::new())),
listings: Arc::new(Mutex::new(HashMap::new())),
}
}
}
fn main() -> Result<(), Box<EvalAltResult>> {
println!("--- Finance Rhai Example ---");
let mut engine = Engine::new();
let mut scope = Scope::new();
let mock_db = Arc::new(MockDb::new());
// Register finance functions and types with the engine
register_rhai_engine_functions(
&mut engine,
Arc::clone(&mock_db.accounts),
Arc::clone(&mock_db.assets),
Arc::clone(&mock_db.listings)
);
println!("Rhai functions registered.");
scope.push("db_instance", mock_db.clone());
let script_path = "examples/finance_rhai/finance.rhai";
println!("Loading script: {}", script_path);
let script = match fs::read_to_string(script_path) {
Ok(s) => s,
Err(e) => {
eprintln!("Error reading script file '{}': {}", script_path, e);
return Err(Box::new(EvalAltResult::ErrorSystem(
"Failed to read script".to_string(),
Box::new(e),
)));
}
};
println!("Executing script...");
match engine.run_with_scope(&mut scope, &script) {
Ok(_) => println!("Script executed successfully!"),
Err(e) => {
eprintln!("Script execution failed: {:?}", e);
return Err(e);
}
}
// Print final state of Accounts
let final_accounts = mock_db.accounts.lock().unwrap();
println!("\n--- Final Mock DB State (Accounts) ---");
if final_accounts.is_empty() {
println!("No accounts in mock DB.");
}
for (id, account) in final_accounts.iter() {
println!("Account ID: {}, Name: '{}', User ID: {}, Assets: {}",
id, account.name, account.user_id, account.assets.len());
}
// Print final state of Assets
let final_assets = mock_db.assets.lock().unwrap();
println!("\n--- Final Mock DB State (Assets) ---");
if final_assets.is_empty() {
println!("No assets in mock DB.");
}
for (id, asset) in final_assets.iter() {
println!("Asset ID: {}, Name: '{}', Amount: {}, Type: {:?}",
id, asset.name, asset.amount, asset.asset_type);
}
// Print final state of Listings
let final_listings = mock_db.listings.lock().unwrap();
println!("\n--- Final Mock DB State (Listings) ---");
if final_listings.is_empty() {
println!("No listings in mock DB.");
}
for (id, listing) in final_listings.iter() {
println!(
"Listing ID: {}, Title: '{}', Type: {:?}, Status: {:?}, Price: {}, Bids: {}",
id, listing.title, listing.listing_type, listing.status, listing.price, listing.bids.len()
);
}
Ok(())
}