Session

Struct Session 

Source
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

Source

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.

Source

pub fn id(&self) -> EntityGlobalId

Available on crate feature unstable only.

Returns the EntityGlobalId of this Session.

This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
Source

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();
Source

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());
Source

pub fn undeclare<'a, T>(&'a self, decl: T) -> impl Resolve<ZResult<()>> + 'a
where 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();
Source

pub fn config(&self) -> GenericConfig

Available on crate feature unstable only.

Get the current configuration of the zenoh Session.

This API has been marked as unstable: it works as advertised, but it may be changed in a future release.

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();
Source

pub fn new_timestamp(&self) -> Timestamp

Get a new Timestamp from a Zenoh Session.

The returned timestamp has the current time, with the Session’s runtime ZenohId.

§Examples
§Get a new timestamp

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let timestamp = session.new_timestamp();
Source§

impl Session

Source

pub fn info(&self) -> SessionInfo

Get information about the zenoh Session.

§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let info = session.info();
Source

pub fn get_shm_provider(&self) -> ShmProviderState

Available on crate feature unstable only.

Returns the ShmProviderState associated with the current Session’s Runtime.

This API has been marked as unstable: it works as advertised, but it may be changed in a future release.

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());
Source

pub fn declare_subscriber<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> SubscriberBuilder<'_, 'b, DefaultHandler>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

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;
Source

pub fn declare_queryable<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QueryableBuilder<'_, 'b, DefaultHandler>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Create a Queryable for the given key expression.

§Arguments
  • key_expr - The key expression matching the queries the Queryable will 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;
Source

pub fn declare_publisher<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> PublisherBuilder<'_, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

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();
Source

pub fn declare_querier<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QuerierBuilder<'_, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

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();
Source

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

Source

pub fn declare_keyexpr<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> impl Resolve<ZResult<KeyExpr<'b>>> + 'a
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

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();
Source

pub fn put<'a, 'b: 'a, TryIntoKeyExpr, IntoZBytes>( &'a self, key_expr: TryIntoKeyExpr, payload: IntoZBytes, ) -> SessionPutBuilder<'a, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>, IntoZBytes: Into<ZBytes>,

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 put
  • payload - 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();
Source

pub fn delete<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> SessionDeleteBuilder<'a, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

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();
Source

pub fn get<'a, 'b: 'a, TryIntoSelector>( &'a self, selector: TryIntoSelector, ) -> SessionGetBuilder<'a, 'b, DefaultHandler>
where TryIntoSelector: TryInto<Selector<'b>>, <TryIntoSelector as TryInto<Selector<'b>>>::Error: Into<Error>,

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§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Session

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<Source> AccessAs for Source

Source§

fn ref_as<T>(&self) -> <Source as IGuardRef<T>>::Guard<'_>
where Source: IGuardRef<T>, T: ?Sized,

Provides immutable access to a type as if it were its ABI-unstable equivalent.
Source§

fn mut_as<T>(&mut self) -> <Source as IGuardMut<T>>::GuardMut<'_>
where Source: IGuardMut<T>, T: ?Sized,

Provides mutable access to a type as if it were its ABI-unstable equivalent.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsNode<T> for T

Source§

fn as_node(&self) -> &T

Source§

impl<T> AsNodeMut<T> for T

Source§

fn as_node_mut(&mut self) -> &mut T

Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, As> IGuardMut<As> for T
where T: Into<As>, As: Into<T>,

Source§

type GuardMut<'a> = MutAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary after applying its changes to the original.
Source§

fn guard_mut_inner(&mut self) -> <T as IGuardMut<As>>::GuardMut<'_>

Construct the temporary and guard it through a mutable reference.
Source§

impl<T, As> IGuardRef<As> for T
where T: Into<As>, As: Into<T>,

Source§

type Guard<'a> = RefAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary.
Source§

fn guard_ref_inner(&self) -> <T as IGuardRef<As>>::Guard<'_>

Construct the temporary and guard it through an immutable reference.
Source§

impl<T> Includes<End> for T

Source§

type Output = End

The result
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more