78 lines
2.6 KiB
Rust
78 lines
2.6 KiB
Rust
use rhai::Engine;
|
|
use rhai_client::RhaiClient; // To submit tasks
|
|
use uuid::Uuid; // For generating task_id
|
|
|
|
use std::time::Duration;
|
|
use tokio::time::sleep;
|
|
use rhailib_worker::spawn_rhai_worker;
|
|
|
|
// Custom function for Rhai
|
|
fn add(a: i64, b: i64) -> i64 {
|
|
a + b
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
env_logger::init();
|
|
log::info!("Starting Math Worker Example...");
|
|
|
|
// 1. Configure and start the Rhai Worker with a custom engine
|
|
let mut math_engine = Engine::new();
|
|
math_engine.register_fn("add", add);
|
|
log::info!("Custom 'add' function registered with Rhai engine for Math Worker.");
|
|
|
|
let (shutdown_tx, shutdown_rx) = tokio::sync::mpsc::channel(1);
|
|
tokio::spawn(async move {
|
|
log::info!("Math Worker task starting...");
|
|
let _worker_handle = spawn_rhai_worker(
|
|
0,
|
|
"math_circle".to_string(),
|
|
math_engine,
|
|
"redis://127.0.0.1/".to_string(),
|
|
shutdown_rx,
|
|
false,
|
|
);
|
|
});
|
|
|
|
// Give the worker a moment to start and connect
|
|
sleep(Duration::from_secs(1)).await;
|
|
|
|
// 2. Use RhaiClient to submit a script to the "math_circle"
|
|
let client = RhaiClient::new("redis://127.0.0.1/")?;
|
|
let script_content = r#"
|
|
let x = 10;
|
|
let y = add(x, 32); // Use the custom registered function
|
|
print("Math script: 10 + 32 = " + y);
|
|
y // Return the result
|
|
"#;
|
|
|
|
log::info!("Submitting math script to 'math_circle' and awaiting result...");
|
|
|
|
let timeout_duration = Duration::from_secs(10);
|
|
let task_id = Uuid::new_v4().to_string();
|
|
|
|
match client.submit_script_and_await_result(
|
|
"math_circle",
|
|
script_content.to_string(),
|
|
task_id, // Pass the generated task_id
|
|
timeout_duration,
|
|
None
|
|
).await {
|
|
Ok(details) => {
|
|
log::info!("Math Worker Example: Task finished. Status: {}, Output: {:?}, Error: {:?}",
|
|
details.status, details.output, details.error);
|
|
if details.status == "completed" {
|
|
assert_eq!(details.output, Some("42".to_string()));
|
|
log::info!("Math Worker Example: Assertion for output 42 passed!");
|
|
Ok(())
|
|
} else {
|
|
log::error!("Math Worker Example: Task completed with error: {:?}", details.error);
|
|
Err(format!("Task failed with error: {:?}", details.error).into())
|
|
}
|
|
}
|
|
Err(e) => {
|
|
log::error!("Math Worker Example: Failed to get task result: {}", e);
|
|
Err(e.into())
|
|
}
|
|
}
|
|
} |