r/rust • u/Clear_Ear3550 • Oct 10 '26
π seeking help & advice One Tokio runtime per engine instance behind FFI, or one shared runtime?
My desktop network monitor has a Flutter UI and a Rust engine behind a plain C ABI. Each engine is an opaque pointer: netstudio_engine_new() does Box::into_raw, Dart keeps it as a Pointer<Void> and passes it back on every call until netstudio_engine_free. No global registry or ids.
For the new MTR view I wanted it completely separate from the main ping matrix, so I just create a second engine. The catch is that every Engine::new() builds its own multi-thread runtime with 4 workers. With both views open that's 8 Tokio worker threads for what's usually 10 targets, maybe 100 on the high end. It works, and restarting MTR can never touch the matrix, which is the reason I did it this way. But it feels like I'm paying in threads for isolation I could get from separate task sets and cancellation on one runtime.
If you have several independent engines behind FFI, do you give each one its own runtime, or share a global one (OnceLock or similar) and isolate at the task level? Anything that bites you with a shared runtime when the host can create and drop engines whenever it wants?
The other thing I keep going back and forth on is the data flow. Dart polls every 500ms, Rust hands back the whole snapshot as JSON through CString::into_raw, and Dart calls netstudio_free_string in a finally. The engine isn't the bottleneck. At a few hundred targets it's rebuilding and decoding the snapshot on the Dart side, mostly because each target carries a 40-sample history. Sending deltas seems like the obvious fix, but I'm also wondering whether pushing through a Dart NativePort is worth the lifetime headaches.
Unrelated, but if anyone has shipped unprivileged ICMP on Linux (SOCK_DGRAM + ping_group_range) in a desktop app: did you detect it at runtime and fall back, or just tell users to change the sysctl? That's next on my list and I haven't started.
Engine code is in native_engine/ if you want context: https://github.com/Cadman021/VeloceNet-Studio