mirror of
https://github.com/logos-messaging/nim-ffi.git
synced 2026-06-22 01:10:03 +00:00
80 lines
3.3 KiB
Rust
80 lines
3.3 KiB
Rust
// Rust client for the my_timer shared library built with nim-ffi + chronos.
|
|
//
|
|
// This file uses the generated `my_timer` crate, which wraps all the raw FFI
|
|
// boilerplate (extern "C" declarations, callback machinery, CBOR encode/decode).
|
|
//
|
|
// To regenerate the `rust_bindings` crate:
|
|
// nimble genbindings_rust
|
|
use std::time::Duration;
|
|
use my_timer::{
|
|
EchoRequest, JobSpec, MyTimerCtx, RetryPolicy, ScheduleConfig, TimerConfig,
|
|
};
|
|
|
|
fn main() {
|
|
let timeout = Duration::from_secs(5);
|
|
|
|
// ── 1. Create the timer service ────────────────────────────────────────
|
|
let ctx = MyTimerCtx::create(TimerConfig { name: "demo".into() }, timeout)
|
|
.expect("my_timer_create failed");
|
|
println!("[1] Context created");
|
|
|
|
// ── 2. Sync call: version ──────────────────────────────────────────────
|
|
let version = ctx.version().expect("my_timer_version failed");
|
|
println!("[2] Version (sync call, callback fired inline): {version}");
|
|
|
|
// ── 3. Async call: echo (200 ms delay) ────────────────────────────────
|
|
let echo = ctx
|
|
.echo(EchoRequest {
|
|
message: "hello from Rust".into(),
|
|
delay_ms: 200,
|
|
})
|
|
.expect("my_timer_echo failed");
|
|
println!(
|
|
"[3] Echo (async, 200 ms chronos delay): echoed={}, timerName={}",
|
|
echo.echoed, echo.timer_name
|
|
);
|
|
|
|
// ── 4. A second echo ──────────────────────────────────────────────────
|
|
let echo2 = ctx
|
|
.echo(EchoRequest {
|
|
message: "second request".into(),
|
|
delay_ms: 50,
|
|
})
|
|
.expect("second my_timer_echo failed");
|
|
println!("[4] Echo: echoed={}, timerName={}", echo2.echoed, echo2.timer_name);
|
|
|
|
// ── 5. Call with three complex parameters ─────────────────────────────
|
|
// Each param is its own first-class Rust struct generated by the
|
|
// bindings. The nim-ffi macro packs all three into one CBOR envelope on
|
|
// the wire — from the caller's perspective, this is just a typed call.
|
|
let schedule = ctx
|
|
.schedule(
|
|
JobSpec {
|
|
name: "nightly-rollup".into(),
|
|
payload: vec!["rollup".into(), "v2".into()],
|
|
priority: 10,
|
|
},
|
|
RetryPolicy {
|
|
max_attempts: 3,
|
|
backoff_ms: 500,
|
|
retry_on: vec!["timeout".into(), "5xx".into()],
|
|
},
|
|
ScheduleConfig {
|
|
start_at_ms: 1_000,
|
|
interval_ms: 15_000,
|
|
jitter: Some(250),
|
|
},
|
|
)
|
|
.expect("my_timer_schedule failed");
|
|
println!(
|
|
"[5] Schedule (3 complex params): jobId={}, willRunCount={}, firstRunAtMs={}, effectiveBackoffMs={}",
|
|
schedule.job_id,
|
|
schedule.will_run_count,
|
|
schedule.first_run_at_ms,
|
|
schedule.effective_backoff_ms,
|
|
);
|
|
|
|
println!("\nDone. The Nim FFI thread and watchdog are still running.");
|
|
println!("(In a real app, call my_timer_destroy to join them gracefully.)");
|
|
}
|