karyon_jsonrpc::client::builder

Struct ClientBuilder

Source
pub struct ClientBuilder<C> {
    inner: ClientConfig,
    codec: C,
}
Expand description

Builder for constructing an RPC Client.

Fields§

§inner: ClientConfig§codec: C

Implementations§

Source§

impl ClientBuilder<JsonCodec>

Source

pub fn new(endpoint: impl ToEndpoint) -> Result<ClientBuilder<JsonCodec>>

Creates a new ClientBuilder

This function initializes a ClientBuilder with the specified endpoint.

§Example
use karyon_jsonrpc::client::ClientBuilder;
  
async {
    let builder = ClientBuilder::new("ws://127.0.0.1:3000")
        .expect("Create a new client builder");
    let client = builder.build().await
        .expect("Build a new client");
};
Source§

impl<C> ClientBuilder<C>
where C: ClonableJsonCodec + 'static,

Source

pub fn new_with_codec( endpoint: impl ToEndpoint, codec: C, ) -> Result<ClientBuilder<C>>

Creates a new ClientBuilder

This function initializes a ClientBuilder with the specified endpoint and the given json codec.

§Example

#[cfg(feature = "ws")]
use karyon_jsonrpc::codec::{WebSocketCodec, WebSocketDecoder, WebSocketEncoder};
#[cfg(feature = "ws")]
use async_tungstenite::tungstenite::Message;
use serde_json::Value;

use karyon_jsonrpc::{
    client::ClientBuilder, codec::{Codec, Decoder, Encoder},
    error::{Error, Result}
};

#[derive(Clone)]
pub struct CustomJsonCodec {}

impl Codec for CustomJsonCodec {
    type Message = serde_json::Value;
    type Error = Error;
}

#[cfg(feature = "ws")]
impl WebSocketCodec for CustomJsonCodec {
    type Message = serde_json::Value;
    type Error = Error;
}

impl Encoder for CustomJsonCodec {
    type EnMessage = serde_json::Value;
    type EnError = Error;
    fn encode(&self, src: &Self::EnMessage, dst: &mut [u8]) -> Result<usize> {
        let msg = match serde_json::to_string(src) {
            Ok(m) => m,
            Err(err) => return Err(Error::Encode(err.to_string())),
        };
        let buf = msg.as_bytes();
        dst[..buf.len()].copy_from_slice(buf);
        Ok(buf.len())
    }
}

impl Decoder for CustomJsonCodec {
    type DeMessage = serde_json::Value;
    type DeError = Error;
    fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeMessage)>> {
        let de = serde_json::Deserializer::from_slice(src);
        let mut iter = de.into_iter::<serde_json::Value>();

        let item = match iter.next() {
            Some(Ok(item)) => item,
            Some(Err(ref e)) if e.is_eof() => return Ok(None),
            Some(Err(e)) => return Err(Error::Decode(e.to_string())),
            None => return Ok(None),
        };

        Ok(Some((iter.byte_offset(), item)))
    }
}

#[cfg(feature = "ws")]
impl WebSocketEncoder for CustomJsonCodec {
    type EnMessage = serde_json::Value;
    type EnError = Error;

    fn encode(&self, src: &Self::EnMessage) -> Result<Message> {
        let msg = match serde_json::to_string(src) {
            Ok(m) => m,
            Err(err) => return Err(Error::Encode(err.to_string())),
        };
        Ok(Message::Text(msg))
    }
}

#[cfg(feature = "ws")]
impl WebSocketDecoder for CustomJsonCodec {
    type DeMessage = serde_json::Value;
    type DeError = Error;
    fn decode(&self, src: &Message) -> Result<Option<Self::DeMessage>> {
         match src {
             Message::Text(s) => match serde_json::from_str(s) {
                 Ok(m) => Ok(Some(m)),
                 Err(err) => Err(Error::Decode(err.to_string())),
             },
             Message::Binary(s) => match serde_json::from_slice(s) {
                 Ok(m) => Ok(m),
                 Err(err) => Err(Error::Decode(err.to_string())),
             },
             Message::Close(_) => Err(Error::IO(std::io::ErrorKind::ConnectionAborted.into())),
             m => Err(Error::Decode(format!(
                 "Receive unexpected message: {:?}",
                 m
             ))),
         }
     }
}

async {
    let builder = ClientBuilder::new_with_codec("tcp://127.0.0.1:3000", CustomJsonCodec {})
        .expect("Create a new client builder with a custom json codec");
    let client = builder.build().await
        .expect("Build a new client");
};
Source

pub fn set_timeout(self, timeout: u64) -> Self

Set timeout for receiving messages, in milliseconds. Requests will fail if it takes longer.

§Example
use karyon_jsonrpc::client::ClientBuilder;
  
async {
    let client = ClientBuilder::new("ws://127.0.0.1:3000")
        .expect("Create a new client builder")
        .set_timeout(5000)
        .build().await
        .expect("Build a new client");
};
Source

pub fn set_max_subscription_buffer_size(self, size: usize) -> Self

Set max size for the subscription buffer.

The client will stop when the subscriber cannot keep up. When subscribing to a method, a new channel with the provided buffer size is initialized. Once the buffer is full and the subscriber doesn’t process the messages in the buffer, the client will disconnect and raise an error.

§Example
use karyon_jsonrpc::client::ClientBuilder;
  
async {
    let client = ClientBuilder::new("ws://127.0.0.1:3000")
        .expect("Create a new client builder")
        .set_max_subscription_buffer_size(10000)
        .build().await
        .expect("Build a new client");
};
Source

pub fn tcp_config(self, config: TcpConfig) -> Result<Self>

Configure TCP settings for the client.

§Example
use karyon_jsonrpc::{client::ClientBuilder, net::TcpConfig};
  
async {
    let tcp_config = TcpConfig::default();

    let client = ClientBuilder::new("ws://127.0.0.1:3000")
        .expect("Create a new client builder")
        .tcp_config(tcp_config)
        .expect("Add tcp config")
        .build().await
        .expect("Build a new client");
};

This function will return an error if the endpoint does not support TCP protocols.

Source

pub async fn build(self) -> Result<Arc<Client<C>>>

Build RPC client from ClientBuilder.

This function creates a new RPC client using the configurations specified in the ClientBuilder. It returns a Arc<Client> on success.

§Example
use karyon_jsonrpc::{client::ClientBuilder, net::TcpConfig};
  
async {
    let tcp_config = TcpConfig::default();
    let client = ClientBuilder::new("ws://127.0.0.1:3000")
        .expect("Create a new client builder")
        .tcp_config(tcp_config)
        .expect("Add tcp config")
        .set_timeout(5000)
        .build().await
        .expect("Build a new client");
};

Auto Trait Implementations§

§

impl<C> Freeze for ClientBuilder<C>
where C: Freeze,

§

impl<C> RefUnwindSafe for ClientBuilder<C>
where C: RefUnwindSafe,

§

impl<C> Send for ClientBuilder<C>
where C: Send,

§

impl<C> Sync for ClientBuilder<C>
where C: Sync,

§

impl<C> Unpin for ClientBuilder<C>
where C: Unpin,

§

impl<C> UnwindSafe for ClientBuilder<C>
where C: UnwindSafe,

Blanket Implementations§

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> 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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

Source§

type Output = T

Should always be Self
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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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