Skip to content

Commit

Permalink
chore(deps): update to hyper 1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Apr 4, 2024
1 parent 0875a83 commit 6ede090
Show file tree
Hide file tree
Showing 8 changed files with 183 additions and 137 deletions.
153 changes: 105 additions & 48 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ vergen = { version = "8", default-features = false }
indexmap = "2.2"
tikv-jemallocator = "0.5.4"

axum = "0.6"
hyper = "0.14"
axum = "0.7"
hyper = "1.0"
tower = "0.4"
tower-http = "0.4"
tower-http = "0.5"
1 change: 0 additions & 1 deletion crates/anvil/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ anvil-rpc = { path = "../rpc" }

# axum related
axum = { workspace = true, features = ["ws"] }
hyper.workspace = true
tower-http = { workspace = true, features = ["trace", "cors"] }

# tracing
Expand Down
4 changes: 2 additions & 2 deletions crates/anvil/server/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ pub struct IpcEndpoint<Handler> {

impl<Handler: PubSubRpcHandler> IpcEndpoint<Handler> {
/// Creates a new endpoint with the given handler
pub fn new(handler: Handler, endpoint: impl Into<String>) -> Self {
Self { handler, endpoint: Endpoint::new(endpoint.into()) }
pub fn new(handler: Handler, endpoint: String) -> Self {
Self { handler, endpoint: Endpoint::new(endpoint) }
}

/// Returns a stream of incoming connection handlers
Expand Down
89 changes: 32 additions & 57 deletions crates/anvil/server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Bootstrap [axum] RPC servers
//! Bootstrap [axum] RPC servers.
#![warn(missing_docs, unused_crate_dependencies)]

Expand All @@ -12,91 +12,66 @@ use anvil_rpc::{
};
use axum::{
http::{header, HeaderValue, Method},
routing::{post, IntoMakeService},
Router, Server,
routing::{post, MethodRouter},
Router,
};
use hyper::server::conn::AddrIncoming;
use serde::de::DeserializeOwned;
use std::{fmt, net::SocketAddr};
use std::fmt;
use tower_http::{cors::CorsLayer, trace::TraceLayer};

mod config;
pub use config::ServerConfig;

mod error;
/// handlers for axum server
mod handler;
#[cfg(feature = "ipc")]
pub mod ipc;

mod pubsub;
mod ws;
pub use pubsub::{PubSubContext, PubSubRpcHandler};

pub use crate::pubsub::{PubSubContext, PubSubRpcHandler};
pub use config::ServerConfig;
mod ws;

/// Type alias for the configured axum server
pub type AnvilServer = Server<AddrIncoming, IntoMakeService<Router>>;
#[cfg(feature = "ipc")]
pub mod ipc;

/// Configures an [axum::Server] that handles RPC-Calls, both HTTP requests and requests via
/// websocket
pub fn serve_http_ws<Http, Ws>(
addr: SocketAddr,
config: ServerConfig,
http: Http,
ws: Ws,
) -> AnvilServer
/// Configures an [`axum::Router`] that handles JSON-RPC calls via both HTTP and WS.
pub fn http_ws_router<Http, Ws>(config: ServerConfig, http: Http, ws: Ws) -> Router
where
Http: RpcHandler,
Ws: PubSubRpcHandler,
{
let ServerConfig { allow_origin, no_cors } = config;

let svc = Router::new()
.route("/", post(handler::handle).get(ws::handle_ws))
.with_state((http, ws))
.layer(TraceLayer::new_for_http());

let svc = if no_cors {
svc
} else {
svc.layer(
// see https://docs.rs/tower-http/latest/tower_http/cors/index.html
// for more details
CorsLayer::new()
.allow_origin(allow_origin.0)
.allow_headers(vec![header::CONTENT_TYPE])
.allow_methods(vec![Method::GET, Method::POST]),
)
}
.into_make_service();
Server::bind(&addr).serve(svc)
router_inner(config, post(handler::handle).get(ws::handle_ws), (http, ws))
}

/// Configures an [axum::Server] that handles RPC-Calls listing for POST on `/`
pub fn serve_http<Http>(addr: SocketAddr, config: ServerConfig, http: Http) -> AnvilServer
/// Configures an [`axum::Router`] that handles JSON-RPC calls via HTTP.
pub fn http_router<Http>(config: ServerConfig, http: Http) -> Router
where
Http: RpcHandler,
{
router_inner(config, post(handler::handle), (http, ()))
}

fn router_inner<S: Clone + Send + Sync + 'static>(
config: ServerConfig,
root_method_router: MethodRouter<S>,
state: S,
) -> Router {
let ServerConfig { allow_origin, no_cors } = config;

let svc = Router::new()
.route("/", post(handler::handle))
.with_state((http, ()))
let mut router = Router::new()
.route("/", root_method_router)
.with_state(state)
.layer(TraceLayer::new_for_http());
let svc = if no_cors {
svc
} else {
svc.layer(
if !no_cors {
router = router.layer(
// see https://docs.rs/tower-http/latest/tower_http/cors/index.html
// for more details
CorsLayer::new()
.allow_origin(allow_origin.0)
.allow_headers(vec![header::CONTENT_TYPE])
.allow_methods(vec![Method::GET, Method::POST]),
)
.allow_headers([header::CONTENT_TYPE])
.allow_methods([Method::GET, Method::POST]),
);
}
.into_make_service();

Server::bind(&addr).serve(svc)
router
}

/// Helper trait that is used to execute ethereum rpc calls
Expand Down
16 changes: 7 additions & 9 deletions crates/anvil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,18 +171,16 @@ pub async fn spawn(mut config: NodeConfig) -> (EthApi, NodeHandle) {
let node_service =
tokio::task::spawn(NodeService::new(pool, backend, miner, fee_history_service, filters));

let mut servers = Vec::new();
let mut addresses = Vec::new();
let mut servers = Vec::with_capacity(config.host.len());
let mut addresses = Vec::with_capacity(config.host.len());

for addr in config.host.iter() {
let sock_addr = SocketAddr::new(addr.to_owned(), port);
let srv = server::serve(sock_addr, api.clone(), server_config.clone());

addresses.push(srv.local_addr());
for addr in &config.host {
let sock_addr = SocketAddr::new(*addr, port);
addresses.push(sock_addr);

// spawn the server on a new task
let srv = tokio::task::spawn(srv.map_err(NodeError::from));
servers.push(srv);
let srv = server::serve(sock_addr, api.clone(), server_config.clone()).await.unwrap();
servers.push(tokio::task::spawn(srv.map_err(Into::into)));
}

let tokio_handle = Handle::current();
Expand Down
48 changes: 32 additions & 16 deletions crates/anvil/src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,59 @@
//! Contains the code to launch an ethereum RPC-Server
//! Contains the code to launch an Ethereum RPC server.
use crate::EthApi;
use anvil_server::{ipc::IpcEndpoint, AnvilServer, ServerConfig};
use anvil_server::{ipc::IpcEndpoint, ServerConfig};
use axum::Router;
use futures::StreamExt;
use handler::{HttpEthRpcHandler, PubSubEthRpcHandler};
use std::net::SocketAddr;
use std::{
future::{Future, IntoFuture},
net::SocketAddr,
pin::pin,
};
use tokio::{io, task::JoinHandle};

pub mod error;
mod handler;

pub mod error;
/// Configures a server that handles [`EthApi`] related JSON-RPC calls via HTTP and WS.
///
/// The returned future creates a new server, binding it to the given address, which returns another
/// future that runs it.
pub async fn serve(
addr: SocketAddr,
api: EthApi,
config: ServerConfig,
) -> io::Result<impl Future<Output = io::Result<()>>> {
tokio::net::TcpListener::bind(addr).await.map(|tcp_listener| {
axum::serve(tcp_listener, router(api, config).into_make_service()).into_future()
})
}

/// Configures an [axum::Server] that handles [EthApi] related JSON-RPC calls via HTTP and WS
pub fn serve(addr: SocketAddr, api: EthApi, config: ServerConfig) -> AnvilServer {
/// Configures an [`axum::Router`] that handles [`EthApi`] related JSON-RPC calls via HTTP and WS.
pub fn router(api: EthApi, config: ServerConfig) -> Router {
let http = HttpEthRpcHandler::new(api.clone());
let ws = PubSubEthRpcHandler::new(api);
anvil_server::serve_http_ws(addr, config, http, ws)
anvil_server::http_ws_router(config, http, ws)
}

/// Launches an ipc server at the given path in a new task
///
/// # Panics
///
/// if setting up the ipc connection was unsuccessful
pub fn spawn_ipc(api: EthApi, path: impl Into<String>) -> JoinHandle<io::Result<()>> {
/// Panics if setting up the IPC connection was unsuccessful.
#[track_caller]
pub fn spawn_ipc(api: EthApi, path: String) -> JoinHandle<io::Result<()>> {
try_spawn_ipc(api, path).expect("failed to establish ipc connection")
}

/// Launches an ipc server at the given path in a new task
pub fn try_spawn_ipc(
api: EthApi,
path: impl Into<String>,
) -> io::Result<JoinHandle<io::Result<()>>> {
let path = path.into();
/// Launches an ipc server at the given path in a new task.
pub fn try_spawn_ipc(api: EthApi, path: String) -> io::Result<JoinHandle<io::Result<()>>> {
let handler = PubSubEthRpcHandler::new(api);
let ipc = IpcEndpoint::new(handler, path);
let incoming = ipc.incoming()?;

let task = tokio::task::spawn(async move {
tokio::pin!(incoming);
let mut incoming = pin!(incoming);
while let Some(stream) = incoming.next().await {
trace!(target: "ipc", "new ipc connection");
tokio::task::spawn(stream);
Expand Down
3 changes: 2 additions & 1 deletion crates/forge/bin/cmd/doc/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ async fn serve(build_dir: PathBuf, address: SocketAddr, file_404: &str) {
let file_404 = build_dir.join(file_404);
let svc = ServeDir::new(build_dir).not_found_service(ServeFile::new(file_404));
let app = Router::new().nest_service("/", get_service(svc));
hyper::Server::bind(&address).serve(app.into_make_service()).await.unwrap();
let tcp_listener = tokio::net::TcpListener::bind(address).await.unwrap();
axum::serve(tcp_listener, app.into_make_service()).await.unwrap();
}

fn open<P: AsRef<std::ffi::OsStr>>(path: P) {
Expand Down

0 comments on commit 6ede090

Please sign in to comment.