diff --git a/Cargo.lock b/Cargo.lock index 55de3d50f9..db32920bdb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4436,7 +4436,7 @@ version = "1.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ - "cfg-if 1.0.0", + "cfg-if 0.1.10", "static_assertions", ] diff --git a/ci/valgrind-check/src/pub_sub/bin/z_pub_sub.rs b/ci/valgrind-check/src/pub_sub/bin/z_pub_sub.rs index d44215cac5..2091f833a1 100644 --- a/ci/valgrind-check/src/pub_sub/bin/z_pub_sub.rs +++ b/ci/valgrind-check/src/pub_sub/bin/z_pub_sub.rs @@ -13,7 +13,7 @@ // use std::time::Duration; use zenoh::config::Config; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; #[tokio::main] async fn main() { @@ -23,15 +23,11 @@ async fn main() { let sub_key_expr = KeyExpr::try_from("test/valgrind/**").unwrap(); println!("Declaring Publisher on '{pub_key_expr}'..."); - let pub_session = zenoh::open(Config::default()).res().await.unwrap(); - let publisher = pub_session - .declare_publisher(&pub_key_expr) - .res() - .await - .unwrap(); + let pub_session = zenoh::open(Config::default()).await.unwrap(); + let publisher = pub_session.declare_publisher(&pub_key_expr).await.unwrap(); println!("Declaring Subscriber on '{sub_key_expr}'..."); - let sub_session = zenoh::open(Config::default()).res().await.unwrap(); + let sub_session = zenoh::open(Config::default()).await.unwrap(); let _subscriber = sub_session .declare_subscriber(&sub_key_expr) .callback(|sample| { @@ -45,7 +41,6 @@ async fn main() { .unwrap_or_else(|e| format!("{}", e)) ); }) - .res() .await .unwrap(); @@ -53,7 +48,7 @@ async fn main() { tokio::time::sleep(Duration::from_secs(1)).await; let buf = format!("[{idx:4}] data"); println!("Putting Data ('{}': '{}')...", &pub_key_expr, buf); - publisher.put(buf).res().await.unwrap(); + publisher.put(buf).await.unwrap(); } tokio::time::sleep(Duration::from_secs(1)).await; diff --git a/ci/valgrind-check/src/queryable_get/bin/z_queryable_get.rs b/ci/valgrind-check/src/queryable_get/bin/z_queryable_get.rs index 364617eb2a..43cb038f94 100644 --- a/ci/valgrind-check/src/queryable_get/bin/z_queryable_get.rs +++ b/ci/valgrind-check/src/queryable_get/bin/z_queryable_get.rs @@ -14,7 +14,7 @@ use std::convert::TryFrom; use std::time::Duration; use zenoh::config::Config; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; #[tokio::main] async fn main() { @@ -24,7 +24,7 @@ async fn main() { let get_selector = Selector::try_from("test/valgrind/**").unwrap(); println!("Declaring Queryable on '{queryable_key_expr}'..."); - let queryable_session = zenoh::open(Config::default()).res().await.unwrap(); + let queryable_session = zenoh::open(Config::default()).await.unwrap(); let _queryable = queryable_session .declare_queryable(queryable_key_expr.clone()) .callback(move |query| { @@ -33,18 +33,16 @@ async fn main() { zenoh_runtime::ZRuntime::Application.block_in_place(async move { query .reply(queryable_key_expr, query.value().unwrap().payload().clone()) - .res() .await .unwrap(); }); }) .complete(true) - .res() .await .unwrap(); println!("Declaring Get session for '{get_selector}'..."); - let get_session = zenoh::open(Config::default()).res().await.unwrap(); + let get_session = zenoh::open(Config::default()).await.unwrap(); for idx in 0..5 { tokio::time::sleep(Duration::from_secs(1)).await; @@ -53,7 +51,6 @@ async fn main() { .get(&get_selector) .value(idx) .target(QueryTarget::All) - .res() .await .unwrap(); while let Ok(reply) = replies.recv_async().await { diff --git a/commons/zenoh-core/src/lib.rs b/commons/zenoh-core/src/lib.rs index e15ff1d3bf..19cf3751ff 100644 --- a/commons/zenoh-core/src/lib.rs +++ b/commons/zenoh-core/src/lib.rs @@ -20,7 +20,7 @@ pub use lazy_static::lazy_static; pub mod macros; -use std::future::{Future, Ready}; +use std::future::{Future, IntoFuture, Ready}; // Re-exports after moving ZError/ZResult to zenoh-result pub use zenoh_result::{bail, to_zerror, zerror}; @@ -30,12 +30,34 @@ pub mod zresult { pub use zresult::Error; pub use zresult::ZResult as Result; +/// A resolvable execution, either sync or async pub trait Resolvable { type To: Sized + Send; } +/// Trick used to mark `::IntoFuture` bound as Send +#[doc(hidden)] +pub trait IntoSendFuture: Resolvable { + type IntoFuture: Future + Send; +} + +impl IntoSendFuture for T +where + T: Resolvable + IntoFuture, + T::IntoFuture: Send, +{ + type IntoFuture = T::IntoFuture; +} + +/// Synchronous execution of a resolvable +pub trait Wait: Resolvable { + /// Synchronously execute and wait + fn wait(self) -> Self::To; +} + +#[deprecated = "use `.await` directly instead"] pub trait AsyncResolve: Resolvable { - type Future: Future::To> + Send; + type Future: Future + Send; fn res_async(self) -> Self::Future; @@ -47,10 +69,24 @@ pub trait AsyncResolve: Resolvable { } } +#[allow(deprecated)] +impl AsyncResolve for T +where + T: Resolvable + IntoFuture, + T::IntoFuture: Send, +{ + type Future = T::IntoFuture; + + fn res_async(self) -> Self::Future { + self.into_future() + } +} + +#[deprecated = "use `.wait()` instead`"] pub trait SyncResolve: Resolvable { - fn res_sync(self) -> ::To; + fn res_sync(self) -> Self::To; - fn res(self) -> ::To + fn res(self) -> Self::To where Self: Sized, { @@ -58,23 +94,42 @@ pub trait SyncResolve: Resolvable { } } +#[allow(deprecated)] +impl SyncResolve for T +where + T: Wait, +{ + fn res_sync(self) -> Self::To { + self.wait() + } +} + /// Zenoh's trait for resolving builder patterns. /// -/// Builder patterns in Zenoh can be resolved with [`AsyncResolve`] in async context and [`SyncResolve`] in sync context. -/// In both async and sync context calling `.res()` resolves the builder. -/// `.res()` maps to `.res_async()` in async context. -/// `.res()` maps to `.res_sync()` in sync context. -/// We advise to prefer the usage of [`AsyncResolve`] and to use [`SyncResolve`] with caution. -#[must_use = "Resolvables do nothing unless you resolve them using `.res()`."] -pub trait Resolve: Resolvable + SyncResolve + AsyncResolve + Send {} +/// Builder patterns in Zenoh can be resolved by awaiting them, in async context, +/// and [`Wait::wait`] in sync context. +/// We advise to prefer the usage of asynchronous execution, and to use synchronous one with caution +#[must_use = "Resolvables do nothing unless you resolve them using `.await` or synchronous `.wait()` method"] +pub trait Resolve: + Resolvable + + Wait + + IntoSendFuture + + IntoFuture::IntoFuture, Output = Output> + + Send +{ +} impl Resolve for T where - T: Resolvable + SyncResolve + AsyncResolve + Send + T: Resolvable + + Wait + + IntoSendFuture + + IntoFuture::IntoFuture, Output = Output> + + Send { } // Closure to wait -#[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] +#[must_use = "Resolvables do nothing unless you resolve them using `.await` or synchronous `.wait()` method"] pub struct ResolveClosure(C) where To: Sized + Send, @@ -98,30 +153,31 @@ where type To = To; } -impl AsyncResolve for ResolveClosure +impl IntoFuture for ResolveClosure where To: Sized + Send, C: FnOnce() -> To + Send, { - type Future = Ready<::To>; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } -impl SyncResolve for ResolveClosure +impl Wait for ResolveClosure where To: Sized + Send, C: FnOnce() -> To + Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { self.0() } } // Future to wait -#[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] +#[must_use = "Resolvables do nothing unless you resolve them using `.await` or synchronous `.wait()` method"] pub struct ResolveFuture(F) where To: Sized + Send, @@ -145,24 +201,25 @@ where type To = To; } -impl AsyncResolve for ResolveFuture +impl IntoFuture for ResolveFuture where To: Sized + Send, F: Future + Send, { - type Future = F; + type Output = To; + type IntoFuture = F; - fn res_async(self) -> Self::Future { + fn into_future(self) -> Self::IntoFuture { self.0 } } -impl SyncResolve for ResolveFuture +impl Wait for ResolveFuture where To: Sized + Send, F: Future + Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { zenoh_runtime::ZRuntime::Application.block_in_place(self.0) } } diff --git a/commons/zenoh-core/src/macros.rs b/commons/zenoh-core/src/macros.rs index d8f2f1fdc3..f20f22f41a 100644 --- a/commons/zenoh-core/src/macros.rs +++ b/commons/zenoh-core/src/macros.rs @@ -233,6 +233,8 @@ macro_rules! zcondfeat { #[macro_export] macro_rules! ztimeout { ($f:expr) => { - tokio::time::timeout(TIMEOUT, $f).await.unwrap() + tokio::time::timeout(TIMEOUT, ::core::future::IntoFuture::into_future($f)) + .await + .unwrap() }; } diff --git a/commons/zenoh-task/src/lib.rs b/commons/zenoh-task/src/lib.rs index 5f7c3c26d2..d41eb50f34 100644 --- a/commons/zenoh-task/src/lib.rs +++ b/commons/zenoh-task/src/lib.rs @@ -24,7 +24,7 @@ use std::time::Duration; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use tokio_util::task::TaskTracker; -use zenoh_core::{ResolveFuture, SyncResolve}; +use zenoh_core::{ResolveFuture, Wait}; use zenoh_runtime::ZRuntime; #[derive(Clone)] @@ -111,7 +111,7 @@ impl TaskController { /// The call blocks until all tasks yield or timeout duration expires. /// Returns 0 in case of success, number of non terminated tasks otherwise. pub fn terminate_all(&self, timeout: Duration) -> usize { - ResolveFuture::new(async move { self.terminate_all_async(timeout).await }).res_sync() + ResolveFuture::new(async move { self.terminate_all_async(timeout).await }).wait() } /// Async version of [`TaskController::terminate_all()`]. @@ -176,7 +176,7 @@ impl TerminatableTask { /// Attempts to terminate the task. /// Returns true if task completed / aborted within timeout duration, false otherwise. pub fn terminate(self, timeout: Duration) -> bool { - ResolveFuture::new(async move { self.terminate_async(timeout).await }).res_sync() + ResolveFuture::new(async move { self.terminate_async(timeout).await }).wait() } /// Async version of [`TerminatableTask::terminate()`]. diff --git a/examples/examples/z_alloc_shm.rs b/examples/examples/z_alloc_shm.rs index 34e1c07058..acff39379c 100644 --- a/examples/examples/z_alloc_shm.rs +++ b/examples/examples/z_alloc_shm.rs @@ -11,7 +11,7 @@ // Contributors: // ZettaScale Zenoh Team, // -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; #[tokio::main] async fn main() { @@ -120,9 +120,9 @@ async fn run() -> ZResult<()> { sbuf[0..8].fill(0); // Declare Session and Publisher (common code) - let session = zenoh::open(Config::default()).res_async().await?; - let publisher = session.declare_publisher("my/key/expr").res_async().await?; + let session = zenoh::open(Config::default()).await?; + let publisher = session.declare_publisher("my/key/expr").await?; // Publish SHM buffer - publisher.put(sbuf).res_async().await + publisher.put(sbuf).await } diff --git a/examples/examples/z_delete.rs b/examples/examples/z_delete.rs index 7ee8c75421..4fbb46367c 100644 --- a/examples/examples/z_delete.rs +++ b/examples/examples/z_delete.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,12 +23,12 @@ async fn main() { let (config, key_expr) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Deleting resources matching '{key_expr}'..."); - session.delete(&key_expr).res().await.unwrap(); + session.delete(&key_expr).await.unwrap(); - session.close().res().await.unwrap(); + session.close().await.unwrap(); } #[derive(clap::Parser, Clone, PartialEq, Eq, Hash, Debug)] diff --git a/examples/examples/z_forward.rs b/examples/examples/z_forward.rs index 000b0f97ff..22a6ef4229 100644 --- a/examples/examples/z_forward.rs +++ b/examples/examples/z_forward.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; use zenoh_ext::SubscriberForward; @@ -24,12 +24,12 @@ async fn main() { let (config, key_expr, forward) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Subscriber on '{key_expr}'..."); - let mut subscriber = session.declare_subscriber(&key_expr).res().await.unwrap(); + let mut subscriber = session.declare_subscriber(&key_expr).await.unwrap(); println!("Declaring Publisher on '{forward}'..."); - let publisher = session.declare_publisher(&forward).res().await.unwrap(); + let publisher = session.declare_publisher(&forward).await.unwrap(); println!("Forwarding data from '{key_expr}' to '{forward}'..."); subscriber.forward(publisher).await.unwrap(); } diff --git a/examples/examples/z_get.rs b/examples/examples/z_get.rs index 56693d9fa1..6b6326ebcf 100644 --- a/examples/examples/z_get.rs +++ b/examples/examples/z_get.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::Duration; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -24,19 +24,18 @@ async fn main() { let (config, selector, value, target, timeout) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Sending Query '{selector}'..."); let replies = session .get(&selector) - // // By default get receives replies from a FIFO. - // // Uncomment this line to use a ring channel instead. + // // By default get receives replies from a FIFO. + // // Uncomment this line to use a ring channel instead. // // More information on the ring channel are available in the z_pull example. - .with(zenoh::handlers::RingChannel::default()) + // .with(zenoh::handlers::RingChannel::default()) .value(value) .target(target) .timeout(timeout) - .res() .await .unwrap(); while let Ok(reply) = replies.recv_async().await { diff --git a/examples/examples/z_get_liveliness.rs b/examples/examples/z_get_liveliness.rs index bd8e62a78c..43747697b6 100644 --- a/examples/examples/z_get_liveliness.rs +++ b/examples/examples/z_get_liveliness.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::Duration; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -24,14 +24,13 @@ async fn main() { let (config, key_expr, timeout) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Sending Liveliness Query '{key_expr}'..."); let replies = session .liveliness() .get(&key_expr) .timeout(timeout) - .res() .await .unwrap(); while let Ok(reply) = replies.recv_async().await { diff --git a/examples/examples/z_info.rs b/examples/examples/z_info.rs index adde62f808..db28970897 100644 --- a/examples/examples/z_info.rs +++ b/examples/examples/z_info.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,17 +23,17 @@ async fn main() { let config = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); let info = session.info(); - println!("zid: {}", info.zid().res().await); + println!("zid: {}", info.zid().await); println!( "routers zid: {:?}", - info.routers_zid().res().await.collect::>() + info.routers_zid().await.collect::>() ); println!( "peers zid: {:?}", - info.peers_zid().res().await.collect::>() + info.peers_zid().await.collect::>() ); } diff --git a/examples/examples/z_liveliness.rs b/examples/examples/z_liveliness.rs index 1c78d3ad24..cee7a29376 100644 --- a/examples/examples/z_liveliness.rs +++ b/examples/examples/z_liveliness.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,17 +23,10 @@ async fn main() { let (config, key_expr) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring LivelinessToken on '{}'...", &key_expr); - let mut token = Some( - session - .liveliness() - .declare_token(&key_expr) - .res() - .await - .unwrap(), - ); + let mut token = Some(session.liveliness().declare_token(&key_expr).await.unwrap()); println!("Press CTRL-C to undeclare LivelinessToken and quit..."); std::thread::park(); @@ -41,7 +34,7 @@ async fn main() { // Use the code below to manually undeclare it if needed if let Some(token) = token.take() { println!("Undeclaring LivelinessToken..."); - token.undeclare().res().await.unwrap(); + token.undeclare().await.unwrap(); }; } diff --git a/examples/examples/z_ping.rs b/examples/examples/z_ping.rs index af1e9c977d..81181f1a81 100644 --- a/examples/examples/z_ping.rs +++ b/examples/examples/z_ping.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::{Duration, Instant}; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; fn main() { @@ -21,7 +21,7 @@ fn main() { zenoh_util::try_init_log_from_env(); let (config, warmup, size, n, express) = parse_args(); - let session = zenoh::open(config).res().unwrap(); + let session = zenoh::open(config).wait().unwrap(); // The key expression to publish data on let key_expr_ping = keyexpr::new("test/ping").unwrap(); @@ -29,12 +29,12 @@ fn main() { // The key expression to wait the response back let key_expr_pong = keyexpr::new("test/pong").unwrap(); - let sub = session.declare_subscriber(key_expr_pong).res().unwrap(); + let sub = session.declare_subscriber(key_expr_pong).wait().unwrap(); let publisher = session .declare_publisher(key_expr_ping) .congestion_control(CongestionControl::Block) .express(express) - .res() + .wait() .unwrap(); let data: ZBytes = (0usize..size) @@ -49,7 +49,7 @@ fn main() { let now = Instant::now(); while now.elapsed() < warmup { let data = data.clone(); - publisher.put(data).res().unwrap(); + publisher.put(data).wait().unwrap(); let _ = sub.recv(); } @@ -57,7 +57,7 @@ fn main() { for _ in 0..n { let data = data.clone(); let write_time = Instant::now(); - publisher.put(data).res().unwrap(); + publisher.put(data).wait().unwrap(); let _ = sub.recv(); let ts = write_time.elapsed().as_micros(); diff --git a/examples/examples/z_ping_shm.rs b/examples/examples/z_ping_shm.rs index 98d9bae825..7a7bd61580 100644 --- a/examples/examples/z_ping_shm.rs +++ b/examples/examples/z_ping_shm.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::{Duration, Instant}; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; fn main() { @@ -27,7 +27,7 @@ fn main() { // subscriber side. By doing so, the probing procedure will succeed and shared memory will operate as expected. config.transport.shared_memory.set_enabled(true).unwrap(); - let session = zenoh::open(config).res().unwrap(); + let session = zenoh::open(config).wait().unwrap(); // The key expression to publish data on let key_expr_ping = keyexpr::new("test/ping").unwrap(); @@ -35,11 +35,11 @@ fn main() { // The key expression to wait the response back let key_expr_pong = keyexpr::new("test/pong").unwrap(); - let sub = session.declare_subscriber(key_expr_pong).res().unwrap(); + let sub = session.declare_subscriber(key_expr_pong).wait().unwrap(); let publisher = session .declare_publisher(key_expr_ping) .congestion_control(CongestionControl::Block) - .res() + .wait() .unwrap(); let mut samples = Vec::with_capacity(n); @@ -87,14 +87,14 @@ fn main() { println!("Warming up for {warmup:?}..."); let now = Instant::now(); while now.elapsed() < warmup { - publisher.put(buf.clone()).res().unwrap(); + publisher.put(buf.clone()).wait().unwrap(); let _ = sub.recv().unwrap(); } for _ in 0..n { let buf = buf.clone(); let write_time = Instant::now(); - publisher.put(buf).res().unwrap(); + publisher.put(buf).wait().unwrap(); let _ = sub.recv(); let ts = write_time.elapsed().as_micros(); diff --git a/examples/examples/z_pong.rs b/examples/examples/z_pong.rs index b2fc075c10..7d7b60b6e9 100644 --- a/examples/examples/z_pong.rs +++ b/examples/examples/z_pong.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; fn main() { @@ -26,7 +26,7 @@ fn main() { // subscriber side. By doing so, the probing procedure will succeed and shared memory will operate as expected. config.transport.shared_memory.set_enabled(true).unwrap(); - let session = zenoh::open(config).res().unwrap().into_arc(); + let session = zenoh::open(config).wait().unwrap().into_arc(); // The key expression to read the data from let key_expr_ping = keyexpr::new("test/ping").unwrap(); @@ -38,13 +38,13 @@ fn main() { .declare_publisher(key_expr_pong) .congestion_control(CongestionControl::Block) .express(express) - .res() + .wait() .unwrap(); let _sub = session .declare_subscriber(key_expr_ping) - .callback(move |sample| publisher.put(sample.payload().clone()).res().unwrap()) - .res() + .callback(move |sample| publisher.put(sample.payload().clone()).wait().unwrap()) + .wait() .unwrap(); std::thread::park(); } diff --git a/examples/examples/z_pub.rs b/examples/examples/z_pub.rs index 79de0e61d4..7c2c9f2c65 100644 --- a/examples/examples/z_pub.rs +++ b/examples/examples/z_pub.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::Duration; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -24,22 +24,17 @@ async fn main() { let (config, key_expr, value, attachment) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Publisher on '{key_expr}'..."); - let publisher = session.declare_publisher(&key_expr).res().await.unwrap(); + let publisher = session.declare_publisher(&key_expr).await.unwrap(); println!("Press CTRL-C to quit..."); for idx in 0..u32::MAX { tokio::time::sleep(Duration::from_secs(1)).await; let buf = format!("[{idx:4}] {value}"); println!("Putting Data ('{}': '{}')...", &key_expr, buf); - publisher - .put(buf) - .attachment(&attachment) - .res() - .await - .unwrap(); + publisher.put(buf).attachment(&attachment).await.unwrap(); } } diff --git a/examples/examples/z_pub_shm.rs b/examples/examples/z_pub_shm.rs index 79527c3e5f..92d19b6b06 100644 --- a/examples/examples/z_pub_shm.rs +++ b/examples/examples/z_pub_shm.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; const N: usize = 10; @@ -31,7 +31,7 @@ async fn main() -> Result<(), ZError> { config.transport.shared_memory.set_enabled(true).unwrap(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Creating POSIX SHM backend..."); // Construct an SHM backend @@ -62,7 +62,7 @@ async fn main() -> Result<(), ZError> { .backend(backend) .res(); - let publisher = session.declare_publisher(&path).res().await.unwrap(); + let publisher = session.declare_publisher(&path).await.unwrap(); println!("Allocating Shared Memory Buffer..."); let layout = shared_memory_provider @@ -95,7 +95,7 @@ async fn main() -> Result<(), ZError> { path, String::from_utf8_lossy(&sbuf[0..slice_len]) ); - publisher.put(sbuf).res().await?; + publisher.put(sbuf).await?; } Ok(()) diff --git a/examples/examples/z_pub_shm_thr.rs b/examples/examples/z_pub_shm_thr.rs index 70a0bf0548..0b94304321 100644 --- a/examples/examples/z_pub_shm_thr.rs +++ b/examples/examples/z_pub_shm_thr.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -26,7 +26,7 @@ async fn main() { // subscriber side. By doing so, the probing procedure will succeed and shared memory will operate as expected. config.transport.shared_memory.set_enabled(true).unwrap(); - let z = zenoh::open(config).res().await.unwrap(); + let z = zenoh::open(config).await.unwrap(); // Construct an SHM backend let backend = { @@ -68,15 +68,18 @@ async fn main() { *b = rand::random::(); } - let publisher = z.declare_publisher("test/thr") - // Make sure to not drop messages because of congestion control - .congestion_control(CongestionControl::Block).res().await.unwrap(); + let publisher = z + .declare_publisher("test/thr") + // Make sure to not drop messages because of congestion control + .congestion_control(CongestionControl::Block) + .await + .unwrap(); let buf: ZSlice = buf.into(); println!("Press CTRL-C to quit..."); loop { - publisher.put(buf.clone()).res().await.unwrap(); + publisher.put(buf.clone()).await.unwrap(); } } diff --git a/examples/examples/z_pub_thr.rs b/examples/examples/z_pub_thr.rs index 5625c1b91d..5eb4f9e96e 100644 --- a/examples/examples/z_pub_thr.rs +++ b/examples/examples/z_pub_thr.rs @@ -14,7 +14,7 @@ use clap::Parser; use std::convert::TryInto; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; fn main() { @@ -34,21 +34,21 @@ fn main() { .collect::>() .into(); - let session = zenoh::open(args.common).res().unwrap(); + let session = zenoh::open(args.common).wait().unwrap(); let publisher = session .declare_publisher("test/thr") .congestion_control(CongestionControl::Block) .priority(prio) .express(args.express) - .res() + .wait() .unwrap(); println!("Press CTRL-C to quit..."); let mut count: usize = 0; let mut start = std::time::Instant::now(); loop { - publisher.put(data.clone()).res().unwrap(); + publisher.put(data.clone()).wait().unwrap(); if args.print { if count < args.number { diff --git a/examples/examples/z_pull.rs b/examples/examples/z_pull.rs index 349779e574..55f211f111 100644 --- a/examples/examples/z_pull.rs +++ b/examples/examples/z_pull.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::Duration; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -24,13 +24,12 @@ async fn main() { let (config, key_expr, size, interval) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Subscriber on '{key_expr}'..."); let subscriber = session .declare_subscriber(&key_expr) .with(RingChannel::new(size)) - .res() .await .unwrap(); diff --git a/examples/examples/z_put.rs b/examples/examples/z_put.rs index bb1274a638..5d68d205f9 100644 --- a/examples/examples/z_put.rs +++ b/examples/examples/z_put.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,10 +23,10 @@ async fn main() { let (config, key_expr, value) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Putting Data ('{key_expr}': '{value}')..."); - session.put(&key_expr, value).res().await.unwrap(); + session.put(&key_expr, value).await.unwrap(); } #[derive(clap::Parser, Clone, PartialEq, Eq, Hash, Debug)] diff --git a/examples/examples/z_put_float.rs b/examples/examples/z_put_float.rs index b9c2a4e019..97e4abd69d 100644 --- a/examples/examples/z_put_float.rs +++ b/examples/examples/z_put_float.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,12 +23,12 @@ async fn main() { let (config, key_expr, value) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Putting Float ('{key_expr}': '{value}')..."); - session.put(&key_expr, value).res().await.unwrap(); + session.put(&key_expr, value).await.unwrap(); - session.close().res().await.unwrap(); + session.close().await.unwrap(); } #[derive(clap::Parser, Clone, PartialEq, Debug)] diff --git a/examples/examples/z_queryable.rs b/examples/examples/z_queryable.rs index 47f70c30c3..e24b8e80cb 100644 --- a/examples/examples/z_queryable.rs +++ b/examples/examples/z_queryable.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,17 +23,16 @@ async fn main() { let (config, key_expr, value, complete) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Queryable on '{key_expr}'..."); let queryable = session .declare_queryable(&key_expr) - // // By default queryable receives queries from a FIFO. - // // Uncomment this line to use a ring channel instead. + // // By default queryable receives queries from a FIFO. + // // Uncomment this line to use a ring channel instead. // // More information on the ring channel are available in the z_pull example. // .with(zenoh::handlers::RingChannel::default()) .complete(complete) - .res() .await .unwrap(); @@ -60,7 +59,6 @@ async fn main() { ); query .reply(key_expr.clone(), value.clone()) - .res() .await .unwrap_or_else(|e| println!(">> [Queryable ] Error sending reply: {e}")); } diff --git a/examples/examples/z_scout.rs b/examples/examples/z_scout.rs index 5ac06f37d4..bcd65ffb0e 100644 --- a/examples/examples/z_scout.rs +++ b/examples/examples/z_scout.rs @@ -11,7 +11,7 @@ // Contributors: // ZettaScale Zenoh Team, // -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; #[tokio::main] async fn main() { @@ -20,7 +20,6 @@ async fn main() { println!("Scouting..."); let receiver = scout(WhatAmI::Peer | WhatAmI::Router, Config::default()) - .res() .await .unwrap(); diff --git a/examples/examples/z_storage.rs b/examples/examples/z_storage.rs index fd4337535c..2b03e32d06 100644 --- a/examples/examples/z_storage.rs +++ b/examples/examples/z_storage.rs @@ -16,7 +16,7 @@ use clap::Parser; use futures::select; use std::collections::HashMap; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -29,16 +29,15 @@ async fn main() { let mut stored: HashMap = HashMap::new(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Subscriber on '{key_expr}'..."); - let subscriber = session.declare_subscriber(&key_expr).res().await.unwrap(); + let subscriber = session.declare_subscriber(&key_expr).await.unwrap(); println!("Declaring Queryable on '{key_expr}'..."); let queryable = session .declare_queryable(&key_expr) .complete(complete) - .res() .await .unwrap(); @@ -60,7 +59,7 @@ async fn main() { println!(">> [Queryable ] Received Query '{}'", query.selector()); for (stored_name, sample) in stored.iter() { if query.selector().key_expr().intersects(unsafe {keyexpr::from_str_unchecked(stored_name)}) { - query.reply(sample.key_expr().clone(), sample.payload().clone()).res().await.unwrap(); + query.reply(sample.key_expr().clone(), sample.payload().clone()).await.unwrap(); } } } diff --git a/examples/examples/z_sub.rs b/examples/examples/z_sub.rs index d2cc370306..156968eb36 100644 --- a/examples/examples/z_sub.rs +++ b/examples/examples/z_sub.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -28,10 +28,10 @@ async fn main() { config.transport.shared_memory.set_enabled(true).unwrap(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Subscriber on '{}'...", &key_expr); - let subscriber = session.declare_subscriber(&key_expr).res().await.unwrap(); + let subscriber = session.declare_subscriber(&key_expr).await.unwrap(); println!("Press CTRL-C to quit..."); while let Ok(sample) = subscriber.recv_async().await { diff --git a/examples/examples/z_sub_liveliness.rs b/examples/examples/z_sub_liveliness.rs index 1df5b9422e..af2c02342d 100644 --- a/examples/examples/z_sub_liveliness.rs +++ b/examples/examples/z_sub_liveliness.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // use clap::Parser; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -23,14 +23,13 @@ async fn main() { let (config, key_expr) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Liveliness Subscriber on '{}'...", &key_expr); let subscriber = session .liveliness() .declare_subscriber(&key_expr) - .res() .await .unwrap(); diff --git a/examples/examples/z_sub_shm.rs b/examples/examples/z_sub_shm.rs index 282fd8c776..5f5c77633f 100644 --- a/examples/examples/z_sub_shm.rs +++ b/examples/examples/z_sub_shm.rs @@ -13,7 +13,7 @@ // use clap::Parser; use zenoh::config::Config; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; #[tokio::main] @@ -29,10 +29,10 @@ async fn main() { config.transport.shared_memory.set_enabled(true).unwrap(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Subscriber on '{}'...", &key_expr); - let subscriber = session.declare_subscriber(&key_expr).res().await.unwrap(); + let subscriber = session.declare_subscriber(&key_expr).await.unwrap(); println!("Press CTRL-C to quit..."); while let Ok(sample) = subscriber.recv_async().await { diff --git a/examples/examples/z_sub_thr.rs b/examples/examples/z_sub_thr.rs index 88105ca8aa..6913a7bf08 100644 --- a/examples/examples/z_sub_thr.rs +++ b/examples/examples/z_sub_thr.rs @@ -13,7 +13,7 @@ // use clap::Parser; use std::time::Instant; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; use zenoh_examples::CommonArgs; struct Stats { @@ -77,7 +77,7 @@ fn main() { // subscriber side. By doing so, the probing procedure will succeed and shared memory will operate as expected. config.transport.shared_memory.set_enabled(true).unwrap(); - let session = zenoh::open(config).res().unwrap(); + let session = zenoh::open(config).wait().unwrap(); let key_expr = "test/thr"; @@ -90,7 +90,7 @@ fn main() { std::process::exit(0) } }) - .res() + .wait() .unwrap(); println!("Press CTRL-C to quit..."); diff --git a/io/zenoh-links/zenoh-link-unixpipe/src/unix/unicast.rs b/io/zenoh-links/zenoh-link-unixpipe/src/unix/unicast.rs index 12543b31a1..ea90630523 100644 --- a/io/zenoh-links/zenoh-link-unixpipe/src/unix/unicast.rs +++ b/io/zenoh-links/zenoh-link-unixpipe/src/unix/unicast.rs @@ -32,7 +32,7 @@ use tokio::io::unix::AsyncFd; use tokio::io::Interest; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; -use zenoh_core::{zasyncread, zasyncwrite, ResolveFuture, SyncResolve}; +use zenoh_core::{zasyncread, zasyncwrite, ResolveFuture, Wait}; use zenoh_protocol::core::{EndPoint, Locator}; use zenoh_protocol::transport::BatchSize; use zenoh_runtime::ZRuntime; @@ -331,7 +331,7 @@ impl UnicastPipeListener { fn stop_listening(self) { self.token.cancel(); - let _ = ResolveFuture::new(self.handle).res_sync(); + let _ = ResolveFuture::new(self.handle).wait(); } } diff --git a/plugins/zenoh-backend-traits/src/lib.rs b/plugins/zenoh-backend-traits/src/lib.rs index 5db79b57bd..761f653064 100644 --- a/plugins/zenoh-backend-traits/src/lib.rs +++ b/plugins/zenoh-backend-traits/src/lib.rs @@ -29,7 +29,7 @@ //! ``` //! use std::sync::Arc; //! use async_trait::async_trait; -//! use zenoh::prelude::r#async::*; +//! use zenoh::prelude::*; //! use zenoh_backend_traits::*; //! use zenoh_backend_traits::config::*; //! diff --git a/plugins/zenoh-plugin-example/src/lib.rs b/plugins/zenoh-plugin-example/src/lib.rs index f1deae363d..3c84e039a8 100644 --- a/plugins/zenoh-plugin-example/src/lib.rs +++ b/plugins/zenoh-plugin-example/src/lib.rs @@ -28,7 +28,6 @@ use zenoh::runtime::Runtime; use zenoh::sample::Sample; use zenoh::session::SessionDeclarations; use zenoh_core::zlock; -use zenoh_core::AsyncResolve; use zenoh_plugin_trait::{plugin_long_version, plugin_version, Plugin, PluginControl}; use zenoh_result::{bail, ZResult}; @@ -147,7 +146,7 @@ async fn run(runtime: Runtime, selector: KeyExpr<'_>, flag: Arc) { zenoh_util::try_init_log_from_env(); // create a zenoh Session that shares the same Runtime than zenohd - let session = zenoh::session::init(runtime).res().await.unwrap(); + let session = zenoh::session::init(runtime).await.unwrap(); // the HasMap used as a storage by this example of storage plugin let mut stored: HashMap = HashMap::new(); @@ -156,11 +155,11 @@ async fn run(runtime: Runtime, selector: KeyExpr<'_>, flag: Arc) { // This storage plugin subscribes to the selector and will store in HashMap the received samples debug!("Create Subscriber on {}", selector); - let sub = session.declare_subscriber(&selector).res().await.unwrap(); + let sub = session.declare_subscriber(&selector).await.unwrap(); // This storage plugin declares a Queryable that will reply to queries with the samples stored in the HashMap debug!("Create Queryable on {}", selector); - let queryable = session.declare_queryable(&selector).res().await.unwrap(); + let queryable = session.declare_queryable(&selector).await.unwrap(); // Plugin's event loop, while the flag is true while flag.load(Relaxed) { @@ -178,7 +177,7 @@ async fn run(runtime: Runtime, selector: KeyExpr<'_>, flag: Arc) { info!("Handling query '{}'", query.selector()); for (key_expr, sample) in stored.iter() { if query.selector().key_expr().intersects(unsafe{keyexpr::from_str_unchecked(key_expr)}) { - query.reply_sample(sample.clone()).res().await.unwrap(); + query.reply_sample(sample.clone()).await.unwrap(); } } } diff --git a/plugins/zenoh-plugin-rest/examples/z_serve_sse.rs b/plugins/zenoh-plugin-rest/examples/z_serve_sse.rs index 5e5485d0d2..59562391ea 100644 --- a/plugins/zenoh-plugin-rest/examples/z_serve_sse.rs +++ b/plugins/zenoh-plugin-rest/examples/z_serve_sse.rs @@ -14,7 +14,7 @@ use clap::{arg, Command}; use std::time::Duration; use zenoh::config::Config; -use zenoh::core::{try_init_log_from_env, AsyncResolve}; +use zenoh::core::try_init_log_from_env; use zenoh::key_expr::keyexpr; use zenoh::publication::CongestionControl; use zenoh::sample::QoSBuilderTrait; @@ -43,16 +43,16 @@ async fn main() { let value = "Pub from sse server!"; println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring Queryable on '{key}'..."); - let queryable = session.declare_queryable(key).res().await.unwrap(); + let queryable = session.declare_queryable(key).await.unwrap(); async_std::task::spawn({ let receiver = queryable.handler().clone(); async move { while let Ok(request) = receiver.recv_async().await { - request.reply(key, HTML).res().await.unwrap(); + request.reply(key, HTML).await.unwrap(); } } }); @@ -63,7 +63,6 @@ async fn main() { let publisher = session .declare_publisher(&event_key) .congestion_control(CongestionControl::Block) - .res() .await .unwrap(); @@ -74,7 +73,7 @@ async fn main() { println!("Data updates are accessible through HTML5 SSE at http://:8000/{key}"); loop { - publisher.put(value).res().await.unwrap(); + publisher.put(value).await.unwrap(); async_std::task::sleep(Duration::from_secs(1)).await; } } diff --git a/plugins/zenoh-plugin-rest/src/lib.rs b/plugins/zenoh-plugin-rest/src/lib.rs index 7fe591e3f7..c712a1add6 100644 --- a/plugins/zenoh-plugin-rest/src/lib.rs +++ b/plugins/zenoh-plugin-rest/src/lib.rs @@ -30,7 +30,7 @@ use tide::http::Mime; use tide::sse::Sender; use tide::{Request, Response, Server, StatusCode}; use zenoh::bytes::{StringOrBase64, ZBytes}; -use zenoh::core::{try_init_log_from_env, AsyncResolve}; +use zenoh::core::try_init_log_from_env; use zenoh::encoding::Encoding; use zenoh::key_expr::{keyexpr, KeyExpr}; use zenoh::plugins::{RunningPluginTrait, ZenohPlugin}; @@ -350,13 +350,7 @@ async fn query(mut req: Request<(Arc, String)>) -> tide::Result, String)>) -> tide::Result, String)>) -> tide::Result, String)>) -> tide::Result { if raw { Ok(to_raw_response(receiver).await) @@ -470,8 +464,8 @@ async fn write(mut req: Request<(Arc, String)>) -> tide::Result session.put(&key_expr, bytes).encoding(encoding).res().await, - SampleKind::Delete => session.delete(&key_expr).res().await, + SampleKind::Put => session.put(&key_expr, bytes).encoding(encoding).await, + SampleKind::Delete => session.delete(&key_expr).await, }; match res { Ok(_) => Ok(Response::new(StatusCode::Ok)), @@ -497,7 +491,7 @@ pub async fn run(runtime: Runtime, conf: Config) -> ZResult<()> { try_init_log_from_env(); let zid = runtime.zid().to_string(); - let session = zenoh::session::init(runtime).res().await.unwrap(); + let session = zenoh::session::init(runtime).await.unwrap(); let mut app = Server::with_state((Arc::new(session), zid)); app.with( diff --git a/plugins/zenoh-plugin-storage-manager/src/lib.rs b/plugins/zenoh-plugin-storage-manager/src/lib.rs index e5ca51c5ef..8818d44688 100644 --- a/plugins/zenoh-plugin-storage-manager/src/lib.rs +++ b/plugins/zenoh-plugin-storage-manager/src/lib.rs @@ -29,7 +29,6 @@ use std::sync::Mutex; use storages_mgt::StorageMessage; use zenoh::core::try_init_log_from_env; use zenoh::core::Result as ZResult; -use zenoh::core::SyncResolve; use zenoh::internal::zlock; use zenoh::internal::LibLoader; use zenoh::key_expr::keyexpr; @@ -51,6 +50,8 @@ use zenoh_plugin_trait::PluginStatusRec; mod backends_mgt; use backends_mgt::*; +use zenoh::prelude::Wait; + mod memory_backend; mod replica; mod storages_mgt; @@ -117,7 +118,7 @@ impl StorageRuntimeInner { let plugins_manager = PluginsManager::dynamic(lib_loader.clone(), BACKEND_LIB_PREFIX) .declare_static_plugin::(true); - let session = Arc::new(zenoh::session::init(runtime.clone()).res_sync()?); + let session = Arc::new(zenoh::session::init(runtime.clone()).wait()?); // After this moment result should be only Ok. Failure of loading of one voulme or storage should not affect others. diff --git a/plugins/zenoh-plugin-storage-manager/src/replica/align_queryable.rs b/plugins/zenoh-plugin-storage-manager/src/replica/align_queryable.rs index c24639b6ca..694e259a18 100644 --- a/plugins/zenoh-plugin-storage-manager/src/replica/align_queryable.rs +++ b/plugins/zenoh-plugin-storage-manager/src/replica/align_queryable.rs @@ -18,7 +18,7 @@ use std::cmp::Ordering; use std::collections::{BTreeSet, HashMap, HashSet}; use std::str; use std::str::FromStr; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; pub struct AlignQueryable { session: Arc, @@ -68,7 +68,6 @@ impl AlignQueryable { .session .declare_queryable(&self.digest_key) .complete(true) // This queryable is meant to have all the history - .res() .await .unwrap(); @@ -97,7 +96,6 @@ impl AlignQueryable { query.key_expr().clone(), serde_json::to_string(&(i, c)).unwrap(), ) - .res() .await .unwrap(); } @@ -107,7 +105,6 @@ impl AlignQueryable { query.key_expr().clone(), serde_json::to_string(&(i, c)).unwrap(), ) - .res() .await .unwrap(); } @@ -117,7 +114,6 @@ impl AlignQueryable { query.key_expr().clone(), serde_json::to_string(&(i, c)).unwrap(), ) - .res() .await .unwrap(); } @@ -126,7 +122,6 @@ impl AlignQueryable { .reply(k, v.payload().clone()) .encoding(v.encoding().clone()) .timestamp(ts) - .res() .await .unwrap(); } @@ -226,7 +221,7 @@ impl AlignQueryable { impl AlignQueryable { async fn get_entry(&self, logentry: &LogEntry) -> Option { // get corresponding key from log - let replies = self.session.get(&logentry.key).res().await.unwrap(); + let replies = self.session.get(&logentry.key).await.unwrap(); if let Ok(reply) = replies.recv_async().await { match reply.into_result() { Ok(sample) => { diff --git a/plugins/zenoh-plugin-storage-manager/src/replica/aligner.rs b/plugins/zenoh-plugin-storage-manager/src/replica/aligner.rs index 3a9fd00558..46ccdc2935 100644 --- a/plugins/zenoh-plugin-storage-manager/src/replica/aligner.rs +++ b/plugins/zenoh-plugin-storage-manager/src/replica/aligner.rs @@ -18,7 +18,7 @@ use async_std::sync::{Arc, RwLock}; use flume::{Receiver, Sender}; use std::collections::{HashMap, HashSet}; use std::str; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; pub struct Aligner { session: Arc, @@ -322,7 +322,6 @@ impl Aligner { .get(&selector) .consolidation(zenoh::query::ConsolidationMode::None) .accept_replies(zenoh::query::ReplyKeyExpr::Any) - .res() .await { Ok(replies) => { diff --git a/plugins/zenoh-plugin-storage-manager/src/replica/mod.rs b/plugins/zenoh-plugin-storage-manager/src/replica/mod.rs index b951b23336..c9d9e03bcf 100644 --- a/plugins/zenoh-plugin-storage-manager/src/replica/mod.rs +++ b/plugins/zenoh-plugin-storage-manager/src/replica/mod.rs @@ -26,7 +26,7 @@ use std::str; use std::str::FromStr; use std::time::{Duration, SystemTime}; use urlencoding::encode; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_backend_traits::config::{ReplicaConfig, StorageConfig}; pub mod align_queryable; @@ -206,7 +206,6 @@ impl Replica { .session .declare_subscriber(&digest_key) .allowed_origin(Locality::Remote) - .res() .await .unwrap(); loop { @@ -265,12 +264,7 @@ impl Replica { .unwrap(); tracing::debug!("[DIGEST_PUB] Declaring Publisher on '{}'...", digest_key); - let publisher = self - .session - .declare_publisher(digest_key) - .res() - .await - .unwrap(); + let publisher = self.session.declare_publisher(digest_key).await.unwrap(); // Ensure digest gets published every interval, accounting for // time it takes to publish. @@ -287,7 +281,7 @@ impl Replica { drop(digest); tracing::trace!("[DIGEST_PUB] Putting Digest: {} ...", digest_json); - match publisher.put(digest_json).res().await { + match publisher.put(digest_json).await { Ok(()) => {} Err(e) => tracing::error!("[DIGEST_PUB] Digest publication failed: {}", e), } diff --git a/plugins/zenoh-plugin-storage-manager/src/replica/storage.rs b/plugins/zenoh-plugin-storage-manager/src/replica/storage.rs index ba078c0012..476893539e 100644 --- a/plugins/zenoh-plugin-storage-manager/src/replica/storage.rs +++ b/plugins/zenoh-plugin-storage-manager/src/replica/storage.rs @@ -23,7 +23,6 @@ use std::str::{self, FromStr}; use std::time::{SystemTime, UNIX_EPOCH}; use zenoh::buffers::SplitBuffer; use zenoh::buffers::ZBuf; -use zenoh::core::AsyncResolve; use zenoh::internal::bail; use zenoh::internal::{zenoh_home, Timed, TimedEvent, Timer}; use zenoh::key_expr::keyexpr_tree::KeyedSetProvider; @@ -144,7 +143,7 @@ impl StorageService { t.add_async(gc).await; // subscribe on key_expr - let storage_sub = match self.session.declare_subscriber(&self.key_expr).res().await { + let storage_sub = match self.session.declare_subscriber(&self.key_expr).await { Ok(storage_sub) => storage_sub, Err(e) => { tracing::error!("Error starting storage '{}': {}", self.name, e); @@ -157,7 +156,6 @@ impl StorageService { .session .declare_queryable(&self.key_expr) .complete(self.complete) - .res() .await { Ok(storage_queryable) => storage_queryable, @@ -522,7 +520,6 @@ impl StorageService { .reply(key.clone(), entry.value.payload().clone()) .encoding(entry.value.encoding().clone()) .timestamp(entry.timestamp) - .res() .await { tracing::warn!( @@ -556,7 +553,6 @@ impl StorageService { .reply(q.key_expr().clone(), entry.value.payload().clone()) .encoding(entry.value.encoding().clone()) .timestamp(entry.timestamp) - .res() .await { tracing::warn!( @@ -644,7 +640,6 @@ impl StorageService { .get(Selector::new(&self.key_expr, "_time=[..]")) .target(QueryTarget::All) .consolidation(ConsolidationMode::None) - .res() .await { Ok(replies) => replies, diff --git a/plugins/zenoh-plugin-storage-manager/tests/operations.rs b/plugins/zenoh-plugin-storage-manager/tests/operations.rs index 0678431b7e..b5384e13be 100644 --- a/plugins/zenoh-plugin-storage-manager/tests/operations.rs +++ b/plugins/zenoh-plugin-storage-manager/tests/operations.rs @@ -21,29 +21,23 @@ use std::thread::sleep; use async_std::task; use zenoh::internal::zasync_executor_init; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_plugin_trait::Plugin; async fn put_data(session: &Session, key_expr: &str, value: &str, _timestamp: Timestamp) { println!("Putting Data ('{key_expr}': '{value}')..."); // @TODO: how to add timestamp metadata with put, not manipulating sample... - session.put(key_expr, value).res().await.unwrap(); + session.put(key_expr, value).await.unwrap(); } async fn delete_data(session: &Session, key_expr: &str, _timestamp: Timestamp) { println!("Deleting Data '{key_expr}'..."); // @TODO: how to add timestamp metadata with delete, not manipulating sample... - session.delete(key_expr).res().await.unwrap(); + session.delete(key_expr).await.unwrap(); } async fn get_data(session: &Session, key_expr: &str) -> Vec { - let replies: Vec = session - .get(key_expr) - .res() - .await - .unwrap() - .into_iter() - .collect(); + let replies: Vec = session.get(key_expr).await.unwrap().into_iter().collect(); println!("Getting replies on '{key_expr}': '{replies:?}'..."); let mut samples = Vec::new(); for reply in replies { @@ -80,7 +74,7 @@ async fn test_updates_in_order() { let storage = zenoh_plugin_storage_manager::StoragesPlugin::start("storage-manager", &runtime).unwrap(); - let session = zenoh::session::init(runtime).res().await.unwrap(); + let session = zenoh::session::init(runtime).await.unwrap(); sleep(std::time::Duration::from_secs(1)); diff --git a/plugins/zenoh-plugin-storage-manager/tests/wildcard.rs b/plugins/zenoh-plugin-storage-manager/tests/wildcard.rs index 72fa62f3ca..bd38e834d7 100644 --- a/plugins/zenoh-plugin-storage-manager/tests/wildcard.rs +++ b/plugins/zenoh-plugin-storage-manager/tests/wildcard.rs @@ -22,29 +22,23 @@ use std::thread::sleep; // use std::collections::HashMap; use async_std::task; use zenoh::internal::zasync_executor_init; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_plugin_trait::Plugin; async fn put_data(session: &Session, key_expr: &str, value: &str, _timestamp: Timestamp) { println!("Putting Data ('{key_expr}': '{value}')..."); // @TODO: how to add timestamp metadata with put, not manipulating sample... - session.put(key_expr, value).res().await.unwrap(); + session.put(key_expr, value).await.unwrap(); } async fn delete_data(session: &Session, key_expr: &str, _timestamp: Timestamp) { println!("Deleting Data '{key_expr}'..."); // @TODO: how to add timestamp metadata with delete, not manipulating sample... - session.delete(key_expr).res().await.unwrap(); + session.delete(key_expr).await.unwrap(); } async fn get_data(session: &Session, key_expr: &str) -> Vec { - let replies: Vec = session - .get(key_expr) - .res() - .await - .unwrap() - .into_iter() - .collect(); + let replies: Vec = session.get(key_expr).await.unwrap().into_iter().collect(); println!("Getting replies on '{key_expr}': '{replies:?}'..."); let mut samples = Vec::new(); for reply in replies { @@ -81,7 +75,7 @@ async fn test_wild_card_in_order() { let storage = zenoh_plugin_storage_manager::StoragesPlugin::start("storage-manager", &runtime).unwrap(); - let session = zenoh::session::init(runtime).res().await.unwrap(); + let session = zenoh::session::init(runtime).await.unwrap(); sleep(std::time::Duration::from_secs(1)); // put *, ts: 1 diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 743f7cd993..b7eadd649b 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.72.0" +channel = "1.72.0" \ No newline at end of file diff --git a/zenoh-ext/examples/examples/z_member.rs b/zenoh-ext/examples/examples/z_member.rs index 2dc1a242c9..35513b1b56 100644 --- a/zenoh-ext/examples/examples/z_member.rs +++ b/zenoh-ext/examples/examples/z_member.rs @@ -14,13 +14,13 @@ use futures::StreamExt; use std::sync::Arc; use std::time::Duration; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_ext::group::*; #[tokio::main] async fn main() { zenoh_util::try_init_log_from_env(); - let z = Arc::new(zenoh::open(Config::default()).res().await.unwrap()); + let z = Arc::new(zenoh::open(Config::default()).await.unwrap()); let member = Member::new(z.zid().to_string()) .unwrap() .lease(Duration::from_secs(3)); diff --git a/zenoh-ext/examples/examples/z_pub_cache.rs b/zenoh-ext/examples/examples/z_pub_cache.rs index 58eb7962c9..09c888cb0b 100644 --- a/zenoh-ext/examples/examples/z_pub_cache.rs +++ b/zenoh-ext/examples/examples/z_pub_cache.rs @@ -14,7 +14,7 @@ use clap::{arg, Parser}; use std::time::Duration; use zenoh::config::{Config, ModeDependentValue}; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_ext::*; use zenoh_ext_examples::CommonArgs; @@ -26,7 +26,7 @@ async fn main() { let (config, key_expr, value, history, prefix, complete) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!("Declaring PublicationCache on {}", &key_expr); let mut publication_cache_builder = session @@ -36,14 +36,14 @@ async fn main() { if let Some(prefix) = prefix { publication_cache_builder = publication_cache_builder.queryable_prefix(prefix); } - let _publication_cache = publication_cache_builder.res().await.unwrap(); + let _publication_cache = publication_cache_builder.await.unwrap(); println!("Press CTRL-C to quit..."); for idx in 0..u32::MAX { tokio::time::sleep(Duration::from_secs(1)).await; let buf = format!("[{idx:4}] {value}"); println!("Put Data ('{}': '{}')", &key_expr, buf); - session.put(&key_expr, buf).res().await.unwrap(); + session.put(&key_expr, buf).await.unwrap(); } } diff --git a/zenoh-ext/examples/examples/z_query_sub.rs b/zenoh-ext/examples/examples/z_query_sub.rs index b34a5771a7..a735ecec66 100644 --- a/zenoh-ext/examples/examples/z_query_sub.rs +++ b/zenoh-ext/examples/examples/z_query_sub.rs @@ -14,7 +14,7 @@ use clap::arg; use clap::Parser; use zenoh::config::Config; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; use zenoh_ext::*; use zenoh_ext_examples::CommonArgs; @@ -26,7 +26,7 @@ async fn main() { let (config, key_expr, query) = parse_args(); println!("Opening session..."); - let session = zenoh::open(config).res().await.unwrap(); + let session = zenoh::open(config).await.unwrap(); println!( "Declaring QueryingSubscriber on {} with an initial query on {}", @@ -39,14 +39,12 @@ async fn main() { .querying() .query_selector(&selector) .query_accept_replies(ReplyKeyExpr::Any) - .res() .await .unwrap() } else { session .declare_subscriber(key_expr) .querying() - .res() .await .unwrap() }; diff --git a/zenoh-ext/examples/examples/z_view_size.rs b/zenoh-ext/examples/examples/z_view_size.rs index 66e79cd301..52e78790bb 100644 --- a/zenoh-ext/examples/examples/z_view_size.rs +++ b/zenoh-ext/examples/examples/z_view_size.rs @@ -15,7 +15,6 @@ use clap::{arg, Parser}; use std::sync::Arc; use std::time::Duration; use zenoh::config::Config; -use zenoh::prelude::r#async::*; use zenoh_ext::group::*; use zenoh_ext_examples::CommonArgs; @@ -25,7 +24,7 @@ async fn main() { let (config, group_name, id, size, timeout) = parse_args(); - let z = Arc::new(zenoh::open(config).res().await.unwrap()); + let z = Arc::new(zenoh::open(config).await.unwrap()); let member_id = id.unwrap_or_else(|| z.zid().to_string()); let member = Member::new(member_id.as_str()) .unwrap() diff --git a/zenoh-ext/src/group.rs b/zenoh-ext/src/group.rs index 1bf37f365c..d764e5ed9c 100644 --- a/zenoh-ext/src/group.rs +++ b/zenoh-ext/src/group.rs @@ -25,7 +25,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::Mutex; use zenoh::internal::{bail, Condition, TaskController}; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; const GROUP_PREFIX: &str = "zenoh/ext/net/group"; const EVENT_POSTFIX: &str = "evt"; @@ -177,7 +177,7 @@ async fn keep_alive_task(state: Arc) { loop { tokio::time::sleep(period).await; tracing::trace!("Sending Keep Alive for: {}", &state.local_member.mid); - let _ = state.group_publisher.put(buf.clone()).res().await; + let _ = state.group_publisher.put(buf.clone()).await; } } @@ -219,18 +219,17 @@ async fn query_handler(z: Arc, state: Arc) { .unwrap(); tracing::debug!("Started query handler for: {}", &qres); let buf = bincode::serialize(&state.local_member).unwrap(); - let queryable = z.declare_queryable(&qres).res().await.unwrap(); + let queryable = z.declare_queryable(&qres).await.unwrap(); while let Ok(query) = queryable.recv_async().await { tracing::trace!("Serving query for: {}", &qres); - query.reply(qres.clone(), buf.clone()).res().await.unwrap(); + query.reply(qres.clone(), buf.clone()).await.unwrap(); } } async fn net_event_handler(z: Arc, state: Arc) { let sub = z .declare_subscriber(state.group_publisher.key_expr()) - .res() .await .unwrap(); while let Ok(s) = sub.recv_async().await { @@ -288,7 +287,7 @@ async fn net_event_handler(z: Arc, state: Arc) { // @TODO: we could also send this member info let qc = ConsolidationMode::None; tracing::trace!("Issuing Query for {}", &qres); - let receiver = z.get(&qres).consolidation(qc).res().await.unwrap(); + let receiver = z.get(&qres).consolidation(qc).await.unwrap(); while let Ok(reply) = receiver.recv_async().await { match reply.result() { @@ -358,7 +357,6 @@ impl Group { let publisher = z .declare_publisher(event_expr) .priority(with.priority) - .res() .await .unwrap(); let state = Arc::new(GroupState { @@ -375,7 +373,7 @@ impl Group { tracing::debug!("Sending Join Message for local member: {:?}", &with); let join_evt = GroupNetEvent::Join(JoinEvent { member: with }); let buf = bincode::serialize(&join_evt).unwrap(); - let _ = state.group_publisher.put(buf).res().await; + let _ = state.group_publisher.put(buf).await; let task_controller = TaskController::default(); // If the liveliness is manual it is the user who has to assert it. diff --git a/zenoh-ext/src/publication_cache.rs b/zenoh-ext/src/publication_cache.rs index 7080b44ac4..11fb8fb72a 100644 --- a/zenoh-ext/src/publication_cache.rs +++ b/zenoh-ext/src/publication_cache.rs @@ -13,12 +13,13 @@ // use std::collections::{HashMap, VecDeque}; use std::convert::TryInto; -use std::future::Ready; +use std::future::{IntoFuture, Ready}; use std::time::Duration; use zenoh::core::Error; -use zenoh::core::{AsyncResolve, Resolvable, Resolve, SyncResolve}; +use zenoh::core::{Resolvable, Resolve}; use zenoh::internal::{ResolveFuture, TerminatableTask}; use zenoh::key_expr::{keyexpr, KeyExpr, OwnedKeyExpr}; +use zenoh::prelude::Wait; use zenoh::queryable::{Query, Queryable}; use zenoh::runtime::ZRuntime; use zenoh::sample::{Locality, Sample}; @@ -96,17 +97,18 @@ impl<'a> Resolvable for PublicationCacheBuilder<'a, '_, '_> { type To = ZResult>; } -impl SyncResolve for PublicationCacheBuilder<'_, '_, '_> { - fn res_sync(self) -> ::To { +impl Wait for PublicationCacheBuilder<'_, '_, '_> { + fn wait(self) -> ::To { PublicationCache::new(self) } } -impl<'a> AsyncResolve for PublicationCacheBuilder<'a, '_, '_> { - type Future = Ready; +impl<'a> IntoFuture for PublicationCacheBuilder<'a, '_, '_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -149,7 +151,7 @@ impl<'a> PublicationCache<'a> { .session .declare_subscriber(&key_expr) .allowed_origin(Locality::SessionLocal) - .res_sync()?; + .wait()?; // declare the queryable which returns the cached publications let mut queryable = conf.session.declare_queryable(&queryable_key_expr); @@ -159,7 +161,7 @@ impl<'a> PublicationCache<'a> { if let Some(complete) = conf.complete { queryable = queryable.complete(complete); } - let queryable = queryable.res_sync()?; + let queryable = queryable.wait()?; // take local ownership of stuff to be moved into task let sub_recv = local_sub.handler().clone(); @@ -215,7 +217,7 @@ impl<'a> PublicationCache<'a> { continue; } } - if let Err(e) = query.reply_sample(sample.clone()).res_async().await { + if let Err(e) = query.reply_sample(sample.clone()).await { tracing::warn!("Error replying to query: {}", e); } } @@ -229,7 +231,7 @@ impl<'a> PublicationCache<'a> { continue; } } - if let Err(e) = query.reply_sample(sample.clone()).res_async().await { + if let Err(e) = query.reply_sample(sample.clone()).await { tracing::warn!("Error replying to query: {}", e); } } @@ -261,8 +263,8 @@ impl<'a> PublicationCache<'a> { local_sub, task, } = self; - _queryable.undeclare().res_async().await?; - local_sub.undeclare().res_async().await?; + _queryable.undeclare().await?; + local_sub.undeclare().await?; task.terminate(Duration::from_secs(10)); Ok(()) }) diff --git a/zenoh-ext/src/querying_subscriber.rs b/zenoh-ext/src/querying_subscriber.rs index 35eb9afe46..6febef7395 100644 --- a/zenoh-ext/src/querying_subscriber.rs +++ b/zenoh-ext/src/querying_subscriber.rs @@ -13,14 +13,15 @@ // use std::collections::{btree_map, BTreeMap, VecDeque}; use std::convert::TryInto; -use std::future::Ready; +use std::future::{IntoFuture, Ready}; use std::mem::swap; use std::sync::{Arc, Mutex}; use std::time::Duration; -use zenoh::core::{AsyncResolve, Resolvable, Resolve, SyncResolve}; +use zenoh::core::{Resolvable, Resolve}; use zenoh::handlers::{locked, DefaultHandler, IntoHandler}; use zenoh::internal::zlock; use zenoh::key_expr::KeyExpr; +use zenoh::prelude::Wait; use zenoh::query::{QueryConsolidation, QueryTarget, ReplyKeyExpr}; use zenoh::sample::{Locality, Sample, SampleBuilder, TimestampBuilderTrait}; use zenoh::selector::Selector; @@ -223,13 +224,13 @@ where type To = ZResult>; } -impl SyncResolve for QueryingSubscriberBuilder<'_, '_, KeySpace, Handler> +impl Wait for QueryingSubscriberBuilder<'_, '_, KeySpace, Handler> where KeySpace: Into + Clone, Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let session = self.session.clone(); let key_expr = self.key_expr?; let key_space = self.key_space.clone().into(); @@ -257,31 +258,32 @@ where .consolidation(query_consolidation) .accept_replies(query_accept_replies) .timeout(query_timeout) - .res_sync(), + .wait(), crate::KeySpace::Liveliness => session .liveliness() .get(key_expr) .callback(cb) .timeout(query_timeout) - .res_sync(), + .wait(), }, handler: self.handler, phantom: std::marker::PhantomData, } - .res_sync() + .wait() } } -impl<'a, KeySpace, Handler> AsyncResolve for QueryingSubscriberBuilder<'a, '_, KeySpace, Handler> +impl<'a, KeySpace, Handler> IntoFuture for QueryingSubscriberBuilder<'a, '_, KeySpace, Handler> where KeySpace: Into + Clone, Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -551,14 +553,14 @@ impl< Handler, Fetch: FnOnce(Box) -> ZResult<()> + Send + Sync, TryIntoSample, - > SyncResolve for FetchingSubscriberBuilder<'_, '_, KeySpace, Handler, Fetch, TryIntoSample> + > Wait for FetchingSubscriberBuilder<'_, '_, KeySpace, Handler, Fetch, TryIntoSample> where KeySpace: Into, Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, TryIntoSample: ExtractSample + Send + Sync, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { FetchingSubscriber::new(self.with_static_keys()) } } @@ -569,17 +571,18 @@ impl< Handler, Fetch: FnOnce(Box) -> ZResult<()> + Send + Sync, TryIntoSample, - > AsyncResolve for FetchingSubscriberBuilder<'a, '_, KeySpace, Handler, Fetch, TryIntoSample> + > IntoFuture for FetchingSubscriberBuilder<'a, '_, KeySpace, Handler, Fetch, TryIntoSample> where KeySpace: Into, Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, TryIntoSample: ExtractSample + Send + Sync, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -595,20 +598,18 @@ where /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// use zenoh_ext::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expr") /// .fetching( |cb| { -/// use zenoh::prelude::sync::SyncResolve; /// session /// .get("key/expr") /// .callback(cb) -/// .res_sync() +/// .wait() /// }) -/// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -689,13 +690,13 @@ impl<'a, Handler> FetchingSubscriber<'a, Handler> { .callback(sub_callback) .reliability(conf.reliability) .allowed_origin(conf.origin) - .res_sync()?, + .wait()?, crate::KeySpace::Liveliness => conf .session .liveliness() .declare_subscriber(&key_expr) .callback(sub_callback) - .res_sync()?, + .wait()?, }; let fetch_subscriber = FetchingSubscriber { @@ -732,10 +733,10 @@ impl<'a, Handler> FetchingSubscriber<'a, Handler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut subscriber = session /// .declare_subscriber("key/expr") /// .fetching( |cb| { @@ -743,9 +744,8 @@ impl<'a, Handler> FetchingSubscriber<'a, Handler> { /// session /// .get("key/expr") /// .callback(cb) - /// .res_sync() + /// .wait() /// }) - /// .res() /// .await /// .unwrap(); /// @@ -756,9 +756,8 @@ impl<'a, Handler> FetchingSubscriber<'a, Handler> { /// session /// .get("key/expr") /// .callback(cb) - /// .res_sync() + /// .wait() /// }) - /// .res() /// .await /// .unwrap(); /// # } @@ -814,10 +813,10 @@ impl Drop for RepliesHandler { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// # use zenoh::prelude::r#async::*; +/// # use zenoh::prelude::*; /// # use zenoh_ext::*; /// # -/// # let session = zenoh::open(config::peer()).res().await.unwrap(); +/// # let session = zenoh::open(config::peer()).await.unwrap(); /// # let mut fetching_subscriber = session /// # .declare_subscriber("key/expr") /// # .fetching( |cb| { @@ -825,9 +824,8 @@ impl Drop for RepliesHandler { /// # session /// # .get("key/expr") /// # .callback(cb) -/// # .res_sync() +/// # .wait() /// # }) -/// # .res() /// # .await /// # .unwrap(); /// # @@ -837,9 +835,8 @@ impl Drop for RepliesHandler { /// session /// .get("key/expr") /// .callback(cb) -/// .res_sync() +/// .wait() /// }) -/// .res() /// .await /// .unwrap(); /// # } @@ -865,26 +862,27 @@ where type To = ZResult<()>; } -impl) -> ZResult<()>, TryIntoSample> - SyncResolve for FetchBuilder +impl) -> ZResult<()>, TryIntoSample> Wait + for FetchBuilder where TryIntoSample: ExtractSample, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let handler = register_handler(self.state, self.callback); run_fetch(self.fetch, handler) } } impl) -> ZResult<()>, TryIntoSample> - AsyncResolve for FetchBuilder + IntoFuture for FetchBuilder where TryIntoSample: ExtractSample, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh-ext/src/session_ext.rs b/zenoh-ext/src/session_ext.rs index 3f23239b29..d005cafc86 100644 --- a/zenoh-ext/src/session_ext.rs +++ b/zenoh-ext/src/session_ext.rs @@ -62,14 +62,14 @@ impl<'s> SessionExt<'s, 'static> for Arc { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh::config::ModeDependentValue::Unique; /// use zenoh_ext::SessionExt; /// /// let mut config = config::default(); /// config.timestamping.set_enabled(Some(Unique(true))); - /// let session = zenoh::open(config).res().await.unwrap().into_arc(); - /// let publication_cache = session.declare_publication_cache("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config).await.unwrap().into_arc(); + /// let publication_cache = session.declare_publication_cache("key/expression").await.unwrap(); /// tokio::task::spawn(async move { /// publication_cache.key_expr(); /// }).await; diff --git a/zenoh-ext/src/subscriber_ext.rs b/zenoh-ext/src/subscriber_ext.rs index 3176745c95..8c3b1239b6 100644 --- a/zenoh-ext/src/subscriber_ext.rs +++ b/zenoh-ext/src/subscriber_ext.rs @@ -60,10 +60,10 @@ pub trait SubscriberBuilderExt<'a, 'b, Handler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expr") /// .fetching( |cb| { @@ -71,9 +71,8 @@ pub trait SubscriberBuilderExt<'a, 'b, Handler> { /// session /// .get("key/expr") /// .callback(cb) - /// .res_sync() + /// .wait() /// }) - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -106,14 +105,13 @@ pub trait SubscriberBuilderExt<'a, 'b, Handler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expr") /// .querying() - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -141,10 +139,10 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> for SubscriberBuilde /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expr") /// .fetching( |cb| { @@ -152,9 +150,8 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> for SubscriberBuilde /// session /// .get("key/expr") /// .callback(cb) - /// .res_sync() + /// .wait() /// }) - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -199,14 +196,13 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> for SubscriberBuilde /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expr") /// .querying() - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -254,10 +250,10 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .liveliness() /// .declare_subscriber("key/expr") @@ -267,9 +263,8 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> /// .liveliness() /// .get("key/expr") /// .callback(cb) - /// .res_sync() + /// .wait() /// }) - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -315,15 +310,14 @@ impl<'a, 'b, Handler> SubscriberBuilderExt<'a, 'b, Handler> /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// use zenoh_ext::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .liveliness() /// .declare_subscriber("key/expr") /// .querying() - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { diff --git a/zenoh/src/api/admin.rs b/zenoh/src/api/admin.rs index c221d7f27c..e720fde1c3 100644 --- a/zenoh/src/api/admin.rs +++ b/zenoh/src/api/admin.rs @@ -25,7 +25,7 @@ use std::{ hash::{Hash, Hasher}, sync::Arc, }; -use zenoh_core::{Result as ZResult, SyncResolve}; +use zenoh_core::{Result as ZResult, Wait}; use zenoh_keyexpr::keyexpr; use zenoh_protocol::{core::WireExpr, network::NetworkMessage}; use zenoh_transport::{ @@ -72,7 +72,7 @@ pub(crate) fn on_admin_query(session: &Session, query: Query) { if let Ok(value) = serde_json::value::to_value(peer.clone()) { match ZBytes::try_from(value) { Ok(zbuf) => { - let _ = query.reply(key_expr, zbuf).res_sync(); + let _ = query.reply(key_expr, zbuf).wait(); } Err(e) => tracing::debug!("Admin query error: {}", e), } @@ -89,7 +89,7 @@ pub(crate) fn on_admin_query(session: &Session, query: Query) { if let Ok(value) = serde_json::value::to_value(link) { match ZBytes::try_from(value) { Ok(zbuf) => { - let _ = query.reply(key_expr, zbuf).res_sync(); + let _ = query.reply(key_expr, zbuf).wait(); } Err(e) => tracing::debug!("Admin query error: {}", e), } diff --git a/zenoh/src/api/builders/publication.rs b/zenoh/src/api/builders/publication.rs index 711cb063f6..5285825b29 100644 --- a/zenoh/src/api/builders/publication.rs +++ b/zenoh/src/api/builders/publication.rs @@ -1,5 +1,3 @@ -use std::future::Ready; - // // Copyright (c) 2024 ZettaScale Technology // @@ -27,7 +25,8 @@ use crate::api::sample::SourceInfo; use crate::api::session::SessionRef; use crate::api::value::Value; use crate::api::{encoding::Encoding, publication::Publisher}; -use zenoh_core::{AsyncResolve, Resolvable, Result as ZResult, SyncResolve}; +use std::future::{IntoFuture, Ready}; +use zenoh_core::{Resolvable, Result as ZResult, Wait}; use zenoh_protocol::core::CongestionControl; use zenoh_protocol::network::Mapping; @@ -57,14 +56,13 @@ pub struct PublicationBuilderDelete; /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// session /// .put("key/expression", "payload") /// .encoding(Encoding::TEXT_PLAIN) /// .congestion_control(CongestionControl::Block) -/// .res() /// .await /// .unwrap(); /// # } @@ -179,9 +177,9 @@ impl Resolvable for PublicationBuilder { type To = ZResult<()>; } -impl SyncResolve for PublicationBuilder, PublicationBuilderPut> { +impl Wait for PublicationBuilder, PublicationBuilderPut> { #[inline] - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let publisher = self.publisher.create_one_shot_publisher()?; publisher.resolve_put( self.kind.payload, @@ -196,9 +194,9 @@ impl SyncResolve for PublicationBuilder, PublicationBui } } -impl SyncResolve for PublicationBuilder, PublicationBuilderDelete> { +impl Wait for PublicationBuilder, PublicationBuilderDelete> { #[inline] - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let publisher = self.publisher.create_one_shot_publisher()?; publisher.resolve_put( ZBytes::empty(), @@ -213,19 +211,21 @@ impl SyncResolve for PublicationBuilder, PublicationBui } } -impl AsyncResolve for PublicationBuilder, PublicationBuilderPut> { - type Future = Ready; +impl IntoFuture for PublicationBuilder, PublicationBuilderPut> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } -impl AsyncResolve for PublicationBuilder, PublicationBuilderDelete> { - type Future = Ready; +impl IntoFuture for PublicationBuilder, PublicationBuilderDelete> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -235,13 +235,12 @@ impl AsyncResolve for PublicationBuilder, PublicationBu /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let publisher = session /// .declare_publisher("key/expression") /// .congestion_control(CongestionControl::Block) -/// .res() /// .await /// .unwrap(); /// # } @@ -327,12 +326,12 @@ impl<'a, 'b> Resolvable for PublisherBuilder<'a, 'b> { type To = ZResult>; } -impl<'a, 'b> SyncResolve for PublisherBuilder<'a, 'b> { - fn res_sync(self) -> ::To { +impl<'a, 'b> Wait for PublisherBuilder<'a, 'b> { + fn wait(self) -> ::To { let mut key_expr = self.key_expr?; if !key_expr.is_fully_optimized(&self.session) { let session_id = self.session.id; - let expr_id = self.session.declare_prefix(key_expr.as_str()).res_sync(); + let expr_id = self.session.declare_prefix(key_expr.as_str()).wait(); let prefix_len = key_expr .len() .try_into() @@ -362,7 +361,7 @@ impl<'a, 'b> SyncResolve for PublisherBuilder<'a, 'b> { } self.session .declare_publication_intent(key_expr.clone()) - .res_sync()?; + .wait()?; #[cfg(feature = "unstable")] let eid = self.session.runtime.next_id(); let publisher = Publisher { @@ -380,16 +379,17 @@ impl<'a, 'b> SyncResolve for PublisherBuilder<'a, 'b> { } } -impl<'a, 'b> AsyncResolve for PublisherBuilder<'a, 'b> { - type Future = Ready; +impl<'a, 'b> IntoFuture for PublisherBuilder<'a, 'b> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } -impl SyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderPut> { - fn res_sync(self) -> ::To { +impl Wait for PublicationBuilder<&Publisher<'_>, PublicationBuilderPut> { + fn wait(self) -> ::To { self.publisher.resolve_put( self.kind.payload, SampleKind::Put, @@ -403,8 +403,8 @@ impl SyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderPut> { } } -impl SyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderDelete> { - fn res_sync(self) -> ::To { +impl Wait for PublicationBuilder<&Publisher<'_>, PublicationBuilderDelete> { + fn wait(self) -> ::To { self.publisher.resolve_put( ZBytes::empty(), SampleKind::Delete, @@ -418,18 +418,20 @@ impl SyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderDelete } } -impl AsyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderPut> { - type Future = Ready; +impl IntoFuture for PublicationBuilder<&Publisher<'_>, PublicationBuilderPut> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } -impl AsyncResolve for PublicationBuilder<&Publisher<'_>, PublicationBuilderDelete> { - type Future = Ready; +impl IntoFuture for PublicationBuilder<&Publisher<'_>, PublicationBuilderDelete> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/info.rs b/zenoh/src/api/info.rs index dbcad9c50c..a6f8ff1629 100644 --- a/zenoh/src/api/info.rs +++ b/zenoh/src/api/info.rs @@ -14,8 +14,8 @@ //! Tools to access information about the current zenoh [`Session`](crate::Session). use super::session::SessionRef; -use std::future::Ready; -use zenoh_core::{AsyncResolve, Resolvable, SyncResolve}; +use std::future::{IntoFuture, Ready}; +use zenoh_core::{Resolvable, Wait}; use zenoh_protocol::core::{WhatAmI, ZenohId}; /// A builder retuned by [`SessionInfo::zid()`](SessionInfo::zid) that allows @@ -25,10 +25,10 @@ use zenoh_protocol::core::{WhatAmI, ZenohId}; /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let zid = session.info().zid().res().await; +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let zid = session.info().zid().await; /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -41,17 +41,18 @@ impl<'a> Resolvable for ZidBuilder<'a> { type To = ZenohId; } -impl<'a> SyncResolve for ZidBuilder<'a> { - fn res_sync(self) -> Self::To { +impl<'a> Wait for ZidBuilder<'a> { + fn wait(self) -> Self::To { self.session.runtime.zid() } } -impl<'a> AsyncResolve for ZidBuilder<'a> { - type Future = Ready; +impl<'a> IntoFuture for ZidBuilder<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -63,10 +64,10 @@ impl<'a> AsyncResolve for ZidBuilder<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let mut routers_zid = session.info().routers_zid().res().await; +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let mut routers_zid = session.info().routers_zid().await; /// while let Some(router_zid) = routers_zid.next() {} /// # } /// ``` @@ -80,8 +81,8 @@ impl<'a> Resolvable for RoutersZidBuilder<'a> { type To = Box + Send + Sync>; } -impl<'a> SyncResolve for RoutersZidBuilder<'a> { - fn res_sync(self) -> Self::To { +impl<'a> Wait for RoutersZidBuilder<'a> { + fn wait(self) -> Self::To { Box::new( zenoh_runtime::ZRuntime::Application .block_in_place(self.session.runtime.manager().get_transports_unicast()) @@ -96,11 +97,12 @@ impl<'a> SyncResolve for RoutersZidBuilder<'a> { } } -impl<'a> AsyncResolve for RoutersZidBuilder<'a> { - type Future = Ready; +impl<'a> IntoFuture for RoutersZidBuilder<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -111,11 +113,11 @@ impl<'a> AsyncResolve for RoutersZidBuilder<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let zid = session.info().zid().res().await; -/// let mut peers_zid = session.info().peers_zid().res().await; +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let zid = session.info().zid().await; +/// let mut peers_zid = session.info().peers_zid().await; /// while let Some(peer_zid) = peers_zid.next() {} /// # } /// ``` @@ -129,8 +131,8 @@ impl<'a> Resolvable for PeersZidBuilder<'a> { type To = Box + Send + Sync>; } -impl<'a> SyncResolve for PeersZidBuilder<'a> { - fn res_sync(self) -> ::To { +impl<'a> Wait for PeersZidBuilder<'a> { + fn wait(self) -> ::To { Box::new( zenoh_runtime::ZRuntime::Application .block_in_place(self.session.runtime.manager().get_transports_unicast()) @@ -145,11 +147,12 @@ impl<'a> SyncResolve for PeersZidBuilder<'a> { } } -impl<'a> AsyncResolve for PeersZidBuilder<'a> { - type Future = Ready; +impl<'a> IntoFuture for PeersZidBuilder<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -160,11 +163,11 @@ impl<'a> AsyncResolve for PeersZidBuilder<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let info = session.info(); -/// let zid = info.zid().res().await; +/// let zid = info.zid().await; /// # } /// ``` pub struct SessionInfo<'a> { @@ -178,10 +181,10 @@ impl SessionInfo<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let zid = session.info().zid().res().await; + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let zid = session.info().zid().await; /// # } /// ``` pub fn zid(&self) -> ZidBuilder<'_> { @@ -197,10 +200,10 @@ impl SessionInfo<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let mut routers_zid = session.info().routers_zid().res().await; + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let mut routers_zid = session.info().routers_zid().await; /// while let Some(router_zid) = routers_zid.next() {} /// # } /// ``` @@ -216,10 +219,10 @@ impl SessionInfo<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let mut peers_zid = session.info().peers_zid().res().await; + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let mut peers_zid = session.info().peers_zid().await; /// while let Some(peer_zid) = peers_zid.next() {} /// # } /// ``` diff --git a/zenoh/src/api/key_expr.rs b/zenoh/src/api/key_expr.rs index 774cf28790..20dcf9cbee 100644 --- a/zenoh/src/api/key_expr.rs +++ b/zenoh/src/api/key_expr.rs @@ -14,12 +14,13 @@ use super::session::{Session, Undeclarable}; use crate::net::primitives::Primitives; +use std::future::IntoFuture; use std::{ convert::{TryFrom, TryInto}, future::Ready, str::FromStr, }; -use zenoh_core::{AsyncResolve, Resolvable, SyncResolve}; +use zenoh_core::{Resolvable, Wait}; use zenoh_keyexpr::{keyexpr, OwnedKeyExpr}; use zenoh_protocol::{ core::{key_expr::canon::Canonizable, ExprId, WireExpr}, @@ -562,11 +563,11 @@ impl<'a> Undeclarable<&'a Session, KeyExprUndeclaration<'a>> for KeyExpr<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let key_expr = session.declare_keyexpr("key/expression").res().await.unwrap(); -/// session.undeclare(key_expr).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let key_expr = session.declare_keyexpr("key/expression").await.unwrap(); +/// session.undeclare(key_expr).await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -579,8 +580,8 @@ impl Resolvable for KeyExprUndeclaration<'_> { type To = ZResult<()>; } -impl SyncResolve for KeyExprUndeclaration<'_> { - fn res_sync(self) -> ::To { +impl Wait for KeyExprUndeclaration<'_> { + fn wait(self) -> ::To { let KeyExprUndeclaration { session, expr } = self; let expr_id = match &expr.0 { KeyExprInner::Wire { @@ -629,11 +630,12 @@ impl SyncResolve for KeyExprUndeclaration<'_> { } } -impl AsyncResolve for KeyExprUndeclaration<'_> { - type Future = Ready; +impl IntoFuture for KeyExprUndeclaration<'_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/liveliness.rs b/zenoh/src/api/liveliness.rs index 761704d7d2..f7235426c3 100644 --- a/zenoh/src/api/liveliness.rs +++ b/zenoh/src/api/liveliness.rs @@ -21,10 +21,11 @@ use super::{ subscriber::{Subscriber, SubscriberInner}, Id, }; +use std::future::IntoFuture; use std::{convert::TryInto, future::Ready, sync::Arc, time::Duration}; use zenoh_config::unwrap_or_default; -use zenoh_core::Resolve; -use zenoh_core::{AsyncResolve, Resolvable, Result as ZResult, SyncResolve}; +use zenoh_core::{Resolvable, Result as ZResult}; +use zenoh_core::{Resolve, Wait}; use zenoh_keyexpr::keyexpr; use zenoh_protocol::network::{declare::subscriber::ext::SubscriberInfo, request}; @@ -55,13 +56,12 @@ lazy_static::lazy_static!( /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") -/// .res() /// .await /// .unwrap(); /// # } @@ -83,13 +83,12 @@ impl<'a> Liveliness<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") - /// .res() /// .await /// .unwrap(); /// # } @@ -119,10 +118,10 @@ impl<'a> Liveliness<'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let subscriber = session.liveliness().declare_subscriber("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let subscriber = session.liveliness().declare_subscriber("key/expression").await.unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { /// match sample.kind() { /// SampleKind::Put => println!("New liveliness: {}", sample.key_expr()), @@ -157,10 +156,10 @@ impl<'a> Liveliness<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let replies = session.liveliness().get("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let replies = session.liveliness().get("key/expression").await.unwrap(); /// while let Ok(reply) = replies.recv_async().await { /// if let Ok(sample) = reply.result() { /// println!(">> Liveliness token {}", sample.key_expr()); @@ -197,13 +196,12 @@ impl<'a> Liveliness<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") -/// .res() /// .await /// .unwrap(); /// # } @@ -222,9 +220,9 @@ impl<'a> Resolvable for LivelinessTokenBuilder<'a, '_> { } #[zenoh_macros::unstable] -impl SyncResolve for LivelinessTokenBuilder<'_, '_> { +impl Wait for LivelinessTokenBuilder<'_, '_> { #[inline] - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let session = self.session; let key_expr = self.key_expr?.into_owned(); session @@ -238,11 +236,12 @@ impl SyncResolve for LivelinessTokenBuilder<'_, '_> { } #[zenoh_macros::unstable] -impl AsyncResolve for LivelinessTokenBuilder<'_, '_> { - type Future = Ready; +impl IntoFuture for LivelinessTokenBuilder<'_, '_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -272,13 +271,12 @@ pub(crate) struct LivelinessTokenState { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") -/// .res() /// .await /// .unwrap(); /// # } @@ -297,17 +295,16 @@ pub struct LivelinessToken<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") -/// .res() /// .await /// .unwrap(); /// -/// liveliness.undeclare().res().await.unwrap(); +/// liveliness.undeclare().await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -322,19 +319,20 @@ impl Resolvable for LivelinessTokenUndeclaration<'_> { } #[zenoh_macros::unstable] -impl SyncResolve for LivelinessTokenUndeclaration<'_> { - fn res_sync(mut self) -> ::To { +impl Wait for LivelinessTokenUndeclaration<'_> { + fn wait(mut self) -> ::To { self.token.alive = false; self.token.session.undeclare_liveliness(self.token.state.id) } } #[zenoh_macros::unstable] -impl<'a> AsyncResolve for LivelinessTokenUndeclaration<'a> { - type Future = Ready; +impl<'a> IntoFuture for LivelinessTokenUndeclaration<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -350,17 +348,16 @@ impl<'a> LivelinessToken<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") - /// .res() /// .await /// .unwrap(); /// - /// liveliness.undeclare().res().await.unwrap(); + /// liveliness.undeclare().await.unwrap(); /// # } /// ``` #[inline] @@ -391,13 +388,12 @@ impl Drop for LivelinessToken<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .best_effort() -/// .res() /// .await /// .unwrap(); /// # } @@ -419,13 +415,12 @@ impl<'a, 'b> LivelinessSubscriberBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback(|sample| { println!("Received: {} {:?}", sample.key_expr(), sample.payload()); }) - /// .res() /// .await /// .unwrap(); /// # } @@ -460,14 +455,13 @@ impl<'a, 'b> LivelinessSubscriberBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut n = 0; /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback_mut(move |_sample| { n += 1; }) - /// .res() /// .await /// .unwrap(); /// # } @@ -490,13 +484,12 @@ impl<'a, 'b> LivelinessSubscriberBuilder<'a, 'b, DefaultHandler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -533,13 +526,13 @@ where } #[zenoh_macros::unstable] -impl<'a, Handler> SyncResolve for LivelinessSubscriberBuilder<'a, '_, Handler> +impl<'a, Handler> Wait for LivelinessSubscriberBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { #[zenoh_macros::unstable] - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let key_expr = self.key_expr?; let session = self.session; let (callback, handler) = self.handler.into_handler(); @@ -563,16 +556,17 @@ where } #[zenoh_macros::unstable] -impl<'a, Handler> AsyncResolve for LivelinessSubscriberBuilder<'a, '_, Handler> +impl<'a, Handler> IntoFuture for LivelinessSubscriberBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; #[zenoh_macros::unstable] - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -583,13 +577,12 @@ where /// # #[tokio::main] /// # async fn main() { /// # use std::convert::TryFrom; -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let tokens = session /// .liveliness() /// .get("key/expression") -/// .res() /// .await /// .unwrap(); /// while let Ok(token) = tokens.recv_async().await { @@ -616,14 +609,13 @@ impl<'a, 'b> LivelinessGetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session /// .liveliness() /// .get("key/expression") /// .callback(|reply| { println!("Received {:?}", reply.result()); }) - /// .res() /// .await /// .unwrap(); /// # } @@ -656,15 +648,14 @@ impl<'a, 'b> LivelinessGetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut n = 0; /// let queryable = session /// .liveliness() /// .get("key/expression") /// .callback_mut(move |reply| {n += 1;}) - /// .res() /// .await /// .unwrap(); /// # } @@ -686,14 +677,13 @@ impl<'a, 'b> LivelinessGetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let replies = session /// .liveliness() /// .get("key/expression") /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(reply) = replies.recv_async().await { @@ -738,12 +728,12 @@ where type To = ZResult; } -impl SyncResolve for LivelinessGetBuilder<'_, '_, Handler> +impl Wait for LivelinessGetBuilder<'_, '_, Handler> where Handler: IntoHandler<'static, Reply> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let (callback, receiver) = self.handler.into_handler(); self.session .query( @@ -764,14 +754,15 @@ where } } -impl AsyncResolve for LivelinessGetBuilder<'_, '_, Handler> +impl IntoFuture for LivelinessGetBuilder<'_, '_, Handler> where Handler: IntoHandler<'static, Reply> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/publication.rs b/zenoh/src/api/publication.rs index f41c35b720..518ddc4d1b 100644 --- a/zenoh/src/api/publication.rs +++ b/zenoh/src/api/publication.rs @@ -25,13 +25,14 @@ use super::{ }; use crate::net::primitives::Primitives; use futures::Sink; +use std::future::IntoFuture; use std::{ convert::TryFrom, future::Ready, pin::Pin, task::{Context, Poll}, }; -use zenoh_core::{zread, AsyncResolve, Resolvable, Resolve, SyncResolve}; +use zenoh_core::{zread, Resolvable, Resolve, Wait}; use zenoh_keyexpr::keyexpr; use zenoh_protocol::{ core::CongestionControl, @@ -86,11 +87,11 @@ impl std::fmt::Debug for PublisherRef<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); -/// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); -/// publisher.put("value").res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); +/// let publisher = session.declare_publisher("key/expression").await.unwrap(); +/// publisher.put("value").await.unwrap(); /// # } /// ``` /// @@ -101,11 +102,11 @@ impl std::fmt::Debug for PublisherRef<'_> { /// # #[tokio::main] /// # async fn main() { /// use futures::StreamExt; -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); -/// let mut subscriber = session.declare_subscriber("key/expression").res().await.unwrap(); -/// let publisher = session.declare_publisher("another/key/expression").res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); +/// let mut subscriber = session.declare_subscriber("key/expression").await.unwrap(); +/// let publisher = session.declare_publisher("another/key/expression").await.unwrap(); /// subscriber.stream().map(Ok).forward(publisher).await.unwrap(); /// # } /// ``` @@ -128,11 +129,10 @@ impl<'a> Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let publisher = session.declare_publisher("key/expression") - /// .res() /// .await /// .unwrap(); /// let publisher_id = publisher.id(); @@ -184,11 +184,11 @@ impl<'a> Publisher<'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap().into_arc(); - /// let matching_listener = publisher.matching_listener().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap().into_arc(); + /// let matching_listener = publisher.matching_listener().await.unwrap(); /// /// tokio::task::spawn(async move { /// while let Ok(matching_status) = matching_listener.recv_async().await { @@ -212,11 +212,11 @@ impl<'a> Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); - /// publisher.put("value").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); + /// publisher.put("value").await.unwrap(); /// # } /// ``` #[inline] @@ -244,11 +244,11 @@ impl<'a> Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); - /// publisher.delete().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); + /// publisher.delete().await.unwrap(); /// # } /// ``` pub fn delete(&self) -> PublisherDeleteBuilder<'_> { @@ -272,13 +272,12 @@ impl<'a> Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); /// let matching_subscribers: bool = publisher /// .matching_status() - /// .res() /// .await /// .unwrap() /// .matching_subscribers(); @@ -301,11 +300,11 @@ impl<'a> Publisher<'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); - /// let matching_listener = publisher.matching_listener().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); + /// let matching_listener = publisher.matching_listener().await.unwrap(); /// while let Ok(matching_status) = matching_listener.recv_async().await { /// if matching_status.matching_subscribers() { /// println!("Publisher has matching subscribers."); @@ -329,11 +328,11 @@ impl<'a> Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); - /// publisher.undeclare().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); + /// publisher.undeclare().await.unwrap(); /// # } /// ``` pub fn undeclare(self) -> impl Resolve> + 'a { @@ -353,11 +352,11 @@ impl<'a> Publisher<'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); -/// let publisher = session.declare_publisher("key/expression").res().await.unwrap().into_arc(); -/// let matching_listener = publisher.matching_listener().res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); +/// let publisher = session.declare_publisher("key/expression").await.unwrap().into_arc(); +/// let matching_listener = publisher.matching_listener().await.unwrap(); /// /// tokio::task::spawn(async move { /// while let Ok(matching_status) = matching_listener.recv_async().await { @@ -376,11 +375,11 @@ pub trait PublisherDeclarations { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap().into_arc(); - /// let matching_listener = publisher.matching_listener().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap().into_arc(); + /// let matching_listener = publisher.matching_listener().await.unwrap(); /// /// tokio::task::spawn(async move { /// while let Ok(matching_status) = matching_listener.recv_async().await { @@ -403,11 +402,11 @@ impl PublisherDeclarations for std::sync::Arc> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap().into_arc(); - /// let matching_listener = publisher.matching_listener().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap().into_arc(); + /// let matching_listener = publisher.matching_listener().await.unwrap(); /// /// tokio::task::spawn(async move { /// while let Ok(matching_status) = matching_listener.recv_async().await { @@ -441,11 +440,11 @@ impl<'a> Undeclarable<(), PublisherUndeclaration<'a>> for Publisher<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); -/// publisher.undeclare().res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let publisher = session.declare_publisher("key/expression").await.unwrap(); +/// publisher.undeclare().await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -457,24 +456,25 @@ impl Resolvable for PublisherUndeclaration<'_> { type To = ZResult<()>; } -impl SyncResolve for PublisherUndeclaration<'_> { - fn res_sync(mut self) -> ::To { +impl Wait for PublisherUndeclaration<'_> { + fn wait(mut self) -> ::To { let Publisher { session, key_expr, .. } = &self.publisher; session .undeclare_publication_intent(key_expr.clone()) - .res_sync()?; + .wait()?; self.publisher.key_expr = unsafe { keyexpr::from_str_unchecked("") }.into(); Ok(()) } } -impl AsyncResolve for PublisherUndeclaration<'_> { - type Future = Ready; +impl IntoFuture for PublisherUndeclaration<'_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -484,7 +484,7 @@ impl Drop for Publisher<'_> { let _ = self .session .undeclare_publication_intent(self.key_expr.clone()) - .res_sync(); + .wait(); } } } @@ -726,11 +726,11 @@ impl TryFrom for Priority { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); -/// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); -/// let matching_status = publisher.matching_status().res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); +/// let publisher = session.declare_publisher("key/expression").await.unwrap(); +/// let matching_status = publisher.matching_status().await.unwrap(); /// # } /// ``` #[zenoh_macros::unstable] @@ -747,13 +747,12 @@ impl MatchingStatus { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); /// let matching_subscribers: bool = publisher /// .matching_status() - /// .res() /// .await /// .unwrap() /// .matching_subscribers(); @@ -780,10 +779,10 @@ impl<'a> MatchingListenerBuilder<'a, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); /// let matching_listener = publisher /// .matching_listener() /// .callback(|matching_status| { @@ -793,7 +792,6 @@ impl<'a> MatchingListenerBuilder<'a, DefaultHandler> { /// println!("Publisher has NO MORE matching subscribers."); /// } /// }) - /// .res() /// .await /// .unwrap(); /// # } @@ -820,15 +818,14 @@ impl<'a> MatchingListenerBuilder<'a, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let mut n = 0; - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); /// let matching_listener = publisher /// .matching_listener() /// .callback_mut(move |_matching_status| { n += 1; }) - /// .res() /// .await /// .unwrap(); /// # } @@ -851,14 +848,13 @@ impl<'a> MatchingListenerBuilder<'a, DefaultHandler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); /// let matching_listener = publisher /// .matching_listener() /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(matching_status) = matching_listener.recv_async().await { @@ -894,13 +890,13 @@ where } #[zenoh_macros::unstable] -impl<'a, Handler> SyncResolve for MatchingListenerBuilder<'a, Handler> +impl<'a, Handler> Wait for MatchingListenerBuilder<'a, Handler> where Handler: IntoHandler<'static, MatchingStatus> + Send, Handler::Handler: Send, { #[zenoh_macros::unstable] - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let (callback, receiver) = self.handler.into_handler(); self.publisher .session @@ -917,16 +913,17 @@ where } #[zenoh_macros::unstable] -impl<'a, Handler> AsyncResolve for MatchingListenerBuilder<'a, Handler> +impl<'a, Handler> IntoFuture for MatchingListenerBuilder<'a, Handler> where Handler: IntoHandler<'static, MatchingStatus> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; #[zenoh_macros::unstable] - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -978,11 +975,11 @@ impl<'a> Undeclarable<(), MatchingListenerUndeclaration<'a>> for MatchingListene /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); -/// let matching_listener = publisher.matching_listener().res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let publisher = session.declare_publisher("key/expression").await.unwrap(); +/// let matching_listener = publisher.matching_listener().await.unwrap(); /// while let Ok(matching_status) = matching_listener.recv_async().await { /// if matching_status.matching_subscribers() { /// println!("Publisher has matching subscribers."); @@ -1009,12 +1006,12 @@ impl<'a, Receiver> MatchingListener<'a, Receiver> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let publisher = session.declare_publisher("key/expression").res().await.unwrap(); - /// let matching_listener = publisher.matching_listener().res().await.unwrap(); - /// matching_listener.undeclare().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let publisher = session.declare_publisher("key/expression").await.unwrap(); + /// let matching_listener = publisher.matching_listener().await.unwrap(); + /// matching_listener.undeclare().await.unwrap(); /// # } /// ``` #[inline] @@ -1056,8 +1053,8 @@ impl Resolvable for MatchingListenerUndeclaration<'_> { } #[zenoh_macros::unstable] -impl SyncResolve for MatchingListenerUndeclaration<'_> { - fn res_sync(mut self) -> ::To { +impl Wait for MatchingListenerUndeclaration<'_> { + fn wait(mut self) -> ::To { self.subscriber.alive = false; self.subscriber .publisher @@ -1067,11 +1064,12 @@ impl SyncResolve for MatchingListenerUndeclaration<'_> { } #[zenoh_macros::unstable] -impl AsyncResolve for MatchingListenerUndeclaration<'_> { - type Future = Ready; +impl IntoFuture for MatchingListenerUndeclaration<'_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -1091,7 +1089,7 @@ impl Drop for MatchingListenerInner<'_> { mod tests { use crate::api::{sample::SampleKind, session::SessionDeclarations}; use zenoh_config::Config; - use zenoh_core::SyncResolve; + use zenoh_core::Wait; #[test] fn priority_from() { @@ -1125,13 +1123,13 @@ mod tests { const VALUE: &str = "zenoh"; fn sample_kind_integrity_in_publication_with(kind: SampleKind) { - let session = open(Config::default()).res().unwrap(); - let sub = session.declare_subscriber(KEY_EXPR).res().unwrap(); - let pub_ = session.declare_publisher(KEY_EXPR).res().unwrap(); + let session = open(Config::default()).wait().unwrap(); + let sub = session.declare_subscriber(KEY_EXPR).wait().unwrap(); + let pub_ = session.declare_publisher(KEY_EXPR).wait().unwrap(); match kind { - SampleKind::Put => pub_.put(VALUE).res().unwrap(), - SampleKind::Delete => pub_.delete().res().unwrap(), + SampleKind::Put => pub_.put(VALUE).wait().unwrap(), + SampleKind::Delete => pub_.delete().wait().unwrap(), } let sample = sub.recv().unwrap(); @@ -1148,18 +1146,17 @@ mod tests { #[test] fn sample_kind_integrity_in_put_builder() { use crate::api::session::open; - use zenoh_core::SyncResolve; const KEY_EXPR: &str = "test/sample_kind_integrity/put_builder"; const VALUE: &str = "zenoh"; fn sample_kind_integrity_in_put_builder_with(kind: SampleKind) { - let session = open(Config::default()).res().unwrap(); - let sub = session.declare_subscriber(KEY_EXPR).res().unwrap(); + let session = open(Config::default()).wait().unwrap(); + let sub = session.declare_subscriber(KEY_EXPR).wait().unwrap(); match kind { - SampleKind::Put => session.put(KEY_EXPR, VALUE).res().unwrap(), - SampleKind::Delete => session.delete(KEY_EXPR).res().unwrap(), + SampleKind::Put => session.put(KEY_EXPR, VALUE).wait().unwrap(), + SampleKind::Delete => session.delete(KEY_EXPR).wait().unwrap(), } let sample = sub.recv().unwrap(); diff --git a/zenoh/src/api/query.rs b/zenoh/src/api/query.rs index 1cb4078ee6..311402b618 100644 --- a/zenoh/src/api/query.rs +++ b/zenoh/src/api/query.rs @@ -24,8 +24,9 @@ use super::{ session::Session, value::Value, }; +use std::future::IntoFuture; use std::{collections::HashMap, future::Ready, time::Duration}; -use zenoh_core::{AsyncResolve, Resolvable, SyncResolve}; +use zenoh_core::{Resolvable, Wait}; use zenoh_keyexpr::OwnedKeyExpr; use zenoh_protocol::core::{CongestionControl, ZenohId}; use zenoh_result::ZResult; @@ -120,14 +121,13 @@ pub(crate) struct QueryState { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let replies = session /// .get("key/expression?value>1") /// .target(QueryTarget::All) /// .consolidation(ConsolidationMode::None) -/// .res() /// .await /// .unwrap(); /// while let Ok(reply) = replies.recv_async().await { @@ -225,13 +225,12 @@ impl<'a, 'b> GetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session /// .get("key/expression") /// .callback(|reply| {println!("Received {:?}", reply.result());}) - /// .res() /// .await /// .unwrap(); /// # } @@ -284,14 +283,13 @@ impl<'a, 'b> GetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut n = 0; /// let queryable = session /// .get("key/expression") /// .callback_mut(move |reply| {n += 1;}) - /// .res() /// .await /// .unwrap(); /// # } @@ -313,13 +311,12 @@ impl<'a, 'b> GetBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let replies = session /// .get("key/expression") /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(reply) = replies.recv_async().await { @@ -444,12 +441,12 @@ where type To = ZResult; } -impl SyncResolve for GetBuilder<'_, '_, Handler> +impl Wait for GetBuilder<'_, '_, Handler> where Handler: IntoHandler<'static, Reply> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let (callback, receiver) = self.handler.into_handler(); self.session @@ -472,14 +469,15 @@ where } } -impl AsyncResolve for GetBuilder<'_, '_, Handler> +impl IntoFuture for GetBuilder<'_, '_, Handler> where Handler: IntoHandler<'static, Reply> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/queryable.rs b/zenoh/src/api/queryable.rs index dc13468181..c83b4b6081 100644 --- a/zenoh/src/api/queryable.rs +++ b/zenoh/src/api/queryable.rs @@ -25,6 +25,7 @@ use super::{ Id, }; use crate::net::primitives::Primitives; +use std::future::IntoFuture; use std::{ fmt, future::Ready, @@ -32,7 +33,7 @@ use std::{ sync::Arc, }; use uhlc::Timestamp; -use zenoh_core::{AsyncResolve, Resolvable, Resolve, SyncResolve}; +use zenoh_core::{Resolvable, Resolve, Wait}; use zenoh_protocol::{ core::{CongestionControl, EntityId, WireExpr, ZenohId}, network::{response, Mapping, RequestId, Response, ResponseFinal}, @@ -265,17 +266,18 @@ impl Resolvable for ReplySample<'_> { type To = ZResult<()>; } -impl SyncResolve for ReplySample<'_> { - fn res_sync(self) -> ::To { +impl Wait for ReplySample<'_> { + fn wait(self) -> ::To { self.query._reply_sample(self.sample) } } -impl AsyncResolve for ReplySample<'_> { - type Future = Ready; +impl IntoFuture for ReplySample<'_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -383,8 +385,8 @@ impl Resolvable for ReplyBuilder<'_, '_, T> { type To = ZResult<()>; } -impl SyncResolve for ReplyBuilder<'_, '_, ReplyBuilderPut> { - fn res_sync(self) -> ::To { +impl Wait for ReplyBuilder<'_, '_, ReplyBuilderPut> { + fn wait(self) -> ::To { let key_expr = self.key_expr?.into_owned(); let sample = SampleBuilder::put(key_expr, self.kind.payload) .encoding(self.kind.encoding) @@ -398,8 +400,8 @@ impl SyncResolve for ReplyBuilder<'_, '_, ReplyBuilderPut> { } } -impl SyncResolve for ReplyBuilder<'_, '_, ReplyBuilderDelete> { - fn res_sync(self) -> ::To { +impl Wait for ReplyBuilder<'_, '_, ReplyBuilderDelete> { + fn wait(self) -> ::To { let key_expr = self.key_expr?.into_owned(); let sample = SampleBuilder::delete(key_expr) .timestamp(self.timestamp) @@ -472,19 +474,21 @@ impl Query { } } -impl AsyncResolve for ReplyBuilder<'_, '_, ReplyBuilderPut> { - type Future = Ready; +impl IntoFuture for ReplyBuilder<'_, '_, ReplyBuilderPut> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } -impl AsyncResolve for ReplyBuilder<'_, '_, ReplyBuilderDelete> { - type Future = Ready; +impl IntoFuture for ReplyBuilder<'_, '_, ReplyBuilderDelete> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -521,8 +525,8 @@ impl<'a> Resolvable for ReplyErrBuilder<'a> { type To = ZResult<()>; } -impl SyncResolve for ReplyErrBuilder<'_> { - fn res_sync(self) -> ::To { +impl Wait for ReplyErrBuilder<'_> { + fn wait(self) -> ::To { self.query.inner.primitives.send_response(Response { rid: self.query.inner.qid, wire_expr: WireExpr { @@ -549,11 +553,12 @@ impl SyncResolve for ReplyErrBuilder<'_> { } } -impl<'a> AsyncResolve for ReplyErrBuilder<'a> { - type Future = Ready; +impl<'a> IntoFuture for ReplyErrBuilder<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -589,14 +594,13 @@ impl fmt::Debug for QueryableState { /// # #[tokio::main] /// # async fn main() { /// use futures::prelude::*; -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let queryable = session.declare_queryable("key/expression").res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let queryable = session.declare_queryable("key/expression").await.unwrap(); /// while let Ok(query) = queryable.recv_async().await { /// println!(">> Handling query '{}'", query.selector()); /// query.reply(KeyExpr::try_from("key/expression").unwrap(), "value") -/// .res() /// .await /// .unwrap(); /// } @@ -621,11 +625,11 @@ impl<'a> Undeclarable<(), QueryableUndeclaration<'a>> for CallbackQueryable<'a> /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let queryable = session.declare_queryable("key/expression").res().await.unwrap(); -/// queryable.undeclare().res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let queryable = session.declare_queryable("key/expression").await.unwrap(); +/// queryable.undeclare().await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -637,8 +641,8 @@ impl Resolvable for QueryableUndeclaration<'_> { type To = ZResult<()>; } -impl SyncResolve for QueryableUndeclaration<'_> { - fn res_sync(mut self) -> ::To { +impl Wait for QueryableUndeclaration<'_> { + fn wait(mut self) -> ::To { self.queryable.alive = false; self.queryable .session @@ -646,11 +650,12 @@ impl SyncResolve for QueryableUndeclaration<'_> { } } -impl<'a> AsyncResolve for QueryableUndeclaration<'a> { - type Future = Ready; +impl<'a> IntoFuture for QueryableUndeclaration<'a> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -668,10 +673,10 @@ impl Drop for CallbackQueryable<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); -/// let queryable = session.declare_queryable("key/expression").res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); +/// let queryable = session.declare_queryable("key/expression").await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -691,13 +696,12 @@ impl<'a, 'b> QueryableBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session /// .declare_queryable("key/expression") /// .callback(|query| {println!(">> Handling query '{}'", query.selector());}) - /// .res() /// .await /// .unwrap(); /// # } @@ -732,14 +736,13 @@ impl<'a, 'b> QueryableBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut n = 0; /// let queryable = session /// .declare_queryable("key/expression") /// .callback_mut(move |query| {n += 1;}) - /// .res() /// .await /// .unwrap(); /// # } @@ -761,13 +764,12 @@ impl<'a, 'b> QueryableBuilder<'a, 'b, DefaultHandler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session /// .declare_queryable("key/expression") /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(query) = queryable.recv_async().await { @@ -827,19 +829,17 @@ impl<'a, 'b, Handler> QueryableBuilder<'a, 'b, Handler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session /// .declare_queryable("key/expression") /// .with(flume::bounded(32)) -/// .res() /// .await /// .unwrap(); /// while let Ok(query) = queryable.recv_async().await { /// println!(">> Handling query '{}'", query.selector()); /// query.reply(KeyExpr::try_from("key/expression").unwrap(), "value") -/// .res() /// .await /// .unwrap(); /// } @@ -859,11 +859,10 @@ impl<'a, Handler> Queryable<'a, Handler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let queryable = session.declare_queryable("key/expression") - /// .res() /// .await /// .unwrap(); /// let queryable_id = queryable.id(); @@ -925,12 +924,12 @@ where type To = ZResult>; } -impl<'a, Handler> SyncResolve for QueryableBuilder<'a, '_, Handler> +impl<'a, Handler> Wait for QueryableBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Query> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let session = self.session; let (callback, receiver) = self.handler.into_handler(); session @@ -951,14 +950,15 @@ where } } -impl<'a, Handler> AsyncResolve for QueryableBuilder<'a, '_, Handler> +impl<'a, Handler> IntoFuture for QueryableBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Query> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/scouting.rs b/zenoh/src/api/scouting.rs index c4e411dec9..8e7853a411 100644 --- a/zenoh/src/api/scouting.rs +++ b/zenoh/src/api/scouting.rs @@ -13,10 +13,11 @@ // use crate::api::handlers::{locked, Callback, DefaultHandler, IntoHandler}; use crate::net::runtime::{orchestrator::Loop, Runtime}; +use std::future::IntoFuture; use std::time::Duration; use std::{fmt, future::Ready, net::SocketAddr, ops::Deref}; use tokio::net::UdpSocket; -use zenoh_core::{AsyncResolve, Resolvable, SyncResolve}; +use zenoh_core::{Resolvable, Wait}; use zenoh_protocol::{core::WhatAmIMatcher, scouting::Hello}; use zenoh_result::ZResult; use zenoh_task::TerminatableTask; @@ -27,10 +28,9 @@ use zenoh_task::TerminatableTask; /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// /// let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) -/// .res() /// .await /// .unwrap(); /// while let Ok(hello) = receiver.recv_async().await { @@ -53,11 +53,10 @@ impl ScoutBuilder { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let scout = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .callback(|hello| { println!("{}", hello); }) - /// .res() /// .await /// .unwrap(); /// # } @@ -88,12 +87,11 @@ impl ScoutBuilder { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let mut n = 0; /// let scout = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .callback_mut(move |_hello| { n += 1; }) - /// .res() /// .await /// .unwrap(); /// # } @@ -115,11 +113,10 @@ impl ScoutBuilder { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(hello) = receiver.recv_async().await { @@ -153,26 +150,27 @@ where type To = ZResult>; } -impl SyncResolve for ScoutBuilder +impl Wait for ScoutBuilder where Handler: IntoHandler<'static, Hello> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let (callback, receiver) = self.handler.into_handler(); _scout(self.what, self.config?, callback).map(|scout| Scout { scout, receiver }) } } -impl AsyncResolve for ScoutBuilder +impl IntoFuture for ScoutBuilder where Handler: IntoHandler<'static, Hello> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -182,11 +180,10 @@ where /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// /// let scout = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .callback(|hello| { println!("{}", hello); }) -/// .res() /// .await /// .unwrap(); /// # } @@ -203,11 +200,10 @@ impl ScoutInner { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let scout = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .callback(|hello| { println!("{}", hello); }) - /// .res() /// .await /// .unwrap(); /// scout.stop(); @@ -239,11 +235,10 @@ impl fmt::Debug for ScoutInner { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// /// let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) /// .with(flume::bounded(32)) -/// .res() /// .await /// .unwrap(); /// while let Ok(hello) = receiver.recv_async().await { @@ -273,11 +268,10 @@ impl Scout { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// /// let scout = zenoh::scout(WhatAmI::Router, config::default()) /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// let _router = scout.recv_async().await; @@ -350,11 +344,10 @@ fn _scout( /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// use zenoh::scouting::WhatAmI; /// /// let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, config::default()) -/// .res() /// .await /// .unwrap(); /// while let Ok(hello) = receiver.recv_async().await { diff --git a/zenoh/src/api/session.rs b/zenoh/src/api/session.rs index 01fc345c3b..dea322419c 100644 --- a/zenoh/src/api/session.rs +++ b/zenoh/src/api/session.rs @@ -32,6 +32,7 @@ use super::{ Id, }; use crate::net::{primitives::Primitives, routing::dispatcher::face::Face, runtime::Runtime}; +use std::future::IntoFuture; use std::{ collections::HashMap, convert::{TryFrom, TryInto}, @@ -49,9 +50,7 @@ use uhlc::HLC; use zenoh_buffers::ZBuf; use zenoh_collections::SingleOrVec; use zenoh_config::{unwrap_or_default, Config, Notifier}; -use zenoh_core::{ - zconfigurable, zread, Resolvable, Resolve, ResolveClosure, ResolveFuture, SyncResolve, -}; +use zenoh_core::{zconfigurable, zread, Resolvable, Resolve, ResolveClosure, ResolveFuture, Wait}; #[cfg(feature = "unstable")] use zenoh_protocol::network::{declare::SubscriberId, ext}; use zenoh_protocol::{ @@ -78,7 +77,6 @@ use zenoh_result::ZResult; #[cfg(all(feature = "unstable", feature = "shared-memory"))] use zenoh_shm::api::client_storage::SharedMemoryClientStorage; use zenoh_task::TaskController; -use zenoh_util::core::AsyncResolve; #[cfg(feature = "unstable")] use super::{ @@ -452,11 +450,10 @@ impl Session { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let subscriber = session.declare_subscriber("key/expression") - /// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -486,10 +483,10 @@ impl Session { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = Session::leak(zenoh::open(config::peer()).res().await.unwrap()); - /// let subscriber = session.declare_subscriber("key/expression").res().await.unwrap(); + /// let session = Session::leak(zenoh::open(config::peer()).await.unwrap()); + /// let subscriber = session.declare_subscriber("key/expression").await.unwrap(); /// tokio::task::spawn(async move { /// while let Ok(sample) = subscriber.recv_async().await { /// println!("Received: {:?}", sample); @@ -504,7 +501,7 @@ impl Session { /// Returns the identifier of the current session. `zid()` is a convenient shortcut. /// See [`Session::info()`](`Session::info()`) and [`SessionInfo::zid()`](`SessionInfo::zid()`) for more details. pub fn zid(&self) -> ZenohId { - self.info().zid().res_sync() + self.info().zid().wait() } pub fn hlc(&self) -> Option<&HLC> { @@ -520,10 +517,10 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// session.close().res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// session.close().await.unwrap(); /// # } /// ``` pub fn close(mut self) -> impl Resolve> { @@ -563,9 +560,9 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let peers = session.config().get("connect/endpoints").unwrap(); /// # } /// ``` @@ -574,9 +571,9 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let _ = session.config().insert_json5("connect/endpoints", r#"["tcp/127.0.0.1/7447"]"#); /// # } /// ``` @@ -635,10 +632,10 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let key_expr = session.declare_keyexpr("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let key_expr = session.declare_keyexpr("key/expression").await.unwrap(); /// # } /// ``` pub fn declare_keyexpr<'a, 'b: 'a, TryIntoKeyExpr>( @@ -661,7 +658,7 @@ impl Session { ResolveClosure::new(move || { let key_expr: KeyExpr = key_expr?; let prefix_len = key_expr.len() as u32; - let expr_id = self.declare_prefix(key_expr.as_str()).res_sync(); + let expr_id = self.declare_prefix(key_expr.as_str()).wait(); let key_expr = match key_expr.0 { KeyExprInner::Borrowed(key_expr) | KeyExprInner::BorrowedWire { key_expr, .. } => { KeyExpr(KeyExprInner::BorrowedWire { @@ -697,13 +694,12 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// session /// .put("key/expression", "payload") /// .encoding(Encoding::TEXT_PLAIN) - /// .res() /// .await /// .unwrap(); /// # } @@ -743,10 +739,10 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// session.delete("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// session.delete("key/expression").await.unwrap(); /// # } /// ``` #[inline] @@ -781,10 +777,10 @@ impl Session { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); - /// let replies = session.get("key/expression").res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); + /// let replies = session.get("key/expression").await.unwrap(); /// while let Ok(reply) = replies.recv_async().await { /// println!(">> Received {:?}", reply.result()); /// } @@ -858,7 +854,6 @@ impl Session { aggregated_subscribers, aggregated_publishers, ) - .res_async() .await; session.owns_runtime = true; runtime.start().await?; @@ -1091,14 +1086,14 @@ impl Session { // match key_expr.as_str().find('*') { // Some(0) => key_expr.to_wire(self), // Some(pos) => { - // let expr_id = self.declare_prefix(&key_expr.as_str()[..pos]).res_sync(); + // let expr_id = self.declare_prefix(&key_expr.as_str()[..pos]).wait(); // WireExpr { // scope: expr_id, // suffix: std::borrow::Cow::Borrowed(&key_expr.as_str()[pos..]), // } // } // None => { - // let expr_id = self.declare_prefix(key_expr.as_str()).res_sync(); + // let expr_id = self.declare_prefix(key_expr.as_str()).wait(); // WireExpr { // scope: expr_id, // suffix: std::borrow::Cow::Borrowed(""), @@ -1840,11 +1835,10 @@ impl<'s> SessionDeclarations<'s, 'static> for Arc { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let subscriber = session.declare_subscriber("key/expression") - /// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -1882,11 +1876,10 @@ impl<'s> SessionDeclarations<'s, 'static> for Arc { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let queryable = session.declare_queryable("key/expression") - /// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -1894,7 +1887,7 @@ impl<'s> SessionDeclarations<'s, 'static> for Arc { /// query.reply( /// KeyExpr::try_from("key/expression").unwrap(), /// "value", - /// ).res().await.unwrap(); + /// ).await.unwrap(); /// } /// }).await; /// # } @@ -1926,14 +1919,13 @@ impl<'s> SessionDeclarations<'s, 'static> for Arc { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let publisher = session.declare_publisher("key/expression") - /// .res() /// .await /// .unwrap(); - /// publisher.put("value").res().await.unwrap(); + /// publisher.put("value").await.unwrap(); /// # } /// ``` fn declare_publisher<'b, TryIntoKeyExpr>( @@ -1960,13 +1952,12 @@ impl<'s> SessionDeclarations<'s, 'static> for Arc { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") - /// .res() /// .await /// .unwrap(); /// # } @@ -2424,7 +2415,7 @@ impl Primitives for Session { impl Drop for Session { fn drop(&mut self) { if self.alive { - let _ = self.clone().close().res_sync(); + let _ = self.clone().close().wait(); } } } @@ -2448,11 +2439,10 @@ impl fmt::Debug for Session { /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); +/// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let subscriber = session.declare_subscriber("key/expression") -/// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -2473,11 +2463,10 @@ pub trait SessionDeclarations<'s, 'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let subscriber = session.declare_subscriber("key/expression") - /// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -2506,11 +2495,10 @@ pub trait SessionDeclarations<'s, 'a> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let queryable = session.declare_queryable("key/expression") - /// .res() /// .await /// .unwrap(); /// tokio::task::spawn(async move { @@ -2518,7 +2506,7 @@ pub trait SessionDeclarations<'s, 'a> { /// query.reply( /// KeyExpr::try_from("key/expression").unwrap(), /// "value", - /// ).res().await.unwrap(); + /// ).await.unwrap(); /// } /// }).await; /// # } @@ -2541,14 +2529,13 @@ pub trait SessionDeclarations<'s, 'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let publisher = session.declare_publisher("key/expression") - /// .res() /// .await /// .unwrap(); - /// publisher.put("value").res().await.unwrap(); + /// publisher.put("value").await.unwrap(); /// # } /// ``` fn declare_publisher<'b, TryIntoKeyExpr>( @@ -2565,13 +2552,12 @@ pub trait SessionDeclarations<'s, 'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap().into_arc(); + /// let session = zenoh::open(config::peer()).await.unwrap().into_arc(); /// let liveliness = session /// .liveliness() /// .declare_token("key/expression") - /// .res() /// .await /// .unwrap(); /// # } @@ -2584,9 +2570,9 @@ pub trait SessionDeclarations<'s, 'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let info = session.info(); /// # } /// ``` @@ -2639,9 +2625,9 @@ impl crate::net::primitives::EPrimitives for Session { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// # } /// ``` /// @@ -2649,13 +2635,13 @@ impl crate::net::primitives::EPrimitives for Session { /// # #[tokio::main] /// # async fn main() { /// use std::str::FromStr; -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// /// let mut config = config::peer(); /// config.set_id(ZenohId::from_str("221b72df20924c15b8794c6bdb471150").unwrap()); /// config.connect.endpoints.extend("tcp/10.10.10.10:7447,tcp/11.11.11.11:7447".split(',').map(|s|s.parse().unwrap())); /// -/// let session = zenoh::open(config).res().await.unwrap(); +/// let session = zenoh::open(config).await.unwrap(); /// # } /// ``` pub fn open(config: TryIntoConfig) -> OpenBuilder @@ -2676,9 +2662,9 @@ where /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -2712,12 +2698,12 @@ where type To = ZResult; } -impl SyncResolve for OpenBuilder +impl Wait for OpenBuilder where TryIntoConfig: std::convert::TryInto + Send + 'static, >::Error: std::fmt::Debug, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let config: crate::config::Config = self .config .try_into() @@ -2727,19 +2713,20 @@ where #[cfg(all(feature = "unstable", feature = "shared-memory"))] self.shm_clients, ) - .res_sync() + .wait() } } -impl AsyncResolve for OpenBuilder +impl IntoFuture for OpenBuilder where TryIntoConfig: std::convert::TryInto + Send + 'static, >::Error: std::fmt::Debug, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -2786,22 +2773,23 @@ impl Resolvable for InitBuilder { } #[zenoh_macros::unstable] -impl SyncResolve for InitBuilder { - fn res_sync(self) -> ::To { +impl Wait for InitBuilder { + fn wait(self) -> ::To { Ok(Session::init( self.runtime, self.aggregated_subscribers, self.aggregated_publishers, ) - .res_sync()) + .wait()) } } #[zenoh_macros::unstable] -impl AsyncResolve for InitBuilder { - type Future = Ready; +impl IntoFuture for InitBuilder { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } diff --git a/zenoh/src/api/subscriber.rs b/zenoh/src/api/subscriber.rs index 4ac035d736..0c4e21b547 100644 --- a/zenoh/src/api/subscriber.rs +++ b/zenoh/src/api/subscriber.rs @@ -19,13 +19,14 @@ use super::{ session::{SessionRef, Undeclarable}, Id, }; +use std::future::IntoFuture; use std::{ fmt, future::Ready, ops::{Deref, DerefMut}, sync::Arc, }; -use zenoh_core::{AsyncResolve, Resolvable, SyncResolve}; +use zenoh_core::{Resolvable, Wait}; use zenoh_protocol::{core::Reliability, network::declare::subscriber::ext::SubscriberInfo}; use zenoh_result::ZResult; @@ -63,13 +64,12 @@ impl fmt::Debug for SubscriberState { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback(|sample| { println!("Received: {} {:?}", sample.key_expr(), sample.payload()) }) -/// .res() /// .await /// .unwrap(); /// # } @@ -91,17 +91,16 @@ impl<'a> SubscriberInner<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// # fn data_handler(_sample: Sample) { }; /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback(data_handler) - /// .res() /// .await /// .unwrap(); - /// subscriber.undeclare().res().await.unwrap(); + /// subscriber.undeclare().await.unwrap(); /// # } /// ``` #[inline] @@ -122,15 +121,14 @@ impl<'a> Undeclarable<(), SubscriberUndeclaration<'a>> for SubscriberInner<'a> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") -/// .res() /// .await /// .unwrap(); -/// subscriber.undeclare().res().await.unwrap(); +/// subscriber.undeclare().await.unwrap(); /// # } /// ``` #[must_use = "Resolvables do nothing unless you resolve them using the `res` method from either `SyncResolve` or `AsyncResolve`"] @@ -142,8 +140,8 @@ impl Resolvable for SubscriberUndeclaration<'_> { type To = ZResult<()>; } -impl SyncResolve for SubscriberUndeclaration<'_> { - fn res_sync(mut self) -> ::To { +impl Wait for SubscriberUndeclaration<'_> { + fn wait(mut self) -> ::To { self.subscriber.alive = false; self.subscriber .session @@ -151,11 +149,12 @@ impl SyncResolve for SubscriberUndeclaration<'_> { } } -impl AsyncResolve for SubscriberUndeclaration<'_> { - type Future = Ready; +impl IntoFuture for SubscriberUndeclaration<'_> { + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -173,13 +172,12 @@ impl Drop for SubscriberInner<'_> { /// ``` /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .best_effort() -/// .res() /// .await /// .unwrap(); /// # } @@ -220,13 +218,12 @@ impl<'a, 'b> SubscriberBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback(|sample| { println!("Received: {} {:?}", sample.key_expr(), sample.payload()); }) - /// .res() /// .await /// .unwrap(); /// # } @@ -263,14 +260,13 @@ impl<'a, 'b> SubscriberBuilder<'a, 'b, DefaultHandler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let mut n = 0; /// let subscriber = session /// .declare_subscriber("key/expression") /// .callback_mut(move |_sample| { n += 1; }) - /// .res() /// .await /// .unwrap(); /// # } @@ -292,13 +288,12 @@ impl<'a, 'b> SubscriberBuilder<'a, 'b, DefaultHandler> { /// ```no_run /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .with(flume::bounded(32)) - /// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -369,12 +364,12 @@ where type To = ZResult>; } -impl<'a, Handler> SyncResolve for SubscriberBuilder<'a, '_, Handler> +impl<'a, Handler> Wait for SubscriberBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { - fn res_sync(self) -> ::To { + fn wait(self) -> ::To { let key_expr = self.key_expr?; let session = self.session; let (callback, receiver) = self.handler.into_handler(); @@ -399,15 +394,16 @@ where } } -impl<'a, Handler> AsyncResolve for SubscriberBuilder<'a, '_, Handler> +impl<'a, Handler> IntoFuture for SubscriberBuilder<'a, '_, Handler> where Handler: IntoHandler<'static, Sample> + Send, Handler::Handler: Send, { - type Future = Ready; + type Output = ::To; + type IntoFuture = Ready<::To>; - fn res_async(self) -> Self::Future { - std::future::ready(self.res_sync()) + fn into_future(self) -> Self::IntoFuture { + std::future::ready(self.wait()) } } @@ -424,13 +420,12 @@ where /// ```no_run /// # #[tokio::main] /// # async fn main() { -/// use zenoh::prelude::r#async::*; +/// use zenoh::prelude::*; /// -/// let session = zenoh::open(config::peer()).res().await.unwrap(); +/// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session /// .declare_subscriber("key/expression") /// .with(flume::bounded(32)) -/// .res() /// .await /// .unwrap(); /// while let Ok(sample) = subscriber.recv_async().await { @@ -452,11 +447,10 @@ impl<'a, Handler> Subscriber<'a, Handler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session.declare_subscriber("key/expression") - /// .res() /// .await /// .unwrap(); /// let subscriber_id = subscriber.id(); @@ -498,14 +492,13 @@ impl<'a, Handler> Subscriber<'a, Handler> { /// ``` /// # #[tokio::main] /// # async fn main() { - /// use zenoh::prelude::r#async::*; + /// use zenoh::prelude::*; /// - /// let session = zenoh::open(config::peer()).res().await.unwrap(); + /// let session = zenoh::open(config::peer()).await.unwrap(); /// let subscriber = session.declare_subscriber("key/expression") - /// .res() /// .await /// .unwrap(); - /// subscriber.undeclare().res().await.unwrap(); + /// subscriber.undeclare().await.unwrap(); /// # } /// ``` #[inline] diff --git a/zenoh/src/lib.rs b/zenoh/src/lib.rs index 3c011e2439..6f679407c8 100644 --- a/zenoh/src/lib.rs +++ b/zenoh/src/lib.rs @@ -32,13 +32,13 @@ //! ### Publishing Data //! The example below shows how to produce a value for a key expression. //! ``` -//! use zenoh::prelude::r#async::*; +//! use zenoh::prelude::*; //! //! #[tokio::main] //! async fn main() { -//! let session = zenoh::open(config::default()).res().await.unwrap(); -//! session.put("key/expression", "value").res().await.unwrap(); -//! session.close().res().await.unwrap(); +//! let session = zenoh::open(config::default()).await.unwrap(); +//! session.put("key/expression", "value").await.unwrap(); +//! session.close().await.unwrap(); //! } //! ``` //! @@ -46,12 +46,12 @@ //! The example below shows how to consume values for a key expresison. //! ```no_run //! use futures::prelude::*; -//! use zenoh::prelude::r#async::*; +//! use zenoh::prelude::*; //! //! #[tokio::main] //! async fn main() { -//! let session = zenoh::open(config::default()).res().await.unwrap(); -//! let subscriber = session.declare_subscriber("key/expression").res().await.unwrap(); +//! let session = zenoh::open(config::default()).await.unwrap(); +//! let subscriber = session.declare_subscriber("key/expression").await.unwrap(); //! while let Ok(sample) = subscriber.recv_async().await { //! println!("Received: {:?}", sample); //! }; @@ -63,12 +63,12 @@ //! resources whose key match the given *key expression*. //! ``` //! use futures::prelude::*; -//! use zenoh::prelude::r#async::*; +//! use zenoh::prelude::*; //! //! #[tokio::main] //! async fn main() { -//! let session = zenoh::open(config::default()).res().await.unwrap(); -//! let replies = session.get("key/expression").res().await.unwrap(); +//! let session = zenoh::open(config::default()).await.unwrap(); +//! let replies = session.get("key/expression").await.unwrap(); //! while let Ok(reply) = replies.recv_async().await { //! println!(">> Received {:?}", reply.result()); //! } @@ -117,10 +117,13 @@ pub mod prelude; /// Zenoh core types pub mod core { + #[allow(deprecated)] pub use zenoh_core::AsyncResolve; pub use zenoh_core::Resolvable; pub use zenoh_core::Resolve; + #[allow(deprecated)] pub use zenoh_core::SyncResolve; + pub use zenoh_core::Wait; /// A zenoh error. pub use zenoh_result::Error; /// A zenoh result. diff --git a/zenoh/src/net/runtime/adminspace.rs b/zenoh/src/net/runtime/adminspace.rs index ea084c453b..9ea54b8d88 100644 --- a/zenoh/src/net/runtime/adminspace.rs +++ b/zenoh/src/net/runtime/adminspace.rs @@ -31,7 +31,7 @@ use std::sync::Mutex; use tracing::{error, trace}; use zenoh_buffers::buffer::SplitBuffer; use zenoh_config::{unwrap_or_default, ConfigValidator, ValidatedMap, WhatAmI}; -use zenoh_core::SyncResolve; +use zenoh_core::Wait; #[cfg(all(feature = "unstable", feature = "plugins"))] use zenoh_plugin_trait::{PluginControl, PluginStatus}; #[cfg(all(feature = "unstable", feature = "plugins"))] @@ -630,7 +630,7 @@ fn local_data(context: &AdminContext, query: Query) { if let Err(e) = query .reply(reply_key, payload) .encoding(Encoding::APPLICATION_JSON) - .res_sync() + .wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } @@ -662,7 +662,7 @@ zenoh_build{{version="{}"}} 1 .openmetrics_text(), ); - if let Err(e) = query.reply(reply_key, metrics).res() { + if let Err(e) = query.reply(reply_key, metrics).wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } } @@ -679,7 +679,7 @@ fn routers_linkstate_data(context: &AdminContext, query: Query) { if let Err(e) = query .reply(reply_key, tables.hat_code.info(&tables, WhatAmI::Router)) - .res() + .wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } @@ -697,7 +697,7 @@ fn peers_linkstate_data(context: &AdminContext, query: Query) { if let Err(e) = query .reply(reply_key, tables.hat_code.info(&tables, WhatAmI::Peer)) - .res() + .wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } @@ -719,7 +719,7 @@ fn subscribers_data(context: &AdminContext, query: Query) { if let Err(e) = query .reply(key, payload) .encoding(Encoding::APPLICATION_JSON) - .res_sync() + .wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } @@ -743,7 +743,7 @@ fn queryables_data(context: &AdminContext, query: Query) { if let Err(e) = query .reply(key, payload) .encoding(Encoding::APPLICATION_JSON) - .res_sync() + .wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } @@ -768,7 +768,7 @@ fn plugins_data(context: &AdminContext, query: Query) { let status = serde_json::to_value(status).unwrap(); match ZBytes::try_from(status) { Ok(zbuf) => { - if let Err(e) = query.reply(key, zbuf).res_sync() { + if let Err(e) = query.reply(key, zbuf).wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } } @@ -793,7 +793,7 @@ fn plugins_status(context: &AdminContext, query: Query) { with_extended_string(plugin_key, &["/__path__"], |plugin_path_key| { if let Ok(key_expr) = KeyExpr::try_from(plugin_path_key.clone()) { if query.key_expr().intersects(&key_expr) { - if let Err(e) = query.reply(key_expr, plugin.path()).res() { + if let Err(e) = query.reply(key_expr, plugin.path()).wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } } @@ -817,7 +817,7 @@ fn plugins_status(context: &AdminContext, query: Query) { if let Ok(key_expr) = KeyExpr::try_from(response.key) { match ZBytes::try_from(response.value) { Ok(zbuf) => { - if let Err(e) = query.reply(key_expr, zbuf).res_sync() { + if let Err(e) = query.reply(key_expr, zbuf).wait() { tracing::error!("Error sending AdminSpace reply: {:?}", e); } }, diff --git a/zenoh/src/prelude.rs b/zenoh/src/prelude.rs index 17286ddeea..ac466ae50b 100644 --- a/zenoh/src/prelude.rs +++ b/zenoh/src/prelude.rs @@ -18,22 +18,11 @@ //! almost always want to import its entire contents, but unlike the standard //! library's prelude you'll have to do so manually. //! -//! There are three variants of the prelude: full, sync and async. The sync one excludes the [`AsyncResolve`](crate::core::AsyncResolve) trait and the async one excludes the [`SyncResolve`](crate::core::SyncResolve) trait. -//! When specific sync or async prelude is included, the `res()` function of buildes works synchronously or asynchronously, respectively. -//! -//! If root prelude is included, the `res_sync()` or `res_async()` function of builders should be called explicitly. -//! //! Examples: //! //! ``` //!use zenoh::prelude::*; //! ``` -//! ``` -//!use zenoh::prelude::sync::*; -//! ``` -//! ``` -//!use zenoh::prelude::r#async::*; -//! ``` // Reexport API in flat namespace pub(crate) mod flat { @@ -81,20 +70,27 @@ pub(crate) mod mods { pub use crate::value; } +#[allow(deprecated)] pub use crate::core::AsyncResolve; +#[allow(deprecated)] pub use crate::core::SyncResolve; +pub use crate::core::Wait; pub use flat::*; pub use mods::*; /// Prelude to import when using Zenoh's sync API. +#[deprecated = "use `zenoh::prelude` instead"] pub mod sync { pub use super::flat::*; pub use super::mods::*; + #[allow(deprecated)] pub use crate::core::SyncResolve; } /// Prelude to import when using Zenoh's async API. +#[deprecated = "use `zenoh::prelude` instead"] pub mod r#async { pub use super::flat::*; pub use super::mods::*; + #[allow(deprecated)] pub use crate::core::AsyncResolve; } diff --git a/zenoh/tests/acl.rs b/zenoh/tests/acl.rs index dd1aa1271d..5f3c482581 100644 --- a/zenoh/tests/acl.rs +++ b/zenoh/tests/acl.rs @@ -16,7 +16,7 @@ mod test { use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::runtime::Handle; - use zenoh::prelude::r#async::*; + use zenoh::prelude::*; use zenoh_core::{zlock, ztimeout}; const TIMEOUT: Duration = Duration::from_secs(60); @@ -46,22 +46,22 @@ mod test { async fn close_router_session(s: Session) { println!("Closing router session"); - ztimeout!(s.close().res_async()).unwrap(); + ztimeout!(s.close()).unwrap(); } async fn get_client_sessions() -> (Session, Session) { println!("Opening client sessions"); let config = config::client(["tcp/127.0.0.1:7447".parse::().unwrap()]); - let s01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s01 = ztimeout!(zenoh::open(config)).unwrap(); let config = config::client(["tcp/127.0.0.1:7447".parse::().unwrap()]); - let s02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s02 = ztimeout!(zenoh::open(config)).unwrap(); (s01, s02) } async fn close_sessions(s01: Session, s02: Session) { println!("Closing client sessions"); - ztimeout!(s01.close().res_async()).unwrap(); - ztimeout!(s02.close().res_async()).unwrap(); + ztimeout!(s01.close()).unwrap(); + ztimeout!(s02.close()).unwrap(); } async fn test_pub_sub_deny() { @@ -82,15 +82,11 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (sub_session, pub_session) = get_client_sessions().await; { - let publisher = pub_session - .declare_publisher(KEY_EXPR) - .res_async() - .await - .unwrap(); + let publisher = pub_session.declare_publisher(KEY_EXPR).await.unwrap(); let received_value = Arc::new(Mutex::new(String::new())); let temp_recv_value = received_value.clone(); let subscriber = sub_session @@ -99,15 +95,14 @@ mod test { let mut temp_value = zlock!(temp_recv_value); *temp_value = sample.payload().deserialize::().unwrap(); }) - .res_async() .await .unwrap(); tokio::time::sleep(SLEEP).await; - publisher.put(VALUE).res_async().await.unwrap(); + publisher.put(VALUE).await.unwrap(); tokio::time::sleep(SLEEP).await; assert_ne!(*zlock!(received_value), VALUE); - ztimeout!(subscriber.undeclare().res_async()).unwrap(); + ztimeout!(subscriber.undeclare()).unwrap(); } close_sessions(sub_session, pub_session).await; close_router_session(session).await; @@ -132,28 +127,28 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (sub_session, pub_session) = get_client_sessions().await; { - let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR).res_async()).unwrap(); + let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR)).unwrap(); let received_value = Arc::new(Mutex::new(String::new())); let temp_recv_value = received_value.clone(); - let subscriber = ztimeout!(sub_session - .declare_subscriber(KEY_EXPR) - .callback(move |sample| { - let mut temp_value = zlock!(temp_recv_value); - *temp_value = sample.payload().deserialize::().unwrap(); - }) - .res_async()) - .unwrap(); + let subscriber = + ztimeout!(sub_session + .declare_subscriber(KEY_EXPR) + .callback(move |sample| { + let mut temp_value = zlock!(temp_recv_value); + *temp_value = sample.payload().deserialize::().unwrap(); + })) + .unwrap(); tokio::time::sleep(SLEEP).await; - ztimeout!(publisher.put(VALUE).res_async()).unwrap(); + ztimeout!(publisher.put(VALUE)).unwrap(); tokio::time::sleep(SLEEP).await; assert_eq!(*zlock!(received_value), VALUE); - ztimeout!(subscriber.undeclare().res_async()).unwrap(); + ztimeout!(subscriber.undeclare()).unwrap(); } close_sessions(sub_session, pub_session).await; @@ -193,28 +188,28 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (sub_session, pub_session) = get_client_sessions().await; { - let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR).res_async()).unwrap(); + let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR)).unwrap(); let received_value = Arc::new(Mutex::new(String::new())); let temp_recv_value = received_value.clone(); - let subscriber = ztimeout!(sub_session - .declare_subscriber(KEY_EXPR) - .callback(move |sample| { - let mut temp_value = zlock!(temp_recv_value); - *temp_value = sample.payload().deserialize::().unwrap(); - }) - .res_async()) - .unwrap(); + let subscriber = + ztimeout!(sub_session + .declare_subscriber(KEY_EXPR) + .callback(move |sample| { + let mut temp_value = zlock!(temp_recv_value); + *temp_value = sample.payload().deserialize::().unwrap(); + })) + .unwrap(); tokio::time::sleep(SLEEP).await; - ztimeout!(publisher.put(VALUE).res_async()).unwrap(); + ztimeout!(publisher.put(VALUE)).unwrap(); tokio::time::sleep(SLEEP).await; assert_ne!(*zlock!(received_value), VALUE); - ztimeout!(subscriber.undeclare().res_async()).unwrap(); + ztimeout!(subscriber.undeclare()).unwrap(); } close_sessions(sub_session, pub_session).await; close_router_session(session).await; @@ -253,28 +248,28 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (sub_session, pub_session) = get_client_sessions().await; { - let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR).res_async()).unwrap(); + let publisher = ztimeout!(pub_session.declare_publisher(KEY_EXPR)).unwrap(); let received_value = Arc::new(Mutex::new(String::new())); let temp_recv_value = received_value.clone(); - let subscriber = ztimeout!(sub_session - .declare_subscriber(KEY_EXPR) - .callback(move |sample| { - let mut temp_value = zlock!(temp_recv_value); - *temp_value = sample.payload().deserialize::().unwrap(); - }) - .res_async()) - .unwrap(); + let subscriber = + ztimeout!(sub_session + .declare_subscriber(KEY_EXPR) + .callback(move |sample| { + let mut temp_value = zlock!(temp_recv_value); + *temp_value = sample.payload().deserialize::().unwrap(); + })) + .unwrap(); tokio::time::sleep(SLEEP).await; - ztimeout!(publisher.put(VALUE).res_async()).unwrap(); + ztimeout!(publisher.put(VALUE)).unwrap(); tokio::time::sleep(SLEEP).await; assert_eq!(*zlock!(received_value), VALUE); - ztimeout!(subscriber.undeclare().res_async()).unwrap(); + ztimeout!(subscriber.undeclare()).unwrap(); } close_sessions(sub_session, pub_session).await; close_router_session(session).await; @@ -298,7 +293,7 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (get_session, qbl_session) = get_client_sessions().await; { @@ -309,15 +304,14 @@ mod test { .callback(move |sample| { tokio::task::block_in_place(move || { Handle::current().block_on(async move { - ztimeout!(sample.reply(KEY_EXPR, VALUE).res_async()).unwrap() + ztimeout!(sample.reply(KEY_EXPR, VALUE)).unwrap() }); }); - }) - .res_async()) + })) .unwrap(); tokio::time::sleep(SLEEP).await; - let recv_reply = ztimeout!(get_session.get(KEY_EXPR).res_async()).unwrap(); + let recv_reply = ztimeout!(get_session.get(KEY_EXPR)).unwrap(); while let Ok(reply) = ztimeout!(recv_reply.recv_async()) { match reply.result() { Ok(sample) => { @@ -329,7 +323,7 @@ mod test { } tokio::time::sleep(SLEEP).await; assert_ne!(received_value, VALUE); - ztimeout!(qbl.undeclare().res_async()).unwrap(); + ztimeout!(qbl.undeclare()).unwrap(); } close_sessions(get_session, qbl_session).await; close_router_session(session).await; @@ -353,7 +347,7 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (get_session, qbl_session) = get_client_sessions().await; { @@ -364,15 +358,14 @@ mod test { .callback(move |sample| { tokio::task::block_in_place(move || { Handle::current().block_on(async move { - ztimeout!(sample.reply(KEY_EXPR, VALUE).res_async()).unwrap() + ztimeout!(sample.reply(KEY_EXPR, VALUE)).unwrap() }); }); - }) - .res_async()) + })) .unwrap(); tokio::time::sleep(SLEEP).await; - let recv_reply = ztimeout!(get_session.get(KEY_EXPR).res_async()).unwrap(); + let recv_reply = ztimeout!(get_session.get(KEY_EXPR)).unwrap(); while let Ok(reply) = ztimeout!(recv_reply.recv_async()) { match reply.result() { Ok(sample) => { @@ -384,7 +377,7 @@ mod test { } tokio::time::sleep(SLEEP).await; assert_eq!(received_value, VALUE); - ztimeout!(qbl.undeclare().res_async()).unwrap(); + ztimeout!(qbl.undeclare()).unwrap(); } close_sessions(get_session, qbl_session).await; close_router_session(session).await; @@ -423,7 +416,7 @@ mod test { println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (get_session, qbl_session) = get_client_sessions().await; { @@ -434,15 +427,14 @@ mod test { .callback(move |sample| { tokio::task::block_in_place(move || { Handle::current().block_on(async move { - ztimeout!(sample.reply(KEY_EXPR, VALUE).res_async()).unwrap() + ztimeout!(sample.reply(KEY_EXPR, VALUE)).unwrap() }); }); - }) - .res_async()) + })) .unwrap(); tokio::time::sleep(SLEEP).await; - let recv_reply = ztimeout!(get_session.get(KEY_EXPR).res_async()).unwrap(); + let recv_reply = ztimeout!(get_session.get(KEY_EXPR)).unwrap(); while let Ok(reply) = ztimeout!(recv_reply.recv_async()) { match reply.result() { Ok(sample) => { @@ -454,7 +446,7 @@ mod test { } tokio::time::sleep(SLEEP).await; assert_eq!(received_value, VALUE); - ztimeout!(qbl.undeclare().res_async()).unwrap(); + ztimeout!(qbl.undeclare()).unwrap(); } close_sessions(get_session, qbl_session).await; close_router_session(session).await; @@ -492,7 +484,7 @@ mod test { .unwrap(); println!("Opening router session"); - let session = ztimeout!(zenoh::open(config_router).res_async()).unwrap(); + let session = ztimeout!(zenoh::open(config_router)).unwrap(); let (get_session, qbl_session) = get_client_sessions().await; { @@ -503,15 +495,14 @@ mod test { .callback(move |sample| { tokio::task::block_in_place(move || { Handle::current().block_on(async move { - ztimeout!(sample.reply(KEY_EXPR, VALUE).res_async()).unwrap() + ztimeout!(sample.reply(KEY_EXPR, VALUE)).unwrap() }); }); - }) - .res_async()) + })) .unwrap(); tokio::time::sleep(SLEEP).await; - let recv_reply = ztimeout!(get_session.get(KEY_EXPR).res_async()).unwrap(); + let recv_reply = ztimeout!(get_session.get(KEY_EXPR)).unwrap(); while let Ok(reply) = ztimeout!(recv_reply.recv_async()) { match reply.result() { Ok(sample) => { @@ -523,7 +514,7 @@ mod test { } tokio::time::sleep(SLEEP).await; assert_ne!(received_value, VALUE); - ztimeout!(qbl.undeclare().res_async()).unwrap(); + ztimeout!(qbl.undeclare()).unwrap(); } close_sessions(get_session, qbl_session).await; close_router_session(session).await; diff --git a/zenoh/tests/attachments.rs b/zenoh/tests/attachments.rs index b98a656089..836845a645 100644 --- a/zenoh/tests/attachments.rs +++ b/zenoh/tests/attachments.rs @@ -15,8 +15,8 @@ #[test] fn attachment_pubsub() { use zenoh::bytes::ZBytes; - use zenoh::prelude::sync::*; - let zenoh = zenoh::open(Config::default()).res().unwrap(); + use zenoh::prelude::*; + let zenoh = zenoh::open(Config::default()).wait().unwrap(); let _sub = zenoh .declare_subscriber("test/attachment") .callback(|sample| { @@ -28,10 +28,10 @@ fn attachment_pubsub() { assert!(k.iter().rev().zip(v.as_slice()).all(|(k, v)| k == v)) } }) - .res() + .wait() .unwrap(); - let publisher = zenoh.declare_publisher("test/attachment").res().unwrap(); + let publisher = zenoh.declare_publisher("test/attachment").wait().unwrap(); for i in 0..10 { let mut backer = [( [0; std::mem::size_of::()], @@ -44,12 +44,12 @@ fn attachment_pubsub() { zenoh .put("test/attachment", "put") .attachment(ZBytes::from_iter(backer.iter())) - .res() + .wait() .unwrap(); publisher .put("publisher") .attachment(ZBytes::from_iter(backer.iter())) - .res() + .wait() .unwrap(); } } @@ -57,8 +57,8 @@ fn attachment_pubsub() { #[cfg(feature = "unstable")] #[test] fn attachment_queries() { - use zenoh::prelude::sync::*; - let zenoh = zenoh::open(Config::default()).res().unwrap(); + use zenoh::prelude::*; + let zenoh = zenoh::open(Config::default()).wait().unwrap(); let _sub = zenoh .declare_queryable("test/attachment") .callback(|query| { @@ -90,10 +90,10 @@ fn attachment_queries() { )>() .map(|(k, _)| (k, k)), )) - .res() + .wait() .unwrap(); }) - .res() + .wait() .unwrap(); for i in 0..10 { let mut backer = [( @@ -108,7 +108,7 @@ fn attachment_queries() { .get("test/attachment") .payload("query") .attachment(ZBytes::from_iter(backer.iter())) - .res() + .wait() .unwrap(); while let Ok(reply) = get.recv() { let response = reply.result().unwrap(); diff --git a/zenoh/tests/connection_retry.rs b/zenoh/tests/connection_retry.rs index d99017ff43..67a1c9c093 100644 --- a/zenoh/tests/connection_retry.rs +++ b/zenoh/tests/connection_retry.rs @@ -11,7 +11,7 @@ // Contributors: // ZettaScale Zenoh Team, // -use zenoh::prelude::sync::*; +use zenoh::prelude::*; #[test] fn retry_config_overriding() { @@ -164,7 +164,7 @@ fn listen_no_retry() { .unwrap(); config.insert_json5("listen/timeout_ms", "0").unwrap(); - zenoh::open(config).res().unwrap(); + zenoh::open(config).wait().unwrap(); } #[test] @@ -177,5 +177,5 @@ fn listen_with_retry() { config.insert_json5("listen/timeout_ms", "1000").unwrap(); - zenoh::open(config).res().unwrap(); + zenoh::open(config).wait().unwrap(); } diff --git a/zenoh/tests/events.rs b/zenoh/tests/events.rs index cbb38e90fc..99ca6055da 100644 --- a/zenoh/tests/events.rs +++ b/zenoh/tests/events.rs @@ -13,7 +13,7 @@ // use std::time::Duration; use zenoh::internal::ztimeout; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; const TIMEOUT: Duration = Duration::from_secs(10); @@ -29,25 +29,24 @@ async fn open_session(listen: &[&str], connect: &[&str]) -> Session { .collect::>(); config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][01a] Opening session"); - ztimeout!(zenoh::open(config).res_async()).unwrap() + ztimeout!(zenoh::open(config)).unwrap() } async fn close_session(session: Session) { println!("[ ][01d] Closing session"); - ztimeout!(session.close().res_async()).unwrap(); + ztimeout!(session.close()).unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn zenoh_events() { let session = open_session(&["tcp/127.0.0.1:18447"], &[]).await; let zid = session.zid(); - let sub1 = ztimeout!(session - .declare_subscriber(format!("@/session/{zid}/transport/unicast/*")) - .res()) - .unwrap(); - let sub2 = ztimeout!(session - .declare_subscriber(format!("@/session/{zid}/transport/unicast/*/link/*")) - .res()) + let sub1 = + ztimeout!(session.declare_subscriber(format!("@/session/{zid}/transport/unicast/*"))) + .unwrap(); + let sub2 = ztimeout!( + session.declare_subscriber(format!("@/session/{zid}/transport/unicast/*/link/*")) + ) .unwrap(); let session2 = open_session(&["tcp/127.0.0.1:18448"], &["tcp/127.0.0.1:18447"]).await; @@ -65,23 +64,21 @@ async fn zenoh_events() { assert!(key_expr.starts_with(&format!("@/session/{zid}/transport/unicast/{zid2}/link/"))); assert!(sample.as_ref().unwrap().kind() == SampleKind::Put); - let replies: Vec = ztimeout!(session - .get(format!("@/session/{zid}/transport/unicast/*")) - .res_async()) - .unwrap() - .into_iter() - .collect(); + let replies: Vec = + ztimeout!(session.get(format!("@/session/{zid}/transport/unicast/*"))) + .unwrap() + .into_iter() + .collect(); assert!(replies.len() == 1); assert!(replies[0].result().is_ok()); let key_expr = replies[0].result().unwrap().key_expr().as_str(); assert!(key_expr.eq(&format!("@/session/{zid}/transport/unicast/{zid2}"))); - let replies: Vec = ztimeout!(session - .get(format!("@/session/{zid}/transport/unicast/*/link/*")) - .res_async()) - .unwrap() - .into_iter() - .collect(); + let replies: Vec = + ztimeout!(session.get(format!("@/session/{zid}/transport/unicast/*/link/*"))) + .unwrap() + .into_iter() + .collect(); assert!(replies.len() == 1); assert!(replies[0].result().is_ok()); let key_expr = replies[0].result().unwrap().key_expr().as_str(); @@ -101,7 +98,7 @@ async fn zenoh_events() { assert!(key_expr.starts_with(&format!("@/session/{zid}/transport/unicast/{zid2}/link/"))); assert!(sample.as_ref().unwrap().kind() == SampleKind::Delete); - ztimeout!(sub2.undeclare().res()).unwrap(); - ztimeout!(sub1.undeclare().res()).unwrap(); + ztimeout!(sub2.undeclare()).unwrap(); + ztimeout!(sub1.undeclare()).unwrap(); close_session(session).await; } diff --git a/zenoh/tests/handler.rs b/zenoh/tests/handler.rs index b83fead54b..0862f9ee89 100644 --- a/zenoh/tests/handler.rs +++ b/zenoh/tests/handler.rs @@ -12,20 +12,20 @@ // ZettaScale Zenoh Team, // use std::{thread, time::Duration}; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; #[test] fn pubsub_with_ringbuffer() { - let zenoh = zenoh::open(Config::default()).res().unwrap(); + let zenoh = zenoh::open(Config::default()).wait().unwrap(); let sub = zenoh .declare_subscriber("test/ringbuffer") .with(RingChannel::new(3)) - .res() + .wait() .unwrap(); for i in 0..10 { zenoh .put("test/ringbuffer", format!("put{i}")) - .res() + .wait() .unwrap(); } // Should only receive the last three samples ("put7", "put8", "put9") @@ -45,22 +45,22 @@ fn pubsub_with_ringbuffer() { #[test] fn query_with_ringbuffer() { - let zenoh = zenoh::open(Config::default()).res().unwrap(); + let zenoh = zenoh::open(Config::default()).wait().unwrap(); let queryable = zenoh .declare_queryable("test/ringbuffer_query") .with(RingChannel::new(1)) - .res() + .wait() .unwrap(); let _reply1 = zenoh .get("test/ringbuffer_query") .payload("query1") - .res() + .wait() .unwrap(); let _reply2 = zenoh .get("test/ringbuffer_query") .payload("query2") - .res() + .wait() .unwrap(); let query = queryable.recv().unwrap(); diff --git a/zenoh/tests/interceptors.rs b/zenoh/tests/interceptors.rs index 7a3a9c80d6..f6e876d92e 100644 --- a/zenoh/tests/interceptors.rs +++ b/zenoh/tests/interceptors.rs @@ -13,7 +13,7 @@ // use std::sync::{Arc, Mutex}; use zenoh::internal::zlock; -use zenoh::prelude::sync::*; +use zenoh::prelude::*; struct IntervalCounter { first_tick: bool, @@ -89,7 +89,7 @@ fn downsampling_by_keyexpr_impl(egress: bool) { .multicast .set_enabled(Some(false)) .unwrap(); - let zenoh_sub = zenoh::open(config_sub).res().unwrap(); + let zenoh_sub = zenoh::open(config_sub).wait().unwrap(); let counter_r100 = Arc::new(Mutex::new(IntervalCounter::new())); let counter_r100_clone = counter_r100.clone(); @@ -110,7 +110,7 @@ fn downsampling_by_keyexpr_impl(egress: bool) { zlock!(counter_r50).tick(); } }) - .res() + .wait() .unwrap(); // declare publisher @@ -126,29 +126,29 @@ fn downsampling_by_keyexpr_impl(egress: bool) { .multicast .set_enabled(Some(false)) .unwrap(); - let zenoh_pub = zenoh::open(config_pub).res().unwrap(); + let zenoh_pub = zenoh::open(config_pub).wait().unwrap(); let publisher_r100 = zenoh_pub .declare_publisher("test/downsamples_by_keyexp/r100") - .res() + .wait() .unwrap(); let publisher_r50 = zenoh_pub .declare_publisher("test/downsamples_by_keyexp/r50") - .res() + .wait() .unwrap(); let publisher_all = zenoh_pub .declare_publisher("test/downsamples_by_keyexp/all") - .res() + .wait() .unwrap(); // WARN(yuyuan): 2 ms is the limit of tokio let interval = std::time::Duration::from_millis(2); let messages_count = 1000; for i in 0..messages_count { - publisher_r100.put(format!("message {}", i)).res().unwrap(); - publisher_r50.put(format!("message {}", i)).res().unwrap(); - publisher_all.put(format!("message {}", i)).res().unwrap(); + publisher_r100.put(format!("message {}", i)).wait().unwrap(); + publisher_r50.put(format!("message {}", i)).wait().unwrap(); + publisher_all.put(format!("message {}", i)).wait().unwrap(); std::thread::sleep(interval); } @@ -205,7 +205,7 @@ fn downsampling_by_interface_impl(egress: bool) { if !egress { config_sub.insert_json5("downsampling", &ds_cfg).unwrap(); }; - let zenoh_sub = zenoh::open(config_sub).res().unwrap(); + let zenoh_sub = zenoh::open(config_sub).wait().unwrap(); let counter_r100 = Arc::new(Mutex::new(IntervalCounter::new())); let counter_r100_clone = counter_r100.clone(); @@ -222,7 +222,7 @@ fn downsampling_by_interface_impl(egress: bool) { zlock!(counter_r100).tick(); } }) - .res() + .wait() .unwrap(); // declare publisher @@ -233,23 +233,23 @@ fn downsampling_by_interface_impl(egress: bool) { if egress { config_pub.insert_json5("downsampling", &ds_cfg).unwrap(); } - let zenoh_pub = zenoh::open(config_pub).res().unwrap(); + let zenoh_pub = zenoh::open(config_pub).wait().unwrap(); let publisher_r100 = zenoh_pub .declare_publisher("test/downsamples_by_interface/r100") - .res() + .wait() .unwrap(); let publisher_all = zenoh_pub .declare_publisher("test/downsamples_by_interface/all") - .res() + .wait() .unwrap(); // WARN(yuyuan): 2 ms is the limit of tokio let interval = std::time::Duration::from_millis(2); let messages_count = 1000; for i in 0..messages_count { - publisher_r100.put(format!("message {}", i)).res().unwrap(); - publisher_all.put(format!("message {}", i)).res().unwrap(); + publisher_r100.put(format!("message {}", i)).wait().unwrap(); + publisher_all.put(format!("message {}", i)).wait().unwrap(); std::thread::sleep(interval); } @@ -295,5 +295,5 @@ fn downsampling_config_error_wrong_strategy() { ) .unwrap(); - zenoh::open(config).res().unwrap(); + zenoh::open(config).wait().unwrap(); } diff --git a/zenoh/tests/liveliness.rs b/zenoh/tests/liveliness.rs index 1cd0830ea2..0456361419 100644 --- a/zenoh/tests/liveliness.rs +++ b/zenoh/tests/liveliness.rs @@ -23,33 +23,24 @@ async fn zenoh_liveliness() { .set_endpoints(vec!["tcp/localhost:47447".parse().unwrap()]) .unwrap(); c1.scouting.multicast.set_enabled(Some(false)).unwrap(); - let session1 = ztimeout!(zenoh::open(c1).res_async()).unwrap(); + let session1 = ztimeout!(zenoh::open(c1)).unwrap(); let mut c2 = config::peer(); c2.connect .set_endpoints(vec!["tcp/localhost:47447".parse().unwrap()]) .unwrap(); c2.scouting.multicast.set_enabled(Some(false)).unwrap(); - let session2 = ztimeout!(zenoh::open(c2).res_async()).unwrap(); + let session2 = ztimeout!(zenoh::open(c2)).unwrap(); let sub = ztimeout!(session2 .liveliness() - .declare_subscriber("zenoh_liveliness_test") - .res_async()) + .declare_subscriber("zenoh_liveliness_test")) .unwrap(); - let token = ztimeout!(session1 - .liveliness() - .declare_token("zenoh_liveliness_test") - .res_async()) - .unwrap(); + let token = ztimeout!(session1.liveliness().declare_token("zenoh_liveliness_test")).unwrap(); tokio::time::sleep(SLEEP).await; - let replies = ztimeout!(session2 - .liveliness() - .get("zenoh_liveliness_test") - .res_async()) - .unwrap(); + let replies = ztimeout!(session2.liveliness().get("zenoh_liveliness_test")).unwrap(); let sample: Sample = ztimeout!(replies.recv_async()) .unwrap() .into_result() @@ -67,11 +58,7 @@ async fn zenoh_liveliness() { tokio::time::sleep(SLEEP).await; - let replies = ztimeout!(session2 - .liveliness() - .get("zenoh_liveliness_test") - .res_async()) - .unwrap(); + let replies = ztimeout!(session2.liveliness().get("zenoh_liveliness_test")).unwrap(); assert!(ztimeout!(replies.recv_async()).is_err()); assert!(replies.try_recv().is_err()); diff --git a/zenoh/tests/matching.rs b/zenoh/tests/matching.rs index 4e838f98a1..1473d7f6fc 100644 --- a/zenoh/tests/matching.rs +++ b/zenoh/tests/matching.rs @@ -35,8 +35,8 @@ async fn create_session_pair(locator: &str) -> (Session, Session) { }; let config2 = zenoh::config::client([Locator::from_str(locator).unwrap()]); - let session1 = ztimeout!(zenoh::open(config1).res_async()).unwrap(); - let session2 = ztimeout!(zenoh::open(config2).res_async()).unwrap(); + let session1 = ztimeout!(zenoh::open(config1)).unwrap(); + let session2 = ztimeout!(zenoh::open(config2)).unwrap(); (session1, session2) } @@ -47,54 +47,47 @@ async fn zenoh_matching_status_any() -> ZResult<()> { let publisher1 = ztimeout!(session1 .declare_publisher("zenoh_matching_status_any_test") - .allowed_destination(Locality::Any) - .res_async()) + .allowed_destination(Locality::Any)) .unwrap(); - let matching_listener = ztimeout!(publisher1.matching_listener().res_async()).unwrap(); + let matching_listener = ztimeout!(publisher1.matching_listener()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session1 - .declare_subscriber("zenoh_matching_status_any_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session1.declare_subscriber("zenoh_matching_status_any_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(true)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(false)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session2 - .declare_subscriber("zenoh_matching_status_any_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session2.declare_subscriber("zenoh_matching_status_any_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(true)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(false)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); Ok(()) } @@ -102,60 +95,53 @@ async fn zenoh_matching_status_any() -> ZResult<()> { #[cfg(feature = "unstable")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn zenoh_matching_status_remote() -> ZResult<()> { - let session1 = ztimeout!(zenoh::open(peer()).res_async()).unwrap(); + let session1 = ztimeout!(zenoh::open(peer())).unwrap(); - let session2 = ztimeout!(zenoh::open(peer()).res_async()).unwrap(); + let session2 = ztimeout!(zenoh::open(peer())).unwrap(); let publisher1 = ztimeout!(session1 .declare_publisher("zenoh_matching_status_remote_test") - .allowed_destination(Locality::Remote) - .res_async()) + .allowed_destination(Locality::Remote)) .unwrap(); - let matching_listener = ztimeout!(publisher1.matching_listener().res_async()).unwrap(); + let matching_listener = ztimeout!(publisher1.matching_listener()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session1 - .declare_subscriber("zenoh_matching_status_remote_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session1.declare_subscriber("zenoh_matching_status_remote_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session2 - .declare_subscriber("zenoh_matching_status_remote_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session2.declare_subscriber("zenoh_matching_status_remote_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(true)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(false)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); Ok(()) @@ -164,60 +150,53 @@ async fn zenoh_matching_status_remote() -> ZResult<()> { #[cfg(feature = "unstable")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn zenoh_matching_status_local() -> ZResult<()> { - let session1 = ztimeout!(zenoh::open(config::peer()).res_async()).unwrap(); + let session1 = ztimeout!(zenoh::open(config::peer())).unwrap(); - let session2 = ztimeout!(zenoh::open(config::peer()).res_async()).unwrap(); + let session2 = ztimeout!(zenoh::open(config::peer())).unwrap(); let publisher1 = ztimeout!(session1 .declare_publisher("zenoh_matching_status_local_test") - .allowed_destination(Locality::SessionLocal) - .res_async()) + .allowed_destination(Locality::SessionLocal)) .unwrap(); - let matching_listener = ztimeout!(publisher1.matching_listener().res_async()).unwrap(); + let matching_listener = ztimeout!(publisher1.matching_listener()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session1 - .declare_subscriber("zenoh_matching_status_local_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session1.declare_subscriber("zenoh_matching_status_local_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(true)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.ok().map(|s| s.matching_subscribers()) == Some(false)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - let sub = ztimeout!(session2 - .declare_subscriber("zenoh_matching_status_local_test") - .res_async()) - .unwrap(); + let sub = ztimeout!(session2.declare_subscriber("zenoh_matching_status_local_test")).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); let received_status = matching_listener.recv_timeout(RECV_TIMEOUT); assert!(received_status.err() == Some(RecvTimeoutError::Timeout)); - let matching_status = ztimeout!(publisher1.matching_status().res_async()).unwrap(); + let matching_status = ztimeout!(publisher1.matching_status()).unwrap(); assert!(!matching_status.matching_subscribers()); Ok(()) diff --git a/zenoh/tests/payload.rs b/zenoh/tests/payload.rs index fac5d37367..fecf10a608 100644 --- a/zenoh/tests/payload.rs +++ b/zenoh/tests/payload.rs @@ -15,7 +15,7 @@ #[test] #[cfg(all(feature = "shared-memory", feature = "unstable"))] fn shm_payload_single_buf() { - use zenoh::prelude::r#async::*; + use zenoh::prelude::*; // create an SHM backend... let backend = PosixSharedMemoryProviderBackend::builder() diff --git a/zenoh/tests/qos.rs b/zenoh/tests/qos.rs index b70d01ec79..6f44b2d0be 100644 --- a/zenoh/tests/qos.rs +++ b/zenoh/tests/qos.rs @@ -13,40 +13,38 @@ // use std::time::Duration; use zenoh::internal::ztimeout; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn pubsub() { - let session1 = ztimeout!(zenoh::open(zenoh_config::peer()).res_async()).unwrap(); - let session2 = ztimeout!(zenoh::open(zenoh_config::peer()).res_async()).unwrap(); + let session1 = ztimeout!(zenoh::open(zenoh_config::peer())).unwrap(); + let session2 = ztimeout!(zenoh::open(zenoh_config::peer())).unwrap(); let publisher1 = ztimeout!(session1 .declare_publisher("test/qos") .priority(Priority::DataHigh) - .congestion_control(CongestionControl::Drop) - .res()) + .congestion_control(CongestionControl::Drop)) .unwrap(); let publisher2 = ztimeout!(session1 .declare_publisher("test/qos") .priority(Priority::DataLow) - .congestion_control(CongestionControl::Block) - .res()) + .congestion_control(CongestionControl::Block)) .unwrap(); - let subscriber = ztimeout!(session2.declare_subscriber("test/qos").res()).unwrap(); + let subscriber = ztimeout!(session2.declare_subscriber("test/qos")).unwrap(); tokio::time::sleep(SLEEP).await; - ztimeout!(publisher1.put("qos").res_async()).unwrap(); + ztimeout!(publisher1.put("qos")).unwrap(); let sample = ztimeout!(subscriber.recv_async()).unwrap(); assert_eq!(sample.priority(), Priority::DataHigh); assert_eq!(sample.congestion_control(), CongestionControl::Drop); - ztimeout!(publisher2.put("qos").res_async()).unwrap(); + ztimeout!(publisher2.put("qos")).unwrap(); let sample = ztimeout!(subscriber.recv_async()).unwrap(); assert_eq!(sample.priority(), Priority::DataLow); diff --git a/zenoh/tests/routing.rs b/zenoh/tests/routing.rs index dd6e7fd715..3c9f2723a6 100644 --- a/zenoh/tests/routing.rs +++ b/zenoh/tests/routing.rs @@ -18,7 +18,7 @@ use std::time::Duration; use tokio_util::{sync::CancellationToken, task::TaskTracker}; use zenoh::core::Result; use zenoh::internal::{bail, ztimeout}; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; const TIMEOUT: Duration = Duration::from_secs(10); const MSG_COUNT: usize = 50; @@ -47,7 +47,7 @@ impl Task { match self { // The Sub task checks if the incoming message matches the expected size until it receives enough counts. Self::Sub(ke, expected_size) => { - let sub = ztimeout!(session.declare_subscriber(ke).res_async())?; + let sub = ztimeout!(session.declare_subscriber(ke))?; let mut counter = 0; loop { tokio::select! { @@ -77,10 +77,11 @@ impl Task { _ = token.cancelled() => break, // WARN: this won't yield after a timeout since the put is a blocking call - res = tokio::time::timeout(std::time::Duration::from_secs(1), session + res = tokio::time::timeout(std::time::Duration::from_secs(1), async {session .put(ke, vec![0u8; *payload_size]) .congestion_control(CongestionControl::Block) - .res()) => { + .await + }) => { let _ = res?; } } @@ -94,7 +95,7 @@ impl Task { while counter < MSG_COUNT { tokio::select! { _ = token.cancelled() => break, - replies = session.get(ke).timeout(Duration::from_secs(10)).res() => { + replies = async { session.get(ke).timeout(Duration::from_secs(10)).await } => { let replies = replies?; while let Ok(reply) = replies.recv_async().await { match reply.result() { @@ -124,14 +125,14 @@ impl Task { // The Queryable task keeps replying to requested messages until all checkpoints are finished. Self::Queryable(ke, payload_size) => { - let queryable = ztimeout!(session.declare_queryable(ke).res_async())?; + let queryable = ztimeout!(session.declare_queryable(ke))?; let payload = vec![0u8; *payload_size]; loop { tokio::select! { _ = token.cancelled() => break, query = queryable.recv_async() => { - ztimeout!(query?.reply(ke.to_owned(), payload.clone()).res_async())?; + ztimeout!(query?.reply(ke.to_owned(), payload.clone()))?; }, } } @@ -276,7 +277,7 @@ impl Recipe { // In case of client can't connect to some peers/routers loop { - if let Ok(session) = ztimeout!(zenoh::open(config.clone()).res_async()) { + if let Ok(session) = ztimeout!(zenoh::open(config.clone())) { break session.into_arc(); } else { tokio::time::sleep(Duration::from_secs(1)).await; @@ -312,7 +313,7 @@ impl Recipe { // node_task_tracker.wait().await; // Close the session once all the task assoicated with the node are done. - ztimeout!(Arc::try_unwrap(session).unwrap().close().res_async())?; + ztimeout!(Arc::try_unwrap(session).unwrap().close())?; println!("Node: {} is closed.", &node.name); Result::Ok(()) diff --git a/zenoh/tests/session.rs b/zenoh/tests/session.rs index 91d9b6d95b..b52dbb90b8 100644 --- a/zenoh/tests/session.rs +++ b/zenoh/tests/session.rs @@ -15,7 +15,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use zenoh::internal::ztimeout; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; +#[cfg(feature = "unstable")] use zenoh::runtime::Runtime; const TIMEOUT: Duration = Duration::from_secs(60); @@ -33,7 +34,7 @@ async fn open_session_unicast(endpoints: &[&str]) -> (Session, Session) { .collect::>(); config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][01a] Opening peer01 session: {:?}", endpoints); - let peer01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer01 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.connect.endpoints = endpoints @@ -42,7 +43,7 @@ async fn open_session_unicast(endpoints: &[&str]) -> (Session, Session) { .collect::>(); config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][02a] Opening peer02 session: {:?}", endpoints); - let peer02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer02 = ztimeout!(zenoh::open(config)).unwrap(); (peer01, peer02) } @@ -53,22 +54,22 @@ async fn open_session_multicast(endpoint01: &str, endpoint02: &str) -> (Session, config.listen.endpoints = vec![endpoint01.parse().unwrap()]; config.scouting.multicast.set_enabled(Some(true)).unwrap(); println!("[ ][01a] Opening peer01 session: {}", endpoint01); - let peer01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer01 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.listen.endpoints = vec![endpoint02.parse().unwrap()]; config.scouting.multicast.set_enabled(Some(true)).unwrap(); println!("[ ][02a] Opening peer02 session: {}", endpoint02); - let peer02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer02 = ztimeout!(zenoh::open(config)).unwrap(); (peer01, peer02) } async fn close_session(peer01: Session, peer02: Session) { println!("[ ][01d] Closing peer01 session"); - ztimeout!(peer01.close().res_async()).unwrap(); + ztimeout!(peer01.close()).unwrap(); println!("[ ][02d] Closing peer02 session"); - ztimeout!(peer02.close().res_async()).unwrap(); + ztimeout!(peer02.close()).unwrap(); } async fn test_session_pubsub(peer01: &Session, peer02: &Session, reliability: Reliability) { @@ -85,13 +86,10 @@ async fn test_session_pubsub(peer01: &Session, peer02: &Session, reliability: Re // Subscribe to data println!("[PS][01b] Subscribing on peer01 session"); let c_msgs = msgs.clone(); - let sub = ztimeout!(peer01 - .declare_subscriber(key_expr) - .callback(move |sample| { - assert_eq!(sample.payload().len(), size); - c_msgs.fetch_add(1, Ordering::Relaxed); - }) - .res_async()) + let sub = ztimeout!(peer01.declare_subscriber(key_expr).callback(move |sample| { + assert_eq!(sample.payload().len(), size); + c_msgs.fetch_add(1, Ordering::Relaxed); + })) .unwrap(); // Wait for the declaration to propagate @@ -102,8 +100,7 @@ async fn test_session_pubsub(peer01: &Session, peer02: &Session, reliability: Re for _ in 0..msg_count { ztimeout!(peer02 .put(key_expr, vec![0u8; size]) - .congestion_control(CongestionControl::Block) - .res_async()) + .congestion_control(CongestionControl::Block)) .unwrap(); } @@ -123,7 +120,7 @@ async fn test_session_pubsub(peer01: &Session, peer02: &Session, reliability: Re tokio::time::sleep(SLEEP).await; println!("[PS][03b] Unsubscribing on peer01 session"); - ztimeout!(sub.undeclare().res_async()).unwrap(); + ztimeout!(sub.undeclare()).unwrap(); // Wait for the declaration to propagate tokio::time::sleep(SLEEP).await; @@ -144,43 +141,36 @@ async fn test_session_qryrep(peer01: &Session, peer02: &Session, reliability: Re // Queryable to data println!("[QR][01c] Queryable on peer01 session"); let c_msgs = msgs.clone(); - let qbl = ztimeout!(peer01 - .declare_queryable(key_expr) - .callback(move |query| { - c_msgs.fetch_add(1, Ordering::Relaxed); - match query.parameters().as_str() { - "ok_put" => { - tokio::task::block_in_place(|| { - tokio::runtime::Handle::current().block_on(async { - ztimeout!(query - .reply( - KeyExpr::try_from(key_expr).unwrap(), - vec![0u8; size].to_vec() - ) - .res_async()) - .unwrap() - }) - }); - } - "ok_del" => { - tokio::task::block_in_place(|| { - tokio::runtime::Handle::current().block_on(async { - ztimeout!(query.reply_del(key_expr).res_async()).unwrap() - }) - }); - } - "err" => { - let rep = Value::from(vec![0u8; size]); - tokio::task::block_in_place(|| { - tokio::runtime::Handle::current().block_on(async { - ztimeout!(query.reply_err(rep).res_async()).unwrap() - }) - }); - } - _ => panic!("Unknown query parameter"), + let qbl = ztimeout!(peer01.declare_queryable(key_expr).callback(move |query| { + c_msgs.fetch_add(1, Ordering::Relaxed); + match query.parameters().as_str() { + "ok_put" => { + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(async { + ztimeout!(query.reply( + KeyExpr::try_from(key_expr).unwrap(), + vec![0u8; size].to_vec() + )) + .unwrap() + }) + }); } - }) - .res_async()) + "ok_del" => { + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current() + .block_on(async { ztimeout!(query.reply_del(key_expr)).unwrap() }) + }); + } + "err" => { + let rep = Value::from(vec![0u8; size]); + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current() + .block_on(async { ztimeout!(query.reply_err(rep)).unwrap() }) + }); + } + _ => panic!("Unknown query parameter"), + } + })) .unwrap(); // Wait for the declaration to propagate @@ -191,7 +181,7 @@ async fn test_session_qryrep(peer01: &Session, peer02: &Session, reliability: Re let mut cnt = 0; for _ in 0..msg_count { let selector = format!("{}?ok_put", key_expr); - let rs = ztimeout!(peer02.get(selector).res_async()).unwrap(); + let rs = ztimeout!(peer02.get(selector)).unwrap(); while let Ok(s) = ztimeout!(rs.recv_async()) { let s = s.result().unwrap(); assert_eq!(s.kind(), SampleKind::Put); @@ -209,7 +199,7 @@ async fn test_session_qryrep(peer01: &Session, peer02: &Session, reliability: Re let mut cnt = 0; for _ in 0..msg_count { let selector = format!("{}?ok_del", key_expr); - let rs = ztimeout!(peer02.get(selector).res_async()).unwrap(); + let rs = ztimeout!(peer02.get(selector)).unwrap(); while let Ok(s) = ztimeout!(rs.recv_async()) { let s = s.result().unwrap(); assert_eq!(s.kind(), SampleKind::Delete); @@ -227,7 +217,7 @@ async fn test_session_qryrep(peer01: &Session, peer02: &Session, reliability: Re let mut cnt = 0; for _ in 0..msg_count { let selector = format!("{}?err", key_expr); - let rs = ztimeout!(peer02.get(selector).res_async()).unwrap(); + let rs = ztimeout!(peer02.get(selector)).unwrap(); while let Ok(s) = ztimeout!(rs.recv_async()) { let e = s.result().unwrap_err(); assert_eq!(e.payload().len(), size); @@ -239,7 +229,7 @@ async fn test_session_qryrep(peer01: &Session, peer02: &Session, reliability: Re assert_eq!(cnt, msg_count); println!("[PS][03c] Unqueryable on peer01 session"); - ztimeout!(qbl.undeclare().res_async()).unwrap(); + ztimeout!(qbl.undeclare()).unwrap(); // Wait for the declaration to propagate tokio::time::sleep(SLEEP).await; @@ -264,6 +254,7 @@ async fn zenoh_session_multicast() { close_session(peer01, peer02).await; } +#[cfg(feature = "unstable")] async fn open_session_unicast_runtime(endpoints: &[&str]) -> (Runtime, Runtime) { // Open the sessions let mut config = config::peer(); @@ -287,15 +278,16 @@ async fn open_session_unicast_runtime(endpoints: &[&str]) -> (Runtime, Runtime) (r1, r2) } +#[cfg(feature = "unstable")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn zenoh_2sessions_1runtime_init() { let (r1, r2) = open_session_unicast_runtime(&["tcp/127.0.0.1:17449"]).await; println!("[RI][02a] Creating peer01 session from runtime 1"); - let peer01 = zenoh::session::init(r1.clone()).res_async().await.unwrap(); + let peer01 = zenoh::session::init(r1.clone()).await.unwrap(); println!("[RI][02b] Creating peer02 session from runtime 2"); - let peer02 = zenoh::session::init(r2.clone()).res_async().await.unwrap(); + let peer02 = zenoh::session::init(r2.clone()).await.unwrap(); println!("[RI][02c] Creating peer01a session from runtime 1"); - let peer01a = zenoh::session::init(r1.clone()).res_async().await.unwrap(); + let peer01a = zenoh::session::init(r1.clone()).await.unwrap(); println!("[RI][03c] Closing peer01a session"); std::mem::drop(peer01a); test_session_pubsub(&peer01, &peer02, Reliability::Reliable).await; diff --git a/zenoh/tests/shm.rs b/zenoh/tests/shm.rs index a7bc481e27..ec77890c1e 100644 --- a/zenoh/tests/shm.rs +++ b/zenoh/tests/shm.rs @@ -17,7 +17,7 @@ mod tests { use std::sync::Arc; use std::time::Duration; use zenoh::internal::ztimeout; - use zenoh::prelude::r#async::*; + use zenoh::prelude::*; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); @@ -35,7 +35,7 @@ mod tests { config.scouting.multicast.set_enabled(Some(false)).unwrap(); config.transport.shared_memory.set_enabled(true).unwrap(); println!("[ ][01a] Opening peer01 session: {:?}", endpoints); - let peer01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer01 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.connect.endpoints = endpoints @@ -45,7 +45,7 @@ mod tests { config.scouting.multicast.set_enabled(Some(false)).unwrap(); config.transport.shared_memory.set_enabled(true).unwrap(); println!("[ ][02a] Opening peer02 session: {:?}", endpoints); - let peer02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer02 = ztimeout!(zenoh::open(config)).unwrap(); (peer01, peer02) } @@ -57,23 +57,23 @@ mod tests { config.scouting.multicast.set_enabled(Some(true)).unwrap(); config.transport.shared_memory.set_enabled(true).unwrap(); println!("[ ][01a] Opening peer01 session: {}", endpoint01); - let peer01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer01 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.listen.endpoints = vec![endpoint02.parse().unwrap()]; config.scouting.multicast.set_enabled(Some(true)).unwrap(); config.transport.shared_memory.set_enabled(true).unwrap(); println!("[ ][02a] Opening peer02 session: {}", endpoint02); - let peer02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let peer02 = ztimeout!(zenoh::open(config)).unwrap(); (peer01, peer02) } async fn close_session(peer01: Session, peer02: Session) { println!("[ ][01d] Closing peer02 session"); - ztimeout!(peer01.close().res_async()).unwrap(); + ztimeout!(peer01.close()).unwrap(); println!("[ ][02d] Closing peer02 session"); - ztimeout!(peer02.close().res_async()).unwrap(); + ztimeout!(peer02.close()).unwrap(); } async fn test_session_pubsub(peer01: &Session, peer02: &Session, reliability: Reliability) { @@ -96,8 +96,7 @@ mod tests { .callback(move |sample| { assert_eq!(sample.payload().len(), size); c_msgs.fetch_add(1, Ordering::Relaxed); - }) - .res_async()) + })) .unwrap(); // Wait for the declaration to propagate @@ -135,8 +134,7 @@ mod tests { // Publish this message ztimeout!(peer02 .put(&key_expr, sbuf) - .congestion_control(CongestionControl::Block) - .res_async()) + .congestion_control(CongestionControl::Block)) .unwrap(); println!("{c} putted"); } diff --git a/zenoh/tests/unicity.rs b/zenoh/tests/unicity.rs index fcddcf3b3e..c5be555a00 100644 --- a/zenoh/tests/unicity.rs +++ b/zenoh/tests/unicity.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use std::time::Duration; use tokio::runtime::Handle; use zenoh::internal::ztimeout; -use zenoh::prelude::r#async::*; +use zenoh::prelude::*; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); @@ -29,14 +29,14 @@ async fn open_p2p_sessions() -> (Session, Session, Session) { config.listen.endpoints = vec!["tcp/127.0.0.1:27447".parse().unwrap()]; config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][01a] Opening s01 session"); - let s01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s01 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.listen.endpoints = vec!["tcp/127.0.0.1:27448".parse().unwrap()]; config.connect.endpoints = vec!["tcp/127.0.0.1:27447".parse().unwrap()]; config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][02a] Opening s02 session"); - let s02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s02 = ztimeout!(zenoh::open(config)).unwrap(); let mut config = config::peer(); config.connect.endpoints = vec![ @@ -45,7 +45,7 @@ async fn open_p2p_sessions() -> (Session, Session, Session) { ]; config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][03a] Opening s03 session"); - let s03 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s03 = ztimeout!(zenoh::open(config)).unwrap(); (s01, s02, s03) } @@ -57,38 +57,38 @@ async fn open_router_session() -> Session { config.listen.endpoints = vec!["tcp/127.0.0.1:37447".parse().unwrap()]; config.scouting.multicast.set_enabled(Some(false)).unwrap(); println!("[ ][00a] Opening router session"); - ztimeout!(zenoh::open(config).res_async()).unwrap() + ztimeout!(zenoh::open(config)).unwrap() } async fn close_router_session(s: Session) { println!("[ ][01d] Closing router session"); - ztimeout!(s.close().res_async()).unwrap(); + ztimeout!(s.close()).unwrap(); } async fn open_client_sessions() -> (Session, Session, Session) { // Open the sessions let config = config::client(["tcp/127.0.0.1:37447".parse::().unwrap()]); println!("[ ][01a] Opening s01 session"); - let s01 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s01 = ztimeout!(zenoh::open(config)).unwrap(); let config = config::client(["tcp/127.0.0.1:37447".parse::().unwrap()]); println!("[ ][02a] Opening s02 session"); - let s02 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s02 = ztimeout!(zenoh::open(config)).unwrap(); let config = config::client(["tcp/127.0.0.1:37447".parse::().unwrap()]); println!("[ ][03a] Opening s03 session"); - let s03 = ztimeout!(zenoh::open(config).res_async()).unwrap(); + let s03 = ztimeout!(zenoh::open(config)).unwrap(); (s01, s02, s03) } async fn close_sessions(s01: Session, s02: Session, s03: Session) { println!("[ ][01d] Closing s01 session"); - ztimeout!(s01.close().res_async()).unwrap(); + ztimeout!(s01.close()).unwrap(); println!("[ ][02d] Closing s02 session"); - ztimeout!(s02.close().res_async()).unwrap(); + ztimeout!(s02.close()).unwrap(); println!("[ ][03d] Closing s03 session"); - ztimeout!(s03.close().res_async()).unwrap(); + ztimeout!(s03.close()).unwrap(); } async fn test_unicity_pubsub(s01: &Session, s02: &Session, s03: &Session) { @@ -104,25 +104,19 @@ async fn test_unicity_pubsub(s01: &Session, s02: &Session, s03: &Session) { // Subscribe to data println!("[PS][01b] Subscribing on s01 session"); let c_msgs1 = msgs1.clone(); - let sub1 = ztimeout!(s01 - .declare_subscriber(key_expr) - .callback(move |sample| { - assert_eq!(sample.payload().len(), size); - c_msgs1.fetch_add(1, Ordering::Relaxed); - }) - .res_async()) + let sub1 = ztimeout!(s01.declare_subscriber(key_expr).callback(move |sample| { + assert_eq!(sample.payload().len(), size); + c_msgs1.fetch_add(1, Ordering::Relaxed); + })) .unwrap(); // Subscribe to data println!("[PS][02b] Subscribing on s02 session"); let c_msgs2 = msgs2.clone(); - let sub2 = ztimeout!(s02 - .declare_subscriber(key_expr) - .callback(move |sample| { - assert_eq!(sample.payload().len(), size); - c_msgs2.fetch_add(1, Ordering::Relaxed); - }) - .res_async()) + let sub2 = ztimeout!(s02.declare_subscriber(key_expr).callback(move |sample| { + assert_eq!(sample.payload().len(), size); + c_msgs2.fetch_add(1, Ordering::Relaxed); + })) .unwrap(); // Wait for the declaration to propagate @@ -133,8 +127,7 @@ async fn test_unicity_pubsub(s01: &Session, s02: &Session, s03: &Session) { for _ in 0..msg_count { ztimeout!(s03 .put(key_expr, vec![0u8; size]) - .congestion_control(CongestionControl::Block) - .res_async()) + .congestion_control(CongestionControl::Block)) .unwrap(); } @@ -162,10 +155,10 @@ async fn test_unicity_pubsub(s01: &Session, s02: &Session, s03: &Session) { assert_eq!(cnt2, msg_count); println!("[PS][02b] Unsubscribing on s02 session"); - ztimeout!(sub2.undeclare().res_async()).unwrap(); + ztimeout!(sub2.undeclare()).unwrap(); println!("[PS][01b] Unsubscribing on s01 session"); - ztimeout!(sub1.undeclare().res_async()).unwrap(); + ztimeout!(sub1.undeclare()).unwrap(); // Wait for the declaration to propagate tokio::time::sleep(SLEEP).await; @@ -186,42 +179,34 @@ async fn test_unicity_qryrep(s01: &Session, s02: &Session, s03: &Session) { println!("[QR][01c] Queryable on s01 session"); let cke = key_expr.clone(); let c_msgs1 = msgs1.clone(); - let qbl1 = ztimeout!(s01 - .declare_queryable(cke.clone()) - .callback(move |sample| { - c_msgs1.fetch_add(1, Ordering::Relaxed); - tokio::task::block_in_place({ - let cke2 = cke.clone(); - move || { - Handle::current().block_on(async move { - ztimeout!(sample.reply(cke2.clone(), vec![0u8; size]).res_async()) - .unwrap() - }); - } - }); - }) - .res_async()) + let qbl1 = ztimeout!(s01.declare_queryable(cke.clone()).callback(move |sample| { + c_msgs1.fetch_add(1, Ordering::Relaxed); + tokio::task::block_in_place({ + let cke2 = cke.clone(); + move || { + Handle::current().block_on(async move { + ztimeout!(sample.reply(cke2.clone(), vec![0u8; size])).unwrap() + }); + } + }); + })) .unwrap(); // Queryable to data println!("[QR][02c] Queryable on s02 session"); let cke = key_expr.clone(); let c_msgs2 = msgs2.clone(); - let qbl2 = ztimeout!(s02 - .declare_queryable(cke.clone()) - .callback(move |sample| { - c_msgs2.fetch_add(1, Ordering::Relaxed); - tokio::task::block_in_place({ - let cke2 = cke.clone(); - move || { - Handle::current().block_on(async move { - ztimeout!(sample.reply(cke2.clone(), vec![0u8; size]).res_async()) - .unwrap() - }); - } - }); - }) - .res_async()) + let qbl2 = ztimeout!(s02.declare_queryable(cke.clone()).callback(move |sample| { + c_msgs2.fetch_add(1, Ordering::Relaxed); + tokio::task::block_in_place({ + let cke2 = cke.clone(); + move || { + Handle::current().block_on(async move { + ztimeout!(sample.reply(cke2.clone(), vec![0u8; size])).unwrap() + }); + } + }); + })) .unwrap(); // Wait for the declaration to propagate @@ -232,7 +217,7 @@ async fn test_unicity_qryrep(s01: &Session, s02: &Session, s03: &Session) { let cke = key_expr.clone(); let mut cnt = 0; for _ in 0..msg_count { - let rs = ztimeout!(s03.get(cke.clone()).res_async()).unwrap(); + let rs = ztimeout!(s03.get(cke.clone())).unwrap(); while let Ok(s) = ztimeout!(rs.recv_async()) { assert_eq!(s.result().unwrap().payload().len(), size); cnt += 1; @@ -248,10 +233,10 @@ async fn test_unicity_qryrep(s01: &Session, s02: &Session, s03: &Session) { assert_eq!(cnt, msg_count); println!("[PS][01c] Unqueryable on s01 session"); - ztimeout!(qbl1.undeclare().res_async()).unwrap(); + ztimeout!(qbl1.undeclare()).unwrap(); println!("[PS][02c] Unqueryable on s02 session"); - ztimeout!(qbl2.undeclare().res_async()).unwrap(); + ztimeout!(qbl2.undeclare()).unwrap(); // Wait for the declaration to propagate tokio::time::sleep(SLEEP).await; diff --git a/zenohd/src/main.rs b/zenohd/src/main.rs index d8fed7eeb4..cabee33333 100644 --- a/zenohd/src/main.rs +++ b/zenohd/src/main.rs @@ -19,7 +19,6 @@ use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::EnvFilter; use zenoh::config::EndPoint; use zenoh::config::{Config, ModeDependentValue, PermissionsConf, ValidatedMap}; -use zenoh::core::AsyncResolve; use zenoh::core::Result; use zenoh::scouting::WhatAmI; @@ -107,7 +106,7 @@ fn main() { let config = config_from_args(&args); tracing::info!("Initial conf: {}", &config); - let _session = match zenoh::open(config).res_async().await { + let _session = match zenoh::open(config).await { Ok(runtime) => runtime, Err(e) => { println!("{e}. Exiting...");