Unverified Commit 21e557d2 authored by Alexandru Vasile's avatar Alexandru Vasile Committed by GitHub
Browse files

Refactor `Middleware` to `Logger` (#845)



* Rename Middleware to Metrics
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Change documentation to reflect the `Metrics` trait
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Middleware name refactoring
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Http middleware renaming
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Rename examples
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Update http-server/src/server.rs
Co-authored-by: James Wilson's avatarJames Wilson <james@jsdw.me>

* http: Use `request` instead of `HeaderMap` for logging
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Rename `Metrics` -> `Logger`
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Fix cargo clippy
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Fix examples
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Fix tests
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Fix cargo fmt
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>

* Fix hyper dependency
Signed-off-by: default avatarAlexandru Vasile <alexandru.vasile@parity.io>
Co-authored-by: James Wilson's avatarJames Wilson <james@jsdw.me>
parent 9f88eb81
Pipeline #206337 passed with stages
in 4 minutes and 45 seconds
...@@ -32,7 +32,7 @@ Support `WebSocket` and `HTTP` transports for both client and server. ...@@ -32,7 +32,7 @@ Support `WebSocket` and `HTTP` transports for both client and server.
- [WebSocket](./examples/examples/ws.rs) - [WebSocket](./examples/examples/ws.rs)
- [WebSocket pubsub](./examples/examples/ws_pubsub_broadcast.rs) - [WebSocket pubsub](./examples/examples/ws_pubsub_broadcast.rs)
- [API generation with proc macro](./examples/examples/proc_macro.rs) - [API generation with proc macro](./examples/examples/proc_macro.rs)
- [Middleware](./examples/examples/multi_middleware.rs) - [Logger](./examples/examples/multi_logger.rs)
- [CORS server](./examples/examples/cors_server.rs) - [CORS server](./examples/examples/cors_server.rs)
- [Core client](./examples/examples/core_client.rs) - [Core client](./examples/examples/core_client.rs)
......
...@@ -51,6 +51,7 @@ server = [ ...@@ -51,6 +51,7 @@ server = [
"lazy_static", "lazy_static",
"unicase", "unicase",
"http", "http",
"hyper",
] ]
client = ["futures-util/sink", "futures-channel/sink", "futures-channel/std"] client = ["futures-util/sink", "futures-channel/sink", "futures-channel/std"]
async-client = [ async-client = [
......
...@@ -46,7 +46,7 @@ cfg_http_helpers! { ...@@ -46,7 +46,7 @@ cfg_http_helpers! {
cfg_server! { cfg_server! {
pub mod id_providers; pub mod id_providers;
pub mod server; pub mod server;
pub mod middleware; pub mod logger;
} }
cfg_client! { cfg_client! {
......
...@@ -24,11 +24,13 @@ ...@@ -24,11 +24,13 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
//! Middleware for `jsonrpsee` servers. //! Logger for `jsonrpsee` servers.
use std::net::SocketAddr; use std::net::SocketAddr;
pub use http::request::Request;
pub use http::HeaderMap as Headers; pub use http::HeaderMap as Headers;
pub use hyper::Body;
pub use jsonrpsee_types::Params; pub use jsonrpsee_types::Params;
/// The type JSON-RPC v2 call, it can be a subscription, method call or unknown. /// The type JSON-RPC v2 call, it can be a subscription, method call or unknown.
...@@ -57,18 +59,18 @@ impl std::fmt::Display for MethodKind { ...@@ -57,18 +59,18 @@ impl std::fmt::Display for MethodKind {
} }
} }
/// Defines a middleware specifically for HTTP requests with callbacks during the RPC request life-cycle. /// Defines a logger specifically for HTTP requests with callbacks during the RPC request life-cycle.
/// The primary use case for this is to collect timings for a larger metrics collection solution. /// The primary use case for this is to collect timings for a larger metrics collection solution.
/// ///
/// See [`HttpServerBuilder::set_middleware`](../../jsonrpsee_http_server/struct.HttpServerBuilder.html#method.set_middleware) method /// See [`HttpServerBuilder::set_logger`](../../jsonrpsee_http_server/struct.HttpServerBuilder.html#method.set_logger) method
/// for examples. /// for examples.
pub trait HttpMiddleware: Send + Sync + Clone + 'static { pub trait HttpLogger: Send + Sync + Clone + 'static {
/// Intended to carry timestamp of a request, for example `std::time::Instant`. How the middleware /// Intended to carry timestamp of a request, for example `std::time::Instant`. How the trait
/// measures time, if at all, is entirely up to the implementation. /// measures time, if at all, is entirely up to the implementation.
type Instant: std::fmt::Debug + Send + Sync + Copy; type Instant: std::fmt::Debug + Send + Sync + Copy;
/// Called when a new JSON-RPC request comes to the server. /// Called when a new JSON-RPC request comes to the server.
fn on_request(&self, remote_addr: SocketAddr, headers: &Headers) -> Self::Instant; fn on_request(&self, remote_addr: SocketAddr, request: &Request<Body>) -> Self::Instant;
/// Called on each JSON-RPC method call, batch requests will trigger `on_call` multiple times. /// Called on each JSON-RPC method call, batch requests will trigger `on_call` multiple times.
fn on_call(&self, method_name: &str, params: Params, kind: MethodKind); fn on_call(&self, method_name: &str, params: Params, kind: MethodKind);
...@@ -80,13 +82,13 @@ pub trait HttpMiddleware: Send + Sync + Clone + 'static { ...@@ -80,13 +82,13 @@ pub trait HttpMiddleware: Send + Sync + Clone + 'static {
fn on_response(&self, result: &str, _started_at: Self::Instant); fn on_response(&self, result: &str, _started_at: Self::Instant);
} }
/// Defines a middleware specifically for WebSocket connections with callbacks during the RPC request life-cycle. /// Defines a logger specifically for WebSocket connections with callbacks during the RPC request life-cycle.
/// The primary use case for this is to collect timings for a larger metrics collection solution. /// The primary use case for this is to collect timings for a larger metrics collection solution.
/// ///
/// See the [`WsServerBuilder::set_middleware`](../../jsonrpsee_ws_server/struct.WsServerBuilder.html#method.set_middleware) /// See the [`WsServerBuilder::set_logger`](../../jsonrpsee_ws_server/struct.WsServerBuilder.html#method.set_logger)
/// for examples. /// for examples.
pub trait WsMiddleware: Send + Sync + Clone + 'static { pub trait WsLogger: Send + Sync + Clone + 'static {
/// Intended to carry timestamp of a request, for example `std::time::Instant`. How the middleware /// Intended to carry timestamp of a request, for example `std::time::Instant`. How the trait
/// measures time, if at all, is entirely up to the implementation. /// measures time, if at all, is entirely up to the implementation.
type Instant: std::fmt::Debug + Send + Sync + Copy; type Instant: std::fmt::Debug + Send + Sync + Copy;
...@@ -109,10 +111,10 @@ pub trait WsMiddleware: Send + Sync + Clone + 'static { ...@@ -109,10 +111,10 @@ pub trait WsMiddleware: Send + Sync + Clone + 'static {
fn on_disconnect(&self, remote_addr: std::net::SocketAddr); fn on_disconnect(&self, remote_addr: std::net::SocketAddr);
} }
impl HttpMiddleware for () { impl HttpLogger for () {
type Instant = (); type Instant = ();
fn on_request(&self, _: std::net::SocketAddr, _: &Headers) -> Self::Instant {} fn on_request(&self, _: std::net::SocketAddr, _: &Request<Body>) -> Self::Instant {}
fn on_call(&self, _: &str, _: Params, _: MethodKind) {} fn on_call(&self, _: &str, _: Params, _: MethodKind) {}
...@@ -121,7 +123,7 @@ impl HttpMiddleware for () { ...@@ -121,7 +123,7 @@ impl HttpMiddleware for () {
fn on_response(&self, _: &str, _: Self::Instant) {} fn on_response(&self, _: &str, _: Self::Instant) {}
} }
impl WsMiddleware for () { impl WsLogger for () {
type Instant = (); type Instant = ();
fn on_connect(&self, _: std::net::SocketAddr, _: &Headers) {} fn on_connect(&self, _: std::net::SocketAddr, _: &Headers) {}
...@@ -137,10 +139,10 @@ impl WsMiddleware for () { ...@@ -137,10 +139,10 @@ impl WsMiddleware for () {
fn on_disconnect(&self, _: std::net::SocketAddr) {} fn on_disconnect(&self, _: std::net::SocketAddr) {}
} }
impl<A, B> WsMiddleware for (A, B) impl<A, B> WsLogger for (A, B)
where where
A: WsMiddleware, A: WsLogger,
B: WsMiddleware, B: WsLogger,
{ {
type Instant = (A::Instant, B::Instant); type Instant = (A::Instant, B::Instant);
...@@ -172,15 +174,15 @@ where ...@@ -172,15 +174,15 @@ where
} }
} }
impl<A, B> HttpMiddleware for (A, B) impl<A, B> HttpLogger for (A, B)
where where
A: HttpMiddleware, A: HttpLogger,
B: HttpMiddleware, B: HttpLogger,
{ {
type Instant = (A::Instant, B::Instant); type Instant = (A::Instant, B::Instant);
fn on_request(&self, remote_addr: std::net::SocketAddr, headers: &Headers) -> Self::Instant { fn on_request(&self, remote_addr: std::net::SocketAddr, request: &Request<Body>) -> Self::Instant {
(self.0.on_request(remote_addr, headers), self.1.on_request(remote_addr, headers)) (self.0.on_request(remote_addr, request), self.1.on_request(remote_addr, request))
} }
fn on_call(&self, method_name: &str, params: Params, kind: MethodKind) { fn on_call(&self, method_name: &str, params: Params, kind: MethodKind) {
......
...@@ -432,7 +432,7 @@ impl Methods { ...@@ -432,7 +432,7 @@ impl Methods {
let conn_state = ConnState { conn_id: 0, close_notify, id_provider: &RandomIntegerIdProvider }; let conn_state = ConnState { conn_id: 0, close_notify, id_provider: &RandomIntegerIdProvider };
let res = (cb)(id, params, sink.clone(), conn_state, None).await; let res = (cb)(id, params, sink.clone(), conn_state, None).await;
// This message is not used because it's used for middleware so we discard in other to // This message is not used because it's used for metrics so we discard in other to
// not read once this is used for subscriptions. // not read once this is used for subscriptions.
// //
// The same information is part of `res` above. // The same information is part of `res` above.
...@@ -1045,9 +1045,9 @@ impl SubscriptionSink { ...@@ -1045,9 +1045,9 @@ impl SubscriptionSink {
fn answer_subscription(&self, response: MethodResponse, subscribe_call: oneshot::Sender<MethodResponse>) -> bool { fn answer_subscription(&self, response: MethodResponse, subscribe_call: oneshot::Sender<MethodResponse>) -> bool {
let ws_send = self.inner.send_raw(response.result.clone()).is_ok(); let ws_send = self.inner.send_raw(response.result.clone()).is_ok();
let middleware_call = subscribe_call.send(response).is_ok(); let logger_call = subscribe_call.send(response).is_ok();
ws_send && middleware_call ws_send && logger_call
} }
fn build_message<T: Serialize>(&self, result: &T) -> Result<String, serde_json::Error> { fn build_message<T: Serialize>(&self, result: &T) -> Result<String, serde_json::Error> {
......
...@@ -28,31 +28,31 @@ use std::net::SocketAddr; ...@@ -28,31 +28,31 @@ use std::net::SocketAddr;
use std::time::Instant; use std::time::Instant;
use jsonrpsee::core::client::ClientT; use jsonrpsee::core::client::ClientT;
use jsonrpsee::core::middleware::{self, Headers, MethodKind, Params}; use jsonrpsee::core::logger::{self, Body, MethodKind, Params, Request};
use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_client::HttpClientBuilder;
use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule};
#[derive(Clone)] #[derive(Clone)]
struct Timings; struct Timings;
impl middleware::HttpMiddleware for Timings { impl logger::HttpLogger for Timings {
type Instant = Instant; type Instant = Instant;
fn on_request(&self, remote_addr: SocketAddr, headers: &Headers) -> Self::Instant { fn on_request(&self, remote_addr: SocketAddr, request: &Request<Body>) -> Self::Instant {
println!("[Middleware::on_request] remote_addr {}, headers: {:?}", remote_addr, headers); println!("[Logger::on_request] remote_addr {}, request: {:?}", remote_addr, request);
Instant::now() Instant::now()
} }
fn on_call(&self, name: &str, params: Params, kind: MethodKind) { fn on_call(&self, name: &str, params: Params, kind: MethodKind) {
println!("[Middleware::on_call] method: '{}', params: {:?}, kind: {}", name, params, kind); println!("[Logger::on_call] method: '{}', params: {:?}, kind: {}", name, params, kind);
} }
fn on_result(&self, name: &str, succeess: bool, started_at: Self::Instant) { fn on_result(&self, name: &str, succeess: bool, started_at: Self::Instant) {
println!("[Middleware::on_result] '{}', worked? {}, time elapsed {:?}", name, succeess, started_at.elapsed()); println!("[Logger::on_result] '{}', worked? {}, time elapsed {:?}", name, succeess, started_at.elapsed());
} }
fn on_response(&self, result: &str, started_at: Self::Instant) { fn on_response(&self, result: &str, started_at: Self::Instant) {
println!("[Middleware::on_response] result: {}, time elapsed {:?}", result, started_at.elapsed()); println!("[Logger::on_response] result: {}, time elapsed {:?}", result, started_at.elapsed());
} }
} }
...@@ -76,7 +76,7 @@ async fn main() -> anyhow::Result<()> { ...@@ -76,7 +76,7 @@ async fn main() -> anyhow::Result<()> {
} }
async fn run_server() -> anyhow::Result<(SocketAddr, HttpServerHandle)> { async fn run_server() -> anyhow::Result<(SocketAddr, HttpServerHandle)> {
let server = HttpServerBuilder::new().set_middleware(Timings).build("127.0.0.1:0").await?; let server = HttpServerBuilder::new().set_logger(Timings).build("127.0.0.1:0").await?;
let mut module = RpcModule::new(()); let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| Ok("lo"))?; module.register_method("say_hello", |_, _| Ok("lo"))?;
let addr = server.local_addr()?; let addr = server.local_addr()?;
......
...@@ -28,39 +28,39 @@ use std::net::SocketAddr; ...@@ -28,39 +28,39 @@ use std::net::SocketAddr;
use std::time::Instant; use std::time::Instant;
use jsonrpsee::core::client::ClientT; use jsonrpsee::core::client::ClientT;
use jsonrpsee::core::middleware::{self, Headers, MethodKind, Params}; use jsonrpsee::core::logger::{self, Headers, MethodKind, Params};
use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_client::WsClientBuilder;
use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder};
#[derive(Clone)] #[derive(Clone)]
struct Timings; struct Timings;
impl middleware::WsMiddleware for Timings { impl logger::WsLogger for Timings {
type Instant = Instant; type Instant = Instant;
fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) { fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) {
println!("[Middleware::on_connect] remote_addr {}, headers: {:?}", remote_addr, headers); println!("[Logger::on_connect] remote_addr {}, headers: {:?}", remote_addr, headers);
} }
fn on_request(&self) -> Self::Instant { fn on_request(&self) -> Self::Instant {
println!("[Middleware::on_request]"); println!("[Logger::on_request]");
Instant::now() Instant::now()
} }
fn on_call(&self, name: &str, params: Params, kind: MethodKind) { fn on_call(&self, name: &str, params: Params, kind: MethodKind) {
println!("[Middleware::on_call] method: '{}', params: {:?}, kind: {}", name, params, kind); println!("[Logger::on_call] method: '{}', params: {:?}, kind: {}", name, params, kind);
} }
fn on_result(&self, name: &str, succeess: bool, started_at: Self::Instant) { fn on_result(&self, name: &str, succeess: bool, started_at: Self::Instant) {
println!("[Middleware::on_result] '{}', worked? {}, time elapsed {:?}", name, succeess, started_at.elapsed()); println!("[Logger::on_result] '{}', worked? {}, time elapsed {:?}", name, succeess, started_at.elapsed());
} }
fn on_response(&self, result: &str, started_at: Self::Instant) { fn on_response(&self, result: &str, started_at: Self::Instant) {
println!("[Middleware::on_response] result: {}, time elapsed {:?}", result, started_at.elapsed()); println!("[Logger::on_response] result: {}, time elapsed {:?}", result, started_at.elapsed());
} }
fn on_disconnect(&self, remote_addr: SocketAddr) { fn on_disconnect(&self, remote_addr: SocketAddr) {
println!("[Middleware::on_disconnect] remote_addr: {}", remote_addr); println!("[Logger::on_disconnect] remote_addr: {}", remote_addr);
} }
} }
...@@ -84,7 +84,7 @@ async fn main() -> anyhow::Result<()> { ...@@ -84,7 +84,7 @@ async fn main() -> anyhow::Result<()> {
} }
async fn run_server() -> anyhow::Result<SocketAddr> { async fn run_server() -> anyhow::Result<SocketAddr> {
let server = WsServerBuilder::new().set_middleware(Timings).build("127.0.0.1:0").await?; let server = WsServerBuilder::new().set_logger(Timings).build("127.0.0.1:0").await?;
let mut module = RpcModule::new(()); let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| Ok("lo"))?; module.register_method("say_hello", |_, _| Ok("lo"))?;
let addr = server.local_addr()?; let addr = server.local_addr()?;
......
...@@ -24,24 +24,24 @@ ...@@ -24,24 +24,24 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
//! Example showing how to add multiple middlewares to the same server. //! Example showing how to add multiple loggers to the same server.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::process::Command; use std::process::Command;
use std::time::Instant; use std::time::Instant;
use jsonrpsee::core::middleware::MethodKind; use jsonrpsee::core::logger::MethodKind;
use jsonrpsee::core::{client::ClientT, middleware, middleware::Headers}; use jsonrpsee::core::{client::ClientT, logger, logger::Headers};
use jsonrpsee::rpc_params; use jsonrpsee::rpc_params;
use jsonrpsee::types::Params; use jsonrpsee::types::Params;
use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_client::WsClientBuilder;
use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder};
/// Example middleware to measure call execution time. /// Example logger to measure call execution time.
#[derive(Clone)] #[derive(Clone)]
struct Timings; struct Timings;
impl middleware::WsMiddleware for Timings { impl logger::WsLogger for Timings {
type Instant = Instant; type Instant = Instant;
fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) { fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) {
...@@ -69,7 +69,7 @@ impl middleware::WsMiddleware for Timings { ...@@ -69,7 +69,7 @@ impl middleware::WsMiddleware for Timings {
} }
} }
/// Example middleware to keep a watch on the number of total threads started in the system. /// Example logger to keep a watch on the number of total threads started in the system.
#[derive(Clone)] #[derive(Clone)]
struct ThreadWatcher; struct ThreadWatcher;
...@@ -88,7 +88,7 @@ impl ThreadWatcher { ...@@ -88,7 +88,7 @@ impl ThreadWatcher {
} }
} }
impl middleware::WsMiddleware for ThreadWatcher { impl logger::WsLogger for ThreadWatcher {
type Instant = isize; type Instant = isize;
fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) { fn on_connect(&self, remote_addr: SocketAddr, headers: &Headers) {
...@@ -142,7 +142,7 @@ async fn main() -> anyhow::Result<()> { ...@@ -142,7 +142,7 @@ async fn main() -> anyhow::Result<()> {
} }
async fn run_server() -> anyhow::Result<SocketAddr> { async fn run_server() -> anyhow::Result<SocketAddr> {
let server = WsServerBuilder::new().set_middleware((Timings, ThreadWatcher)).build("127.0.0.1:0").await?; let server = WsServerBuilder::new().set_logger((Timings, ThreadWatcher)).build("127.0.0.1:0").await?;
let mut module = RpcModule::new(()); let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| Ok("lo"))?; module.register_method("say_hello", |_, _| Ok("lo"))?;
module.register_method("thready", |params, _| { module.register_method("thready", |params, _| {
......
...@@ -41,7 +41,7 @@ use hyper::service::{make_service_fn, service_fn}; ...@@ -41,7 +41,7 @@ use hyper::service::{make_service_fn, service_fn};
use hyper::{Error as HyperError, Method}; use hyper::{Error as HyperError, Method};
use jsonrpsee_core::error::{Error, GenericTransportError}; use jsonrpsee_core::error::{Error, GenericTransportError};
use jsonrpsee_core::http_helpers::{self, read_body}; use jsonrpsee_core::http_helpers::{self, read_body};
use jsonrpsee_core::middleware::{self, HttpMiddleware as Middleware}; use jsonrpsee_core::logger::{self, HttpLogger as Logger};
use jsonrpsee_core::server::access_control::AccessControl; use jsonrpsee_core::server::access_control::AccessControl;
use jsonrpsee_core::server::helpers::{prepare_error, MethodResponse}; use jsonrpsee_core::server::helpers::{prepare_error, MethodResponse};
use jsonrpsee_core::server::helpers::{BatchResponse, BatchResponseBuilder}; use jsonrpsee_core::server::helpers::{BatchResponse, BatchResponseBuilder};
...@@ -59,7 +59,7 @@ type Notif<'a> = Notification<'a, Option<&'a RawValue>>; ...@@ -59,7 +59,7 @@ type Notif<'a> = Notification<'a, Option<&'a RawValue>>;
/// Builder to create JSON-RPC HTTP server. /// Builder to create JSON-RPC HTTP server.
#[derive(Debug)] #[derive(Debug)]
pub struct Builder<M = ()> { pub struct Builder<L = ()> {
/// Access control based on HTTP headers. /// Access control based on HTTP headers.
access_control: AccessControl, access_control: AccessControl,
resources: Resources, resources: Resources,
...@@ -68,7 +68,7 @@ pub struct Builder<M = ()> { ...@@ -68,7 +68,7 @@ pub struct Builder<M = ()> {
batch_requests_supported: bool, batch_requests_supported: bool,
/// Custom tokio runtime to run the server on. /// Custom tokio runtime to run the server on.
tokio_runtime: Option<tokio::runtime::Handle>, tokio_runtime: Option<tokio::runtime::Handle>,
middleware: M, logger: L,
max_log_length: u32, max_log_length: u32,
health_api: Option<HealthApi>, health_api: Option<HealthApi>,
} }
...@@ -82,7 +82,7 @@ impl Default for Builder { ...@@ -82,7 +82,7 @@ impl Default for Builder {
batch_requests_supported: true, batch_requests_supported: true,
resources: Resources::default(), resources: Resources::default(),
tokio_runtime: None, tokio_runtime: None,
middleware: (), logger: (),
max_log_length: 4096, max_log_length: 4096,
health_api: None, health_api: None,
} }
...@@ -96,24 +96,25 @@ impl Builder { ...@@ -96,24 +96,25 @@ impl Builder {
} }
} }
impl<M> Builder<M> { impl<L> Builder<L> {
/// Add a middleware to the builder [`Middleware`](../jsonrpsee_core/middleware/trait.Middleware.html). /// Add a logger to the builder [`Logger`](../jsonrpsee_core/logger/trait.Logger.html).
/// ///
/// ``` /// ```
/// use std::{time::Instant, net::SocketAddr}; /// use std::{time::Instant, net::SocketAddr};
/// use hyper::Request;
/// ///
/// use jsonrpsee_core::middleware::{HttpMiddleware, Headers, MethodKind, Params}; /// use jsonrpsee_core::logger::{HttpLogger, Headers, MethodKind, Params};
/// use jsonrpsee_http_server::HttpServerBuilder; /// use jsonrpsee_http_server::HttpServerBuilder;
/// ///
/// #[derive(Clone)] /// #[derive(Clone)]
/// struct MyMiddleware; /// struct MyLogger;
/// ///
/// impl HttpMiddleware for MyMiddleware { /// impl HttpLogger for MyLogger {
/// type Instant = Instant; /// type Instant = Instant;
/// ///
/// // Called once the HTTP request is received, it may be a single JSON-RPC call /// // Called once the HTTP request is received, it may be a single JSON-RPC call
/// // or batch. /// // or batch.
/// fn on_request(&self, _remote_addr: SocketAddr, _headers: &Headers) -> Instant { /// fn on_request(&self, _remote_addr: SocketAddr, _request: &Request<hyper::Body>) -> Instant {
/// Instant::now() /// Instant::now()
/// } /// }
/// ///
...@@ -135,9 +136,9 @@ impl<M> Builder<M> { ...@@ -135,9 +136,9 @@ impl<M> Builder<M> {
/// } /// }
/// } /// }
/// ///
/// let builder = HttpServerBuilder::new().set_middleware(MyMiddleware); /// let builder = HttpServerBuilder::new().set_logger(MyLogger);
/// ``` /// ```
pub fn set_middleware<T: Middleware>(self, middleware: T) -> Builder<T> { pub fn set_logger<T: Logger>(self, logger: T) -> Builder<T> {
Builder { Builder {
access_control: self.access_control, access_control: self.access_control,
max_request_body_size: self.max_request_body_size, max_request_body_size: self.max_request_body_size,
...@@ -145,7 +146,7 @@ impl<M> Builder<M> { ...@@ -145,7 +146,7 @@ impl<M> Builder<M> {