Skip to content

add session closing callback API #2009

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

Draft
wants to merge 6 commits 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: 4 additions & 6 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 @@ -163,6 +163,7 @@ serde = { version = "1.0.210", default-features = false, features = [
serde_json = "1.0.128"
serde_with = "3.12.0"
serde_yaml = "0.9.34"
slab = "0.4.10"
static_init = "1.0.3"
stabby = "36.1.1"
sha3 = "0.10.8"
Expand Down
1 change: 1 addition & 0 deletions zenoh/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ rand = { workspace = true, features = ["default"] }
ref-cast = { workspace = true }
serde = { workspace = true, features = ["default"] }
serde_json = { workspace = true }
slab = { workspace = true }
socket2 = { workspace = true }
uhlc = { workspace = true, features = ["default"] }
vec_map = { workspace = true }
Expand Down
106 changes: 106 additions & 0 deletions zenoh/src/api/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@
pub(crate) aggregated_subscribers: Vec<OwnedKeyExpr>,
pub(crate) aggregated_publishers: Vec<OwnedKeyExpr>,
pub(crate) publisher_qos_tree: KeBoxTree<PublisherQoSConfig>,
pub(crate) closing_callbacks: ClosingCallbackList,
}

impl SessionState {
Expand Down Expand Up @@ -190,6 +191,7 @@
aggregated_subscribers,
aggregated_publishers,
publisher_qos_tree,
closing_callbacks: Default::default(),
}
}
}
Expand Down Expand Up @@ -1249,6 +1251,63 @@
source_info: SourceInfo::empty(),
}
}

/// Registers a closing callback to the session.
///
/// The callback will be called when the session will be closed. It returns an id to unregister
/// the callback with [`unregister_closing_callback`](Self::unregister_closing_callback). If
/// the session is already closed, the callback is returned in an error.
///
/// Execution order of callbacks is unspecified.
///
/// # Examples
///
/// ```rust
/// # #[tokio::main]
/// # async fn main() {
///
/// let session = zenoh::open(zenoh::Config::default()).await.unwrap();
/// if let Err(_) = session.register_closing_callback(|| println!("session closed")) {
/// println!("session already closed");
/// }
/// # }
/// ```
#[zenoh_macros::internal]
pub fn register_closing_callback<F: FnOnce() + Send + Sync + 'static>(
&self,
callback: F,
) -> Result<ClosingCallbackId, F> {
let mut state = zwrite!(self.0.state);
if state.primitives().is_err() {
return Err(callback);

Check warning on line 1282 in zenoh/src/api/session.rs

View check run for this annotation

Codecov / codecov/patch

zenoh/src/api/session.rs#L1282

Added line #L1282 was not covered by tests
}
Ok(state.closing_callbacks.insert_callback(Box::new(callback)))
}

/// Unregisters a closing callback.
///
/// The callback must have been registered with
/// [`register_closing_callback`](Self::register_closing_callback).
/// It will no longer be called on session closing.
///
/// # Examples
///
/// ```rust
/// # #[tokio::main]
/// # async fn main() {
///
/// let session = zenoh::open(zenoh::Config::default()).await.unwrap();
/// let Ok(id) = session.register_closing_callback(|| println!("session closed")) else {
/// panic!("session already closed");
/// };
/// session.unregister_closing_callback(id);
/// # }
/// ```
#[zenoh_macros::internal]
pub fn unregister_closing_callback(&self, callback_id: ClosingCallbackId) {
let mut state = zwrite!(self.0.state);
state.closing_callbacks.remove_callback(callback_id);
}
}

impl Session {
Expand Down Expand Up @@ -3213,6 +3272,7 @@
// will be stabilized.
let mut state = zwrite!(self.state);
let _matching_listeners = std::mem::take(&mut state.matching_listeners);
let _closing_callbacks = std::mem::take(&mut state.closing_callbacks);
drop(state);
}
}
Expand All @@ -3225,3 +3285,49 @@
self.0.clone()
}
}

#[derive(Default)]
pub(crate) struct ClosingCallbackList {
callbacks: slab::Slab<ClosingCallback>,
generation: usize,
}

impl ClosingCallbackList {
fn insert_callback(&mut self, callback: Box<dyn FnOnce() + Send + Sync>) -> ClosingCallbackId {
let generation = self.generation;
let index = self.callbacks.insert(ClosingCallback {
callback,
generation,
});
self.generation = self.generation.wrapping_add(1);
ClosingCallbackId { index, generation }
}

fn remove_callback(&mut self, id: ClosingCallbackId) {
if matches!( self.callbacks.get(id.index), Some(cb) if cb.generation == id.generation) {
self.callbacks.remove(id.index);
}
}
}

impl Drop for ClosingCallbackList {
fn drop(&mut self) {
for cb in self.callbacks.drain() {
(cb.callback)();
}
}
}

struct ClosingCallback {
callback: Box<dyn FnOnce() + Send + Sync>,
generation: usize,
}

/// The id of a registered session closing callback.
///
/// See [`Session::register_closing_callback`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosingCallbackId {
index: usize,
generation: usize,
}
2 changes: 2 additions & 0 deletions zenoh/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ pub mod session {

#[zenoh_macros::internal]
pub use crate::api::builders::session::{init, InitBuilder};
#[zenoh_macros::internal]
pub use crate::api::session::ClosingCallbackId;
pub use crate::api::{
builders::{
close::CloseBuilder,
Expand Down
Loading