pub struct Session(/* private fields */);Expand description
The Session is the main component of Zenoh. It holds the zenoh runtime object,
which maintains the state of the connection of the node to the Zenoh network.
The session allows declaring other zenoh entities like publishers, subscribers, queriers, queryables, etc. and keeps them functioning. Closing the session will close all associated entities.
The session is cloneable so it’s easy to share it between tasks and threads. Each clone of the
session is an Arc to the internal session object, so cloning is cheap and fast.
A Zenoh session is instantiated using zenoh::open
with parameters specified in the Config object.
Objects created by the session (Publisher,
Subscriber, Querier, etc.),
have lifetimes independent of the session, but they stop functioning if all clones of the session
object are dropped or the session is closed with the close method.
§Background entities
Sometimes it is inconvenient to keep a reference to an object (for example,
a Queryable) solely to keep it alive. There is a way to
avoid keeping this reference and keep the object alive until the session is closed.
To do this, call the background method on the
corresponding builder. This causes the builder to return () instead of the object instance and
keeps the instance alive while the session is alive.
§Difference between session and runtime
The session object holds all declared zenoh entities (publishers, subscribers, etc.) and a shared reference to the runtime object which maintains the state of the zenoh node. Closing the session will close all associated entities and drop the reference to the runtime.
Typically each session has its own runtime, but in some cases
the session may share the runtime with other sessions. This is the case for the plugins
where each plugin has its own session but all plugins share the same zenohd runtime
for efficiency.
In this case, all these sessions will have the same network identity
Session::zid.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session.put("key/expression", "value").await.unwrap();Implementations§
Source§impl Session
impl Session
Sourcepub fn zid(&self) -> ZenohId
pub fn zid(&self) -> ZenohId
Returns the identifier of the current session. zid() is a convenient shortcut.
See Session::info() and SessionInfo::zid() for more details.
Sourcepub fn id(&self) -> EntityGlobalId
Available on crate feature unstable only.
pub fn id(&self) -> EntityGlobalId
unstable only.Returns the EntityGlobalId of this Session.
Sourcepub fn close(&self) -> CloseBuilder<Self>
pub fn close(&self) -> CloseBuilder<Self>
Close the zenoh Session.
Every subscriber and queryable declared will stop receiving data, and further attempts to
publish or query with the session or publishers will result in an error. Undeclaring an
entity after session closing is a no-op. Session state can be checked with
Session::is_closed.
Sessions are automatically closed when all their instances are dropped, same as Arc.
You may still want to use this function to handle errors or close the session
asynchronously.
Closing the session can also save bandwidth, as it avoids propagating the undeclaration
of the remaining entities.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let subscriber = session
.declare_subscriber("key/expression")
.await
.unwrap();
let subscriber_task = tokio::spawn(async move {
while let Ok(sample) = subscriber.recv_async().await {
println!("Received: {} {:?}", sample.key_expr(), sample.payload());
}
});
session.close().await.unwrap();
// subscriber task will end as `subscriber.recv_async()` will return `Err`
// subscriber undeclaration has not been sent over the wire
subscriber_task.await.unwrap();Sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
Check if the session has been closed.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
assert!(!session.is_closed());
session.close().await.unwrap();
assert!(session.is_closed());Sourcepub fn undeclare<'a, T>(&'a self, decl: T) -> impl Resolve<ZResult<()>> + 'awhere
T: Undeclarable<&'a Session> + 'a,
pub fn undeclare<'a, T>(&'a self, decl: T) -> impl Resolve<ZResult<()>> + 'awhere
T: Undeclarable<&'a Session> + 'a,
Undeclare a zenoh entity declared by the session.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let keyexpr = session.declare_keyexpr("key/expression").await.unwrap();
let subscriber = session
.declare_subscriber(&keyexpr)
.await
.unwrap();
session.undeclare(subscriber).await.unwrap();
session.undeclare(keyexpr).await.unwrap();Sourcepub fn config(&self) -> GenericConfig
Available on crate feature unstable only.
pub fn config(&self) -> GenericConfig
unstable only.Get the current configuration of the zenoh Session.
The returned configuration Notifier can be used to read the current
zenoh configuration through the get function or
modify the zenoh configuration through the insert
or insert_json5 function.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let peers = session.config().get("connect/endpoints").unwrap();Sourcepub fn new_timestamp(&self) -> Timestamp
pub fn new_timestamp(&self) -> Timestamp
Source§impl Session
impl Session
Sourcepub fn info(&self) -> SessionInfo
pub fn info(&self) -> SessionInfo
Sourcepub fn get_shm_provider(&self) -> ShmProviderState
Available on crate feature unstable only.
pub fn get_shm_provider(&self) -> ShmProviderState
unstable only.Returns the ShmProviderState associated with the current Session’s Runtime.
Each Runtime may create its own provider to manage internal optimizations.
This method exposes that provider so it can also be accessed at the application level.
Note that the provider may not be immediately available or may be disabled via configuration. Provider initialization is concurrent and triggered by access events (both transport-internal and through this API).
To use this provider, both shared_memory and transport_optimization config sections must be enabled.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let shm_provider = session.get_shm_provider();
assert!(shm_provider.into_option().is_none());
std::thread::sleep(std::time::Duration::from_millis(100));
let shm_provider = session.get_shm_provider();
assert!(shm_provider.into_option().is_some());Sourcepub fn declare_subscriber<'b, TryIntoKeyExpr>(
&self,
key_expr: TryIntoKeyExpr,
) -> SubscriberBuilder<'_, 'b, DefaultHandler>
pub fn declare_subscriber<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> SubscriberBuilder<'_, 'b, DefaultHandler>
Create a Subscriber for the given key expression.
§Arguments
key_expr- The resource key expression to subscribe to
§Examples
let session = zenoh::open(zenoh::Config::default()).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);
}
}).await;Sourcepub fn declare_queryable<'b, TryIntoKeyExpr>(
&self,
key_expr: TryIntoKeyExpr,
) -> QueryableBuilder<'_, 'b, DefaultHandler>
pub fn declare_queryable<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QueryableBuilder<'_, 'b, DefaultHandler>
Create a Queryable for the given key expression.
§Arguments
key_expr- The key expression matching the queries theQueryablewill reply to
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let queryable = session.declare_queryable("key/expression")
.await
.unwrap();
tokio::task::spawn(async move {
while let Ok(query) = queryable.recv_async().await {
query.reply(
"key/expression",
"value",
).await.unwrap();
}
}).await;Sourcepub fn declare_publisher<'b, TryIntoKeyExpr>(
&self,
key_expr: TryIntoKeyExpr,
) -> PublisherBuilder<'_, 'b>
pub fn declare_publisher<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> PublisherBuilder<'_, 'b>
Create a Publisher for the given key expression.
§Arguments
key_expr- The key expression matching resources to write
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let publisher = session.declare_publisher("key/expression")
.await
.unwrap();
publisher.put("value").await.unwrap();Sourcepub fn declare_querier<'b, TryIntoKeyExpr>(
&self,
key_expr: TryIntoKeyExpr,
) -> QuerierBuilder<'_, 'b>
pub fn declare_querier<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QuerierBuilder<'_, 'b>
Create a Querier for the given key expression.
§Arguments
key_expr- The key expression matching resources to query
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let querier = session.declare_querier("key/expression")
.await
.unwrap();
let replies = querier.get().await.unwrap();Sourcepub fn liveliness(&self) -> Liveliness<'_>
pub fn liveliness(&self) -> Liveliness<'_>
Obtain a Liveliness struct tied to this Zenoh Session.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let liveliness = session
.liveliness()
.declare_token("key/expression")
.await
.unwrap();Source§impl Session
impl Session
Sourcepub fn declare_keyexpr<'a, 'b: 'a, TryIntoKeyExpr>(
&'a self,
key_expr: TryIntoKeyExpr,
) -> impl Resolve<ZResult<KeyExpr<'b>>> + 'a
pub fn declare_keyexpr<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> impl Resolve<ZResult<KeyExpr<'b>>> + 'a
Informs Zenoh that you intend to use key_expr multiple times and that it should optimize its transmission.
The returned KeyExpr’s internal structure may differ from what you would have obtained through a simple
key_expr.try_into(), to save time on detecting the optimizations that have been associated with it.
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let key_expr = session.declare_keyexpr("key/expression").await.unwrap();Sourcepub fn put<'a, 'b: 'a, TryIntoKeyExpr, IntoZBytes>(
&'a self,
key_expr: TryIntoKeyExpr,
payload: IntoZBytes,
) -> SessionPutBuilder<'a, 'b>
pub fn put<'a, 'b: 'a, TryIntoKeyExpr, IntoZBytes>( &'a self, key_expr: TryIntoKeyExpr, payload: IntoZBytes, ) -> SessionPutBuilder<'a, 'b>
Publish SampleKind::Put sample directly from the session. This is a shortcut for declaring
a Publisher and calling put
on it.
§Arguments
key_expr- Key expression matching the resources to putpayload- The payload to put
§Examples
use zenoh::bytes::Encoding;
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session
.put("key/expression", "payload")
.encoding(Encoding::TEXT_PLAIN)
.await
.unwrap();Sourcepub fn delete<'a, 'b: 'a, TryIntoKeyExpr>(
&'a self,
key_expr: TryIntoKeyExpr,
) -> SessionDeleteBuilder<'a, 'b>
pub fn delete<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> SessionDeleteBuilder<'a, 'b>
Publish a SampleKind::Delete sample directly from the session. This is a shortcut for declaring
a Publisher and calling delete on it.
§Arguments
key_expr- Key expression matching the resources to delete
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session.delete("key/expression").await.unwrap();Sourcepub fn get<'a, 'b: 'a, TryIntoSelector>(
&'a self,
selector: TryIntoSelector,
) -> SessionGetBuilder<'a, 'b, DefaultHandler>
pub fn get<'a, 'b: 'a, TryIntoSelector>( &'a self, selector: TryIntoSelector, ) -> SessionGetBuilder<'a, 'b, DefaultHandler>
Query data from the matching queryables in the system. This is a shortcut for declaring
a Querier and calling get on it.
Unless explicitly requested via accept_replies,
replies are guaranteed to have
key expressions that match the requested selector.
§Arguments
selector- The selection of resources to query
§Examples
let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let replies = session.get("key/expression").await.unwrap();
while let Ok(reply) = replies.recv_async().await {
println!(">> Received {:?}", reply.result());
}Trait Implementations§
Auto Trait Implementations§
impl Freeze for Session
impl !RefUnwindSafe for Session
impl Send for Session
impl Sync for Session
impl Unpin for Session
impl !UnwindSafe for Session
Blanket Implementations§
Source§impl<Source> AccessAs for Source
impl<Source> AccessAs for Source
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more