From 747df1617c9815ba1d37be79b865623d441e9117 Mon Sep 17 00:00:00 2001 From: magine Date: Wed, 3 Jan 2024 17:44:45 +0800 Subject: [PATCH] Add an example of native provider --- .github/workflows/qaci.yml | 7 +- Cargo.lock | 97 ++++++++++++++------------ Cargo.toml | 4 +- core/Cargo.toml | 2 +- examples/ffi/rings.py | 1 - examples/native/Cargo.toml | 14 ++++ examples/native/src/main.rs | 87 +++++++++++++++++++++++ node/Cargo.toml | 2 +- node/src/backend/browser.rs | 26 +++++-- node/src/backend/ffi.rs | 84 ++++++++++++---------- node/src/backend/mod.rs | 10 +-- node/src/backend/native/extension.rs | 2 +- node/src/backend/native/mod.rs | 9 +-- node/src/backend/native/service/mod.rs | 20 ++++-- node/src/backend/types.rs | 6 +- node/src/processor.rs | 6 +- node/src/provider/mod.rs | 8 ++- rpc/Cargo.toml | 2 +- transport/Cargo.toml | 2 +- 19 files changed, 271 insertions(+), 118 deletions(-) create mode 100644 examples/native/Cargo.toml create mode 100644 examples/native/src/main.rs diff --git a/.github/workflows/qaci.yml b/.github/workflows/qaci.yml index e84e42337..eb2c33223 100644 --- a/.github/workflows/qaci.yml +++ b/.github/workflows/qaci.yml @@ -94,7 +94,7 @@ jobs: run: cargo test --all --verbose build_ffi: - name: Build and test for ffi + name: Build and test for examples timeout-minutes: 20 strategy: matrix: @@ -124,9 +124,12 @@ jobs: with: python-version: "3.11" - - name: Smoke test + - name: Smoke test ffi run: pip install wheel && pip install web3 cffi && python examples/ffi/rings.py + - name: Smoke test native + run: cargo run -p rings-native-example + rustfmt_and_clippy: name: Check rustfmt style && run clippy timeout-minutes: 10 diff --git a/Cargo.lock b/Cargo.lock index 9fb8e46bf..3fc63a58f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -331,7 +331,7 @@ checksum = "0e97ce7de6cf12de5d7226c73f5ba9811622f4db3a5b91b55c53e987e5f91cba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -353,18 +353,18 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] name = "async-trait" -version = "0.1.73" +version = "0.1.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" +checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -758,7 +758,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -1145,7 +1145,7 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -1167,7 +1167,7 @@ checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" dependencies = [ "darling_core 0.20.1", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -1310,7 +1310,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -1478,7 +1478,7 @@ dependencies = [ "darling 0.20.1", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -1709,7 +1709,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -2338,9 +2338,9 @@ checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" [[package]] name = "libc" -version = "0.2.147" +version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" +checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "libm" @@ -2513,9 +2513,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.7" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eebffdb73fe72e917997fad08bdbf31ac50b0fa91cec93e69a0662e4264d454c" +checksum = "8f3d0b296e374a4e6f3c7b0a1f5a51d748a0d34c85e7dc48fc3fa9a87657fe09" dependencies = [ "libc", "wasi 0.11.0+wasi-snapshot-preview1", @@ -2918,7 +2918,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -3057,9 +3057,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.66" +version = "1.0.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" +checksum = "2de98502f212cfcea8d0bb305bd0f49d7ebdd75b64ba0a68f937d888f4e0d6db" dependencies = [ "unicode-ident", ] @@ -3139,7 +3139,7 @@ dependencies = [ "itertools", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -3173,9 +3173,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.32" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -3529,7 +3529,7 @@ dependencies = [ [[package]] name = "rings-core" -version = "0.5.1" +version = "0.5.2" dependencies = [ "arrayref", "async-channel", @@ -3591,18 +3591,29 @@ dependencies = [ [[package]] name = "rings-derive" -version = "0.5.1" +version = "0.5.2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", "wasm-bindgen-macro-support", "wasmer", ] +[[package]] +name = "rings-native-example" +version = "0.5.2" +dependencies = [ + "async-trait", + "rings-core", + "rings-node", + "rings-rpc", + "tokio", +] + [[package]] name = "rings-node" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "arrayref", @@ -3663,7 +3674,7 @@ dependencies = [ [[package]] name = "rings-rpc" -version = "0.5.1" +version = "0.5.2" dependencies = [ "async-trait", "base64 0.13.1", @@ -3683,7 +3694,7 @@ dependencies = [ [[package]] name = "rings-transport" -version = "0.5.1" +version = "0.5.2" dependencies = [ "async-trait", "bincode", @@ -4027,7 +4038,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -4225,9 +4236,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.3" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877" +checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" dependencies = [ "libc", "windows-sys 0.48.0", @@ -4336,9 +4347,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.29" +version = "2.0.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" +checksum = "89456b690ff72fddcecf231caedbe615c59480c93358a93dfae7fc29e3ebbf0e" dependencies = [ "proc-macro2", "quote", @@ -4441,7 +4452,7 @@ checksum = "6bb623b56e39ab7dcd4b1b98bb6c8f8d907ed255b18de254088016b27a8ee19b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -4529,9 +4540,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.32.0" +version = "1.35.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" +checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" dependencies = [ "backtrace", "bytes", @@ -4541,20 +4552,20 @@ dependencies = [ "parking_lot 0.12.1", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.3", + "socket2 0.5.5", "tokio-macros", "windows-sys 0.48.0", ] [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -4708,7 +4719,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] [[package]] @@ -5013,7 +5024,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", "wasm-bindgen-shared", ] @@ -5070,7 +5081,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5916,5 +5927,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.46", ] diff --git a/Cargo.toml b/Cargo.toml index 769a90265..0e3bd0ca2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["core", "transport", "node", "rpc", "derive"] +members = ["core", "transport", "node", "rpc", "derive", "examples/native"] [workspace.package] version = "0.5.2" @@ -10,10 +10,12 @@ authors = ["RND "] repository = "https://github.com/RingsNetwork/rings-node" [workspace.dependencies] +async-trait = "0.1.77" js-sys = "0.3.64" jsonrpc-core = "18.0.0" rings-core = { path = "core", default-features = false } rings-derive = { path = "derive", default-features = false } +rings-node = { path = "node" } rings-rpc = { path = "rpc", default-features = false } rings-transport = { path = "transport" } serde-wasm-bindgen = "0.6.1" diff --git a/core/Cargo.toml b/core/Cargo.toml index efd58fe01..6b897740b 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -47,7 +47,7 @@ arrayref = "0.3.6" async-lock = "2.5.0" async-recursion = "1.0.0" async-stream = "0.3.2" -async-trait = "0.1.52" +async-trait = { workspace = true } base58 = "0.2.0" base58-monero = { version = "0.3", default-features = false, features = ["check"] } bincode = "1.3.3" diff --git a/examples/ffi/rings.py b/examples/ffi/rings.py index ac66b5720..1fb071aa8 100644 --- a/examples/ffi/rings.py +++ b/examples/ffi/rings.py @@ -1,4 +1,3 @@ - import platform import re import time diff --git a/examples/native/Cargo.toml b/examples/native/Cargo.toml new file mode 100644 index 000000000..198ff88d1 --- /dev/null +++ b/examples/native/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rings-native-example" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +[dependencies] +async-trait = { workspace = true } +rings-core = { workspace = true } +rings-node = { workspace = true } +rings-rpc = { workspace = true } +tokio = { version = "1.13.0", features = ["full"] } diff --git a/examples/native/src/main.rs b/examples/native/src/main.rs new file mode 100644 index 000000000..6436e681a --- /dev/null +++ b/examples/native/src/main.rs @@ -0,0 +1,87 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use rings_core::dht::Did; +use rings_core::ecc::SecretKey; +use rings_core::message::MessagePayload; +use rings_core::session::SessionSkBuilder; +use rings_core::storage::PersistenceStorage; +use rings_node::backend::types::BackendMessage; +use rings_node::backend::types::MessageHandler; +use rings_node::backend::Backend; +use rings_node::processor::ProcessorBuilder; +use rings_node::processor::ProcessorConfig; +use rings_node::provider::Provider; +use rings_rpc::method::Method; +use rings_rpc::protos::rings_node::*; + +struct BackendBehaviour; + +#[async_trait] +impl MessageHandler for BackendBehaviour { + async fn handle_message( + &self, + _provider: Arc, + _ctx: &MessagePayload, + msg: &BackendMessage, + ) -> Result<(), Box> { + println!("Received message: {:?}", msg); + Ok(()) + } +} + +#[tokio::main] +async fn main() { + // Generate a random secret key and its did. + let key = SecretKey::random(); + let did = Did::from(key.address()); + + // Build SessionSk of node in a safely way. + // You can also use `SessionSk::new_with_key(&key)` directly. + let mut skb = SessionSkBuilder::new(did.to_string(), "secp256k1".to_string()); + let sig = key.sign(&skb.unsigned_proof()); + skb = skb.set_session_sig(sig.to_vec()); + let sk = skb.build().unwrap(); + + // Build processor + let config = ProcessorConfig::new("stun://stun.l.google.com:19302".to_string(), sk, 3); + let storage_path = PersistenceStorage::random_path("./tmp"); + let storage = PersistenceStorage::new_with_path(storage_path.as_str()) + .await + .unwrap(); + let processor = Arc::new( + ProcessorBuilder::from_config(&config) + .unwrap() + .storage(storage) + .build() + .unwrap(), + ); + + // Wrap api with provider + let provider = Arc::new(Provider::from_processor(processor)); + + // Setup your callback handler. + let backend = Arc::new(Backend::new(provider.clone(), Box::new(BackendBehaviour))); + provider.set_swarm_callback(backend).unwrap(); + + // Listen messages from peers. + let listening_provider = provider.clone(); + tokio::spawn(async move { listening_provider.listen().await }); + + // Invoke apis of node. + println!("\nrequest NodeInfo api..."); + let resp = provider + .request(Method::NodeInfo, NodeInfoRequest {}) + .await + .unwrap(); + println!("NodeInfo: {:?}", resp); + + println!("\nrequest CreateOffer api..."); + let resp = provider + .request(Method::CreateOffer, CreateOfferRequest { + did: "0x11E807fcc88dD319270493fB2e822e388Fe36ab0".to_string(), + }) + .await + .unwrap(); + println!("CreateOffer: {:?}", resp); +} diff --git a/node/Cargo.toml b/node/Cargo.toml index cbe9581aa..e20537fca 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -67,7 +67,7 @@ browser_chrome_test = ["browser"] [dependencies] anyhow = "1.0.45" arrayref = "0.3.6" -async-trait = "0.1.52" +async-trait = { workspace = true } base64 = { version = "0.13.0" } bincode = "1.3.3" bytes = { version = "1.2.1", features = ["serde"] } diff --git a/node/src/backend/browser.rs b/node/src/backend/browser.rs index 810a2a661..3ba951a74 100644 --- a/node/src/backend/browser.rs +++ b/node/src/backend/browser.rs @@ -1,5 +1,6 @@ #![warn(missing_docs)] //! BackendBehaviour implementation for browser +use std::result::Result; use std::sync::Arc; use async_trait::async_trait; @@ -12,7 +13,7 @@ use wasm_bindgen::JsValue; use crate::backend::types::BackendMessage; use crate::backend::types::MessageHandler; -use crate::error::Result; +use crate::error::Error; use crate::provider::Provider; /// BackendBehaviour is a context instance for handling backend message for browser @@ -41,17 +42,13 @@ impl BackendBehaviour { extension_message_handler, } } -} -#[cfg_attr(feature = "browser", async_trait(?Send))] -#[cfg_attr(not(feature = "browser"), async_trait)] -impl MessageHandler for BackendBehaviour { - async fn handle_message( + async fn do_handle_message( &self, provider: Arc, payload: &MessagePayload, msg: &BackendMessage, - ) -> Result<()> { + ) -> Result<(), Error> { let provider = provider.clone().as_ref().clone(); let ctx = js_value::serialize(&payload)?; match msg { @@ -79,3 +76,18 @@ impl MessageHandler for BackendBehaviour { Ok(()) } } + +#[cfg_attr(feature = "browser", async_trait(?Send))] +#[cfg_attr(not(feature = "browser"), async_trait)] +impl MessageHandler for BackendBehaviour { + async fn handle_message( + &self, + provider: Arc, + payload: &MessagePayload, + msg: &BackendMessage, + ) -> Result<(), Box> { + self.do_handle_message(provider, payload, msg) + .await + .map_err(|e| e.into()) + } +} diff --git a/node/src/backend/ffi.rs b/node/src/backend/ffi.rs index 052da09d6..37073eefa 100644 --- a/node/src/backend/ffi.rs +++ b/node/src/backend/ffi.rs @@ -4,6 +4,7 @@ //! use std::ffi::c_char; use std::ffi::CString; +use std::result::Result; use std::sync::Arc; use async_trait::async_trait; @@ -11,7 +12,7 @@ use tokio::runtime::Runtime; use crate::backend::types::BackendMessage; use crate::backend::types::MessageHandler; -use crate::error::Result; +use crate::error::Error; use crate::prelude::MessagePayload; use crate::provider::ffi::ProviderPtr; use crate::provider::ffi::ProviderWithRuntime; @@ -62,6 +63,28 @@ pub struct FFIBackendBehaviourWithRuntime { runtime: Arc, } +macro_rules! handle_backend_message { + ($self:ident, $provider:ident, $handler:ident, $payload: ident, $message:ident) => { + if let Some(handler) = &$self.behaviour.$handler { + let rt = $self.runtime.clone(); + + let provider_with_runtime = ProviderWithRuntime::new($provider.clone(), rt.clone()); + provider_with_runtime.check_arc(); + let provider_ptr: ProviderPtr = (&provider_with_runtime).into(); + let payload = serde_json::to_string(&$payload)?; + let message = serde_json::to_string(&$message)?; + let payload = CString::new(payload)?; + let message = CString::new(message)?; + handler( + $self as *const FFIBackendBehaviourWithRuntime, + &provider_ptr as *const ProviderPtr, + payload.as_ptr(), + message.as_ptr(), + ); + } + }; +} + impl FFIBackendBehaviourWithRuntime { /// Create a new instance pub fn new(behaviour: FFIBackendBehaviour, runtime: Arc) -> Self { @@ -70,6 +93,26 @@ impl FFIBackendBehaviourWithRuntime { runtime: runtime.clone(), } } + + async fn do_handle_message( + &self, + provider: Arc, + payload: &MessagePayload, + msg: &BackendMessage, + ) -> Result<(), Error> { + match msg { + BackendMessage::PlainText(m) => { + handle_backend_message!(self, provider, paintext_message_handler, payload, m) + } + BackendMessage::Extension(m) => { + handle_backend_message!(self, provider, extension_message_handler, payload, m) + } + BackendMessage::ServiceMessage(m) => { + handle_backend_message!(self, provider, service_message_handler, payload, m) + } + } + Ok(()) + } } /// Backend behaviour for FFI @@ -107,28 +150,6 @@ pub extern "C" fn new_ffi_backend_behaviour( } } -macro_rules! handle_backend_message { - ($self:ident, $provider:ident, $handler:ident, $payload: ident, $message:ident) => { - if let Some(handler) = &$self.behaviour.$handler { - let rt = $self.runtime.clone(); - - let provider_with_runtime = ProviderWithRuntime::new($provider.clone(), rt.clone()); - provider_with_runtime.check_arc(); - let provider_ptr: ProviderPtr = (&provider_with_runtime).into(); - let payload = serde_json::to_string(&$payload)?; - let message = serde_json::to_string(&$message)?; - let payload = CString::new(payload)?; - let message = CString::new(message)?; - handler( - $self as *const FFIBackendBehaviourWithRuntime, - &provider_ptr as *const ProviderPtr, - payload.as_ptr(), - message.as_ptr(), - ); - } - }; -} - #[async_trait] impl MessageHandler for FFIBackendBehaviourWithRuntime { async fn handle_message( @@ -136,18 +157,9 @@ impl MessageHandler for FFIBackendBehaviourWithRuntime { provider: Arc, payload: &MessagePayload, msg: &BackendMessage, - ) -> Result<()> { - match msg { - BackendMessage::PlainText(m) => { - handle_backend_message!(self, provider, paintext_message_handler, payload, m) - } - BackendMessage::Extension(m) => { - handle_backend_message!(self, provider, extension_message_handler, payload, m) - } - BackendMessage::ServiceMessage(m) => { - handle_backend_message!(self, provider, service_message_handler, payload, m) - } - } - Ok(()) + ) -> Result<(), Box> { + self.do_handle_message(provider, payload, msg) + .await + .map_err(|e| e.into()) } } diff --git a/node/src/backend/mod.rs b/node/src/backend/mod.rs index 54b0fef4c..09d32c372 100644 --- a/node/src/backend/mod.rs +++ b/node/src/backend/mod.rs @@ -2,6 +2,7 @@ //! This module provide basic mechanism. pub mod types; +use std::result::Result; use std::sync::Arc; use async_trait::async_trait; @@ -12,7 +13,6 @@ use rings_core::swarm::callback::SwarmCallback; use crate::backend::types::BackendMessage; use crate::backend::types::MessageHandler; -use crate::error::Result; use crate::provider::Provider; #[cfg(feature = "browser")] @@ -45,7 +45,7 @@ impl Backend { &self, payload: &MessagePayload, msg: &BackendMessage, - ) -> Result<()> { + ) -> Result<(), Box> { let provider = self.provider.clone(); self.handler.handle_message(provider, payload, msg).await } @@ -54,11 +54,7 @@ impl Backend { #[cfg_attr(feature = "browser", async_trait(?Send))] #[cfg_attr(not(feature = "browser"), async_trait)] impl SwarmCallback for Backend { - async fn on_inbound( - &self, - - payload: &MessagePayload, - ) -> std::result::Result<(), Box> { + async fn on_inbound(&self, payload: &MessagePayload) -> Result<(), Box> { let data: Message = payload.transaction.data()?; let Message::CustomMessage(CustomMessage(msg)) = data else { diff --git a/node/src/backend/native/extension.rs b/node/src/backend/native/extension.rs index 4eaf10212..befa5cf69 100644 --- a/node/src/backend/native/extension.rs +++ b/node/src/backend/native/extension.rs @@ -149,7 +149,7 @@ impl MessageHandler for Extension { provider: Arc, _ctx: &MessagePayload, data: &bytes::Bytes, - ) -> Result<()> { + ) -> std::result::Result<(), Box> { for h in &self.handlers { h.call(data.clone(), provider.clone())?; } diff --git a/node/src/backend/native/mod.rs b/node/src/backend/native/mod.rs index 3c17b33d4..1edc8bc93 100644 --- a/node/src/backend/native/mod.rs +++ b/node/src/backend/native/mod.rs @@ -14,6 +14,7 @@ pub mod extension; pub mod service; +use std::result::Result; use std::sync::Arc; use async_trait::async_trait; @@ -26,7 +27,7 @@ use crate::backend::native::service::ServiceConfig; use crate::backend::native::service::ServiceProvider; use crate::backend::types::BackendMessage; use crate::backend::types::MessageHandler; -use crate::error::Result; +use crate::error::Error; use crate::provider::Provider; /// BackendConfig including services config and extension config @@ -51,14 +52,14 @@ impl MessageHandler for BackendBehaviour { provider: Arc, payload: &MessagePayload, msg: &BackendMessage, - ) -> Result<()> { + ) -> Result<(), Box> { self.handle_backend_message(provider, payload, msg).await } } impl BackendBehaviour { /// Create a new BackendBehaviour instance with config - pub async fn new(config: BackendConfig) -> Result { + pub async fn new(config: BackendConfig) -> Result { Ok(Self { server: ServiceProvider::new(config.services), extension: Extension::new(&config.extensions).await?, @@ -79,7 +80,7 @@ impl BackendBehaviour { provider: Arc, payload: &MessagePayload, msg: &BackendMessage, - ) -> Result<()> { + ) -> Result<(), Box> { match msg { BackendMessage::Extension(data) => { self.extension.handle_message(provider, payload, data).await diff --git a/node/src/backend/native/service/mod.rs b/node/src/backend/native/service/mod.rs index 70ca62d55..59f9c46d1 100644 --- a/node/src/backend/native/service/mod.rs +++ b/node/src/backend/native/service/mod.rs @@ -70,16 +70,14 @@ impl ServiceProvider { tunnels: DashMap::new(), } } + fn service(&self, name: &str) -> Option<&ServiceConfig> { self.services .iter() .find(|x| x.name.eq_ignore_ascii_case(name)) } -} -#[async_trait::async_trait] -impl MessageHandler for ServiceProvider { - async fn handle_message( + async fn do_handle_message( &self, provider: Arc, ctx: &MessagePayload, @@ -141,6 +139,20 @@ impl MessageHandler for ServiceProvider { } } +#[async_trait::async_trait] +impl MessageHandler for ServiceProvider { + async fn handle_message( + &self, + provider: Arc, + ctx: &MessagePayload, + msg: &ServiceMessage, + ) -> std::result::Result<(), Box> { + self.do_handle_message(provider, ctx, msg) + .await + .map_err(|e| e.into()) + } +} + async fn handle_http_request(addr: SocketAddr, req: &HttpRequest) -> Result { let url = format!("http://{}/{}", addr, req.path.trim_start_matches('/')); tracing::info!("Handle http request on url: {:?} start", url); diff --git a/node/src/backend/types.rs b/node/src/backend/types.rs index 08e688f30..0d69b2117 100644 --- a/node/src/backend/types.rs +++ b/node/src/backend/types.rs @@ -10,7 +10,7 @@ use rings_rpc::protos::rings_node::SendBackendMessageRequest; use serde::Deserialize; use serde::Serialize; -use crate::error::Result; +use crate::error::Error; use crate::provider::Provider; /// TunnelId type, use uuid. @@ -121,7 +121,7 @@ pub trait MessageHandler { provider: Arc, ctx: &MessagePayload, data: &T, - ) -> Result<()>; + ) -> Result<(), Box>; } impl From for BackendMessage { @@ -147,7 +147,7 @@ impl BackendMessage { pub fn into_send_backend_message_request( self, destination_did: impl ToString, - ) -> Result { + ) -> Result { Ok(SendBackendMessageRequest { destination_did: destination_did.to_string(), data: serde_json::to_string(&self)?, diff --git a/node/src/processor.rs b/node/src/processor.rs index 9cf12b914..635a51aa2 100644 --- a/node/src/processor.rs +++ b/node/src/processor.rs @@ -5,8 +5,6 @@ use std::str::FromStr; use std::sync::Arc; -use futures::future::Join; -use futures::Future; use rings_rpc::protos::rings_node::*; use rings_transport::core::transport::ConnectionInterface; use serde::Deserialize; @@ -268,14 +266,14 @@ impl ProcessorBuilder { impl Processor { /// Listen processor message - pub fn listen(&self) -> Join { + pub async fn listen(&self) { let swarm = self.swarm.clone(); let message_listener = async { swarm.listen().await }; let stb = self.stabilization.clone(); let stabilization = async { stb.wait().await }; - futures::future::join(message_listener, stabilization) + futures::future::join(message_listener, stabilization).await; } } diff --git a/node/src/provider/mod.rs b/node/src/provider/mod.rs index 6409bd1a6..5f3fa8a0e 100644 --- a/node/src/provider/mod.rs +++ b/node/src/provider/mod.rs @@ -127,7 +127,8 @@ impl Provider { Self::new_provider_with_storage_internal(config, "rings-node".to_string()).await } - pub(crate) fn set_swarm_callback(&self, callback: SharedSwarmCallback) -> Result<()> { + /// Set callback for swarm. + pub fn set_swarm_callback(&self, callback: SharedSwarmCallback) -> Result<()> { self.processor .swarm .set_callback(callback) @@ -163,4 +164,9 @@ impl Provider { let params = serde_json::to_value(params)?; self.request_internal(method.to_string(), params).await } + + /// Listen messages + pub async fn listen(&self) { + self.processor.listen().await; + } } diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index be4880565..d2829f464 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -21,7 +21,7 @@ std = ["rings-core/default", "reqwest"] wasm = ["rings-core/wasm", "reqwest-wasm"] [dependencies] -async-trait = "0.1.73" +async-trait = { workspace = true } base64 = { version = "0.13.0" } bytes = "1.5.0" http = "0.2.6" diff --git a/transport/Cargo.toml b/transport/Cargo.toml index 4b2a9f349..f4cd38f77 100644 --- a/transport/Cargo.toml +++ b/transport/Cargo.toml @@ -48,7 +48,7 @@ web-sys = { version = "0.3.64", optional = true, features = [ ] } # Common dependencies -async-trait = "0.1.73" +async-trait = { workspace = true } bincode = "1.3.3" bytes = { version = "1.4.0", features = ["serde"] } chrono = { version = "0.4.30", features = ["wasmbind"] }