Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

atexit-safe close builder draft #1576

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ libloading = "0.8"
tracing = "0.1"
lockfree = "0.5"
lz4_flex = "0.11"
nolocal-block-on = "1.0.1"
nix = { version = "0.29.0", features = ["fs"] }
num_cpus = "1.16.0"
num-traits = { version = "0.2.19", default-features = false }
Expand Down
1 change: 1 addition & 0 deletions zenoh/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ git-version = { workspace = true }
itertools = { workspace = true }
json5 = { workspace = true }
lazy_static = { workspace = true }
nolocal-block-on = { workspace = true }
tracing = { workspace = true }
paste = { workspace = true }
petgraph = { workspace = true }
Expand Down
117 changes: 86 additions & 31 deletions zenoh/src/api/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,23 @@ use std::{
collections::HashMap,
convert::TryInto,
fmt,
future::{Future, IntoFuture},
ops::Deref,
pin::Pin,
sync::{
atomic::{AtomicU16, Ordering},
Arc, Mutex, RwLock,
},
time::{Duration, SystemTime, UNIX_EPOCH},
};

use tracing::{error, info, trace, warn};
use uhlc::Timestamp;
#[cfg(feature = "internal")]
use uhlc::HLC;
use zenoh_buffers::ZBuf;
use zenoh_collections::SingleOrVec;
use zenoh_config::{unwrap_or_default, wrappers::ZenohId};
use zenoh_core::{zconfigurable, zread, Resolve, ResolveClosure, ResolveFuture, Wait};
use zenoh_core::{zconfigurable, zread, Resolvable, Resolve, ResolveClosure, ResolveFuture, Wait};
#[cfg(feature = "unstable")]
use zenoh_protocol::network::{
declare::{DeclareToken, SubscriberId, TokenId, UndeclareToken},
Expand Down Expand Up @@ -615,8 +616,8 @@ impl Session {
/// subscriber_task.await.unwrap();
/// # }
/// ```
pub fn close(&self) -> impl Resolve<ZResult<()>> + '_ {
self.0.close()
pub fn close(&self) -> SessionCloseBuilder {
SessionCloseBuilder::new(self.0.clone())
}

/// Check if the session has been closed.
Expand Down Expand Up @@ -1073,38 +1074,39 @@ impl Session {
})
}
}

impl SessionInner {
pub fn zid(&self) -> ZenohId {
self.runtime.zid()
}

fn close(&self) -> impl Resolve<ZResult<()>> + '_ {
ResolveFuture::new(async move {
let Some(primitives) = zwrite!(self.state).primitives.take() else {
return Ok(());
};
if self.owns_runtime {
info!(zid = %self.zid(), "close session");
}
self.task_controller.terminate_all(Duration::from_secs(10));
if self.owns_runtime {
self.runtime.close().await?;
} else {
primitives.send_close();
}
let mut state = zwrite!(self.state);
state.queryables.clear();
state.subscribers.clear();
state.liveliness_subscribers.clear();
state.local_resources.clear();
state.remote_resources.clear();
#[cfg(feature = "unstable")]
{
state.tokens.clear();
state.matching_listeners.clear();
}
Ok(())
})
async fn close(&self, _timeout: Duration) -> ZResult<()> {
let Some(primitives) = zwrite!(self.state).primitives.take() else {
return Ok(());
};
if self.owns_runtime {
info!(zid = %self.zid(), "close session");
}
self.task_controller
.terminate_all_async(Duration::from_secs(10))
.await;
if self.owns_runtime {
self.runtime.close().await?
} else {
primitives.send_close();
}
let mut state = zwrite!(self.state);
state.queryables.clear();
state.subscribers.clear();
state.liveliness_subscribers.clear();
state.local_resources.clear();
state.remote_resources.clear();
#[cfg(feature = "unstable")]
{
state.tokens.clear();
state.matching_listeners.clear();
}
Ok(())
}

pub(crate) fn declare_prefix<'a>(
Expand Down Expand Up @@ -2880,3 +2882,56 @@ where
{
OpenBuilder::new(config)
}

/// A builder for closing a [`crate::Session`].
///
/// # Examples
/// ```
/// # #[tokio::main]
/// # async fn main() {
///
/// let session = zenoh::open(zenoh::Config::default()).await.unwrap();
/// session.close()
/// .timeout(std::time::Duration::from_secs(10))
/// .await
/// .unwrap();
/// # }
/// ```

pub struct SessionCloseBuilder {
inner: Arc<SessionInner>,
timeout: Duration,
}

impl SessionCloseBuilder {
fn new(inner: Arc<SessionInner>) -> Self {
Self {
inner,
timeout: Duration::MAX,
}
}

pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
}

impl Resolvable for SessionCloseBuilder {
type To = ZResult<()>;
}

impl Wait for SessionCloseBuilder {
fn wait(self) -> Self::To {
nolocal_block_on::block_on(self.into_future())
}
}

impl IntoFuture for SessionCloseBuilder {
type Output = <Self as Resolvable>::To;
type IntoFuture = Pin<Box<dyn Future<Output = <Self as IntoFuture>::Output> + Send>>;

fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.inner.close(self.timeout).await }.into_future())
}
}
Loading