pub struct SubscriptionSink { /* private fields */ }
Expand description

Represents a single subscription.

Implementations§

source§

impl SubscriptionSink

source

pub fn reject( &mut self, err: impl Into<ErrorObjectOwned> ) -> Result<(), SubscriptionAcceptRejectError>

Reject the subscription call from ErrorObject.

source

pub fn accept(&mut self) -> Result<(), SubscriptionAcceptRejectError>

Attempt to accept the subscription and respond the subscription method call.

Fails if the connection was closed, or if called multiple times.

source

pub fn subscription_id(&self) -> Option<RpcSubscriptionId<'static>>

Return the subscription ID if the the subscription was accepted.

SubscriptionSink::accept should be called prior to this method.

source

pub fn send<T: Serialize>(&mut self, result: &T) -> Result<bool, Error>

Send a message back to subscribers.

Returns

  • Ok(true) if the message could be send.
  • Ok(false) if the sink was closed (either because the subscription was closed or the connection was terminated), or the subscription could not be accepted.
  • Err(err) if the message could not be serialized.
source

pub async fn pipe_from_try_stream<S, T, E>( &mut self, stream: S ) -> SubscriptionClosedwhere S: TryStream<Ok = T, Error = E> + Unpin, T: Serialize, E: Display,

Reads data from the stream and sends back data on the subscription when items gets produced by the stream. The underlying stream must produce Result values, see [futures_util::TryStream`] for further information.

Returns Ok(()) if the stream or connection was terminated. Returns Err(_) immediately if the underlying stream returns an error or if an item from the stream could not be serialized.

Examples

use jsonrpsee_core::server::rpc_module::RpcModule;
use jsonrpsee_core::error::{Error, SubscriptionClosed};
use jsonrpsee_types::ErrorObjectOwned;
use anyhow::anyhow;

let mut m = RpcModule::new(());
m.register_subscription("sub", "_", "unsub", |params, mut sink, _| {
    let stream = futures_util::stream::iter(vec![Ok(1_u32), Ok(2), Err("error on the stream")]);
    // This will return send `[Ok(1_u32), Ok(2_u32), Err(Error::SubscriptionClosed))]` to the subscriber
    // because after the `Err(_)` the stream is terminated.
    let stream = futures_util::stream::iter(vec![Ok(1_u32), Ok(2), Err("error on the stream")]);

    tokio::spawn(async move {

        // jsonrpsee doesn't send an error notification unless `close` is explicitly called.
        // If we pipe messages to the sink, we can inspect why it ended:
        match sink.pipe_from_try_stream(stream).await {
           SubscriptionClosed::Success => {
               let err_obj: ErrorObjectOwned = SubscriptionClosed::Success.into();
               sink.close(err_obj);
           }
           // we don't want to send close reason when the client is unsubscribed or disconnected.
           SubscriptionClosed::RemotePeerAborted => (),
           SubscriptionClosed::Failed(e) => {
               sink.close(e);
           }
        }
    });
    Ok(())
});
source

pub async fn pipe_from_stream<S, T>(&mut self, stream: S) -> SubscriptionClosedwhere S: Stream<Item = T> + Unpin, T: Serialize,

Similar to SubscriptionSink::pipe_from_try_stream but it doesn’t require the stream return Result.

Warning: it’s possible to pass in a stream that returns Result if Result: Serialize is satisfied but it won’t cancel the stream when an error occurs. If you want the stream to be canceled when an error occurs use SubscriptionSink::pipe_from_try_stream instead.

Examples

use jsonrpsee_core::server::rpc_module::RpcModule;

let mut m = RpcModule::new(());
m.register_subscription("sub", "_", "unsub", |params, mut sink, _| {
    let stream = futures_util::stream::iter(vec![1_usize, 2, 3]);
    tokio::spawn(async move { sink.pipe_from_stream(stream).await; });
    Ok(())
});
source

pub fn is_closed(&self) -> bool

Returns whether the subscription is closed.

source

pub fn close(self, err: impl Into<ErrorObjectOwned>) -> bool

Close the subscription, sending a notification with a special error field containing the provided error.

This can be used to signal an actual error, or just to signal that the subscription has been closed, depending on your preference.

If you’d like to to close the subscription without sending an error, just drop it and don’t call this method.

{
 "jsonrpc": "2.0",
 "method": "<method>",
 "params": {
   "subscription": "<subscriptionID>",
   "error": { "code": <code from error>, "message": <message from error>, "data": <data from error> }
   }
 }
}

Trait Implementations§

source§

impl Debug for SubscriptionSink

source§

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

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

impl Drop for SubscriptionSink

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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 Twhere 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> Same<T> for T

§

type Output = T

Should always be Self
source§

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

§

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 Twhere U: TryFrom<T>,

§

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 Twhere 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
source§

impl<T> MaybeSend for Twhere T: Send,