From 25d0d296c1c265af3e051959d66513e34868c2d6 Mon Sep 17 00:00:00 2001 From: Daniel Sanchez Quiros Date: Fri, 16 Feb 2024 08:40:18 +0100 Subject: [PATCH] Update event callback idea --- waku-bindings/src/node/mod.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/waku-bindings/src/node/mod.rs b/waku-bindings/src/node/mod.rs index c45e1ee..cdccb8e 100644 --- a/waku-bindings/src/node/mod.rs +++ b/waku-bindings/src/node/mod.rs @@ -9,10 +9,11 @@ mod relay; // std pub use aes_gcm::{Aes256Gcm, Key}; pub use multiaddr::Multiaddr; +use once_cell::sync::Lazy; pub use secp256k1::{PublicKey, SecretKey}; use std::sync::{Arc, Mutex}; use std::time::Duration; -use once_cell::sync::Lazy; +use tokio::sync::broadcast; // crates use libc::c_void; // internal @@ -30,12 +31,12 @@ pub struct OpaqueWakunodePtr { unsafe impl Send for OpaqueWakunodePtr {} /// Handle to the underliying waku node -pub struct WakuNodeHandle { +pub struct WakuNodeHandle { ctx: Arc>, - callback: Lazy>>, + events_channel: broadcast::Receiver, } -impl WakuNodeHandle { +impl WakuNodeHandle { /// Start a Waku node mounting all the protocols that were enabled during the Waku node instantiation. /// as per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_start) pub fn start(&self) -> Result<()> { @@ -85,19 +86,24 @@ impl WakuNodeHandle { relay::waku_relay_unsubscribe(ctx.obj_ptr, pubsub_topic) } - pub fn set_event_callback(&self, f: F) { + fn set_event_callback(&self, f: F) { let mut ctx = self.ctx.lock().unwrap(); - *self.callback.lock().unwrap() = Box::new(f); - events::waku_set_event_callback(ctx.obj_ptr, &self.callback) + events::waku_set_event_callback(ctx.obj_ptr, f) } } /// Spawn a new Waku node with the given configuration (default configuration if `None` provided) /// as per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_newchar-jsonconfig) -pub fn waku_new(config: Option) -> Result { +pub fn waku_new(config: Option) -> Result> { let obj_ptr = management::waku_new(config)?; - Ok(WakuNodeHandle { + let (sender, receiver) = broadcast::channel(100); + let mut node = WakuNodeHandle:: { ctx: Arc::new(Mutex::new(OpaqueWakunodePtr { obj_ptr })), - callback: Lazy::new(|| Mutex::new(Box::new(|_| {}))), - }) + events_channel: receiver, + }; + node.set_event_callback(move |event| { + // use channel here + sender; + }); + Ok(node) }