Struct HttpServerBuilder

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

Builder to create JSON-RPC HTTP server.

Implementations§

Source§

impl Builder

Source

pub fn new() -> Self

Create a default server builder.

Source§

impl<M> Builder<M>

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::{HttpMiddleware, Headers, MethodKind, Params};
use jsonrpsee_http_server::HttpServerBuilder;

#[derive(Clone)]
struct MyMiddleware;

impl HttpMiddleware for MyMiddleware {
    type Instant = Instant;

    // Called once the HTTP request is received, it may be a single JSON-RPC call
    // or batch.
    fn on_request(&self, _remote_addr: SocketAddr, _headers: &Headers) -> Instant {
        Instant::now()
    }

    // Called once a single JSON-RPC method call is processed, it may be called multiple times
    // on batches.
    fn on_call(&self, method_name: &str, params: Params, kind: MethodKind) {
        println!("Call to method: '{}' params: {:?}, kind: {}", method_name, params, kind);
    }

    // Called once a single JSON-RPC call is completed, it may be called multiple times
    // on batches.
    fn on_result(&self, method_name: &str, success: bool, started_at: Instant) {
        println!("Call to '{}' took {:?}", method_name, started_at.elapsed());
    }

    // Called the entire JSON-RPC is completed, called on once for both single calls or batches.
    fn on_response(&self, result: &str, started_at: Instant) {
        println!("complete JSON-RPC response: {}, took: {:?}", result, started_at.elapsed());
    }
}

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

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

Sets the maximum size of a request body in bytes (default is 10 MiB).

Source

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

Sets the maximum size of a response body in bytes (default is 10 MiB).

Source

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

Sets access control settings.

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 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 resource_limiting for details.

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 health_api( self, path: impl Into<String>, method: impl Into<String>, ) -> Result<Self, Error>

Enable health endpoint. Allows you to expose one of the methods under GET / The method will be invoked with no parameters. Error returned from the method will be converted to status 500 response. Expects a tuple with (, ).

Fails if the path is missing /.

Source

pub fn build_from_hyper( self, listener: Builder<AddrIncoming>, local_addr: SocketAddr, ) -> Result<Server<M>, Error>

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

use jsonrpsee_http_server::HttpServerBuilder;
use socket2::{Domain, Socket, Type};
use std::net::TcpListener;

#[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 listener: TcpListener = socket.into();
  let local_addr = listener.local_addr().ok();

  // hyper does some settings on the provided socket, ensure that nothing breaks our "expected settings".

  let listener = hyper::Server::from_tcp(listener)
    .unwrap()
    .tcp_sleep_on_accept_errors(true)
    .tcp_keepalive(None)
    .tcp_nodelay(true);

  let server = HttpServerBuilder::new().build_from_hyper(listener, addr).unwrap();
}
Source

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

Finalizes the configuration of the server with customized TCP settings on the socket. Note, that hyper might overwrite some of the TCP settings on the socket if you want full-control of socket settings use Builder::build_from_hyper instead.

use jsonrpsee_http_server::HttpServerBuilder;
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 = HttpServerBuilder::new().build_from_tcp(socket).unwrap();
}
Source

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

Finalizes the configuration of the server.

#[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_http_server::HttpServerBuilder::default().build(occupied_addr).await.is_err());
  assert!(jsonrpsee_http_server::HttpServerBuilder::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, 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