Struct WsServerBuilder

Source
pub struct WsServerBuilder<M = ()> { /* private fields */ }
Expand description

Builder to configure and create a JSON-RPC Websocket server

Implementations§

Source§

impl Builder

Source

pub fn new() -> Self

Create a default server builder.

Source§

impl<M> Builder<M>

Source

pub fn max_request_body_size(self, size: u32) -> Self

Set the maximum size of a request body in bytes. Default is 10 MiB.

Source

pub fn max_response_body_size(self, size: u32) -> Self

Set the maximum size of a response body in bytes. Default is 10 MiB.

Source

pub fn max_connections(self, max: u64) -> Self

Set the maximum number of connections allowed. Default is 100.

Source

pub fn batch_requests_supported(self, supported: bool) -> Self

Enables or disables support of batch requests. By default, support is enabled.

Source

pub fn max_subscriptions_per_connection(self, max: u32) -> Self

Set the maximum number of connections allowed. Default is 1024.

Source

pub fn register_resource( self, label: &'static str, capacity: u16, default: u16, ) -> Result<Self, Error>

Register a new resource kind. Errors if label is already registered, or if the number of registered resources on this server instance would exceed 8.

See the module documentation for resurce_limiting for details.

Source

pub fn set_middleware<T: Middleware>(self, middleware: T) -> Builder<T>

Add a middleware to the builder Middleware.

use std::{time::Instant, net::SocketAddr};

use jsonrpsee_core::middleware::{WsMiddleware, Headers, MethodKind, Params};
use jsonrpsee_ws_server::WsServerBuilder;

#[derive(Clone)]
struct MyMiddleware;

impl WsMiddleware for MyMiddleware {
    type Instant = Instant;

    fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) {
         println!("[MyMiddleware::on_call] remote_addr: {}, headers: {:?}", remote_addr, headers);
    }

    fn on_request(&self) -> Self::Instant {
         Instant::now()
    }

    fn on_call(&self, method_name: &str, params: Params, kind: MethodKind) {
         println!("[MyMiddleware::on_call] method: '{}' params: {:?}, kind: {:?}", method_name, params, kind);
    }

    fn on_result(&self, method_name: &str, success: bool, started_at: Self::Instant) {
         println!("[MyMiddleware::on_result] '{}', worked? {}, time elapsed {:?}", method_name, success, started_at.elapsed());
    }

    fn on_response(&self, result: &str, started_at: Self::Instant) {
         println!("[MyMiddleware::on_response] result: {}, time elapsed {:?}", result, started_at.elapsed());
    }

    fn on_disconnect(&self, remote_addr: SocketAddr) {
         println!("[MyMiddleware::on_disconnect] remote_addr: {}", remote_addr);
    }
}

let builder = WsServerBuilder::new().set_middleware(MyMiddleware);
Source

pub fn custom_tokio_runtime(self, rt: Handle) -> Self

Configure a custom tokio::runtime::Handle to run the server on.

Default: tokio::spawn

Source

pub fn ping_interval(self, interval: Duration) -> Self

Configure the interval at which pings are submitted.

This option is used to keep the connection alive, and is just submitting Ping frames, without making any assumptions about when a Pong frame should be received.

Default: 60 seconds.

§Examples
use std::time::Duration;
use jsonrpsee_ws_server::WsServerBuilder;

// Set the ping interval to 10 seconds.
let builder = WsServerBuilder::default().ping_interval(Duration::from_secs(10));
Source

pub fn set_id_provider<I: IdProvider + 'static>(self, id_provider: I) -> Self

Configure custom subscription ID provider for the server to use to when getting new subscription calls.

You may choose static dispatch or dynamic dispatch because IdProvider is implemented for Box<T>.

Default: RandomIntegerIdProvider.

§Examples
use jsonrpsee_ws_server::{WsServerBuilder, RandomStringIdProvider, IdProvider};

// static dispatch
let builder1 = WsServerBuilder::default().set_id_provider(RandomStringIdProvider::new(16));

// or dynamic dispatch
let builder2 = WsServerBuilder::default().set_id_provider(Box::new(RandomStringIdProvider::new(16)));
Source

pub fn set_access_control(self, acl: AccessControl) -> Self

Sets access control settings.

Source

pub async fn build(self, addrs: impl ToSocketAddrs) -> Result<Server<M>, Error>

Finalize the configuration of the server. Consumes the Builder.

#[tokio::main]
async fn main() {
  let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
  let occupied_addr = listener.local_addr().unwrap();
  let addrs: &[std::net::SocketAddr] = &[
      occupied_addr,
      "127.0.0.1:0".parse().unwrap(),
  ];
  assert!(jsonrpsee_ws_server::WsServerBuilder::default().build(occupied_addr).await.is_err());
  assert!(jsonrpsee_ws_server::WsServerBuilder::default().build(addrs).await.is_ok());
}

Trait Implementations§

Source§

impl<M: Debug> Debug for Builder<M>

Source§

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

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

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<M> Freeze for Builder<M>
where M: Freeze,

§

impl<M = ()> !RefUnwindSafe for Builder<M>

§

impl<M> Send for Builder<M>
where M: Send,

§

impl<M> Sync for Builder<M>
where M: Sync,

§

impl<M> Unpin for Builder<M>
where M: Unpin,

§

impl<M = ()> !UnwindSafe for Builder<M>

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.

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> 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> 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.
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
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