pub struct ServerBuilder<B = Identity, L = ()> { /* private fields */ }
Expand description

Builder to configure and create a JSON-RPC server

Implementations§

source§

impl Builder

source

pub fn new() -> Self

Create a default server builder.

source§

impl<B, L> Builder<B, L>

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: u32) -> Self

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

source

pub fn set_batch_request_config(self, cfg: BatchRequestConfig) -> Self

Configure how batch requests shall be handled by the server.

Default: batch requests are allowed and can be arbitrary big but the maximum payload size is limited.

source

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

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

source

pub fn set_logger<T: Logger>(self, logger: T) -> Builder<B, T>

Add a logger to the builder Logger.

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

use jsonrpsee_server::logger::{Logger, HttpRequest, MethodKind, Params, TransportProtocol, SuccessOrError};
use jsonrpsee_server::ServerBuilder;

#[derive(Clone)]
struct MyLogger;

impl Logger for MyLogger {
    type Instant = Instant;

    fn on_connect(&self, remote_addr: SocketAddr, request: &HttpRequest, transport: TransportProtocol) {
         println!("[MyLogger::on_call] remote_addr: {:?}, headers: {:?}, transport: {}", remote_addr, request, transport);
    }

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

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

    fn on_result(&self, method_name: &str, success_or_error: SuccessOrError, started_at: Self::Instant, transport: TransportProtocol) {
         println!("[MyLogger::on_result] '{}', worked? {}, time elapsed {:?}, transport: {}", method_name, success_or_error.is_success(), started_at.elapsed(), transport);
    }

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

    fn on_disconnect(&self, remote_addr: SocketAddr, transport: TransportProtocol) {
         println!("[MyLogger::on_disconnect] remote_addr: {:?}, transport: {}", remote_addr, transport);
    }
}

let builder = ServerBuilder::new().set_logger(MyLogger);
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_server::ServerBuilder;

// Set the ping interval to 10 seconds.
let builder = ServerBuilder::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_server::{ServerBuilder, RandomStringIdProvider, IdProvider};

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

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

pub fn set_middleware<T>( self, service_builder: ServiceBuilder<T> ) -> Builder<T, L>

Configure a custom tower::ServiceBuilder middleware for composing layers to be applied to the RPC service.

Default: No tower layers are applied to the RPC service.

Examples

use std::time::Duration;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let builder = tower::ServiceBuilder::new().timeout(Duration::from_secs(2));

    let server = jsonrpsee_server::ServerBuilder::new()
        .set_middleware(builder)
        .build("127.0.0.1:0".parse::<SocketAddr>().unwrap())
        .await
        .unwrap();
}
source

pub fn http_only(self) -> Self

Configure the server to only serve JSON-RPC HTTP requests.

Default: both http and ws are enabled.

source

pub fn ws_only(self) -> Self

Configure the server to only serve JSON-RPC WebSocket requests.

That implies that server just denies HTTP requests which isn’t a WebSocket upgrade request

Default: both http and ws are enabled.

source

pub fn set_message_buffer_capacity(self, c: u32) -> Self

The server enforces backpressure which means that n messages can be buffered and if the client can’t keep with up the server.

This capacity is applied per connection and applies globally on the connection which implies all JSON-RPC messages.

For example if a subscription produces plenty of new items and the client can’t keep up then no new messages are handled.

If this limit is exceeded then the server will “back-off” and only accept new messages once the client reads pending messages.

Panics

Panics if the buffer capacity is 0.

source

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

Set maximum length for logging calls and responses.

Logs bigger than this limit will be truncated.

source

pub async fn build( self, addrs: impl ToSocketAddrs ) -> Result<Server<B, L>, 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_server::ServerBuilder::default().build(occupied_addr).await.is_err());
  assert!(jsonrpsee_server::ServerBuilder::default().build(addrs).await.is_ok());
}
source

pub fn build_from_tcp( self, listener: impl Into<StdTcpListener> ) -> Result<Server<B, L>, Error>

Finalizes the configuration of the server with customized TCP settings on the socket.

use jsonrpsee_server::ServerBuilder;
use socket2::{Domain, Socket, Type};
use std::time::Duration;

#[tokio::main]
async fn main() {
  let addr = "127.0.0.1:0".parse().unwrap();
  let domain = Domain::for_address(addr);
  let socket = Socket::new(domain, Type::STREAM, None).unwrap();
  socket.set_nonblocking(true).unwrap();

  let address = addr.into();
  socket.bind(&address).unwrap();

  socket.listen(4096).unwrap();

  let server = ServerBuilder::new().build_from_tcp(socket).unwrap();
}

Trait Implementations§

source§

impl<B: Debug, L: Debug> Debug for Builder<B, L>

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<B = Identity, L = ()> !RefUnwindSafe for Builder<B, L>

§

impl<B, L> Send for Builder<B, L>where B: Send, L: Send,

§

impl<B, L> Sync for Builder<B, L>where B: Sync, L: Sync,

§

impl<B, L> Unpin for Builder<B, L>where B: Unpin, L: Unpin,

§

impl<B = Identity, L = ()> !UnwindSafe for Builder<B, L>

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

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

§

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