Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove duplicate JsonRpcError and Request objects #4081

Merged
merged 4 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions scripts/tests/calibnet_offline_rpc_check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ for port in "${PORTS[@]}"; do
diff "$parent_path/test_data/calibnet_block_3000.json" "$temp_dir/block.json"
done

# TODO(aatifsyed): https://github.com/ChainSafe/forest/pull/4096
# `--filter` logic should be commonised
# Compare the http endpoints
$FOREST_TOOL_PATH api compare "$snapshot" --forest /ip4/127.0.0.1/tcp/8080/http --lotus /ip4/127.0.0.1/tcp/8081/http --n-tipsets 5
$FOREST_TOOL_PATH api compare "$snapshot" --forest /ip4/127.0.0.1/tcp/8080/http --lotus /ip4/127.0.0.1/tcp/8081/http --n-tipsets 5 '--filter=!Filecoin.StateWaitMsg'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We probably want to filter out all the flaky tests.


# Compare the ws endpoints
$FOREST_TOOL_PATH api compare "$snapshot" --forest /ip4/127.0.0.1/tcp/8080/ws --lotus /ip4/127.0.0.1/tcp/8081/ws --n-tipsets 5
$FOREST_TOOL_PATH api compare "$snapshot" --forest /ip4/127.0.0.1/tcp/8080/ws --lotus /ip4/127.0.0.1/tcp/8081/ws --n-tipsets 5 '--filter=!Filecoin.StateWaitMsg'
2 changes: 1 addition & 1 deletion src/cli/subcommands/auth_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn process_perms(perm: String) -> Result<Vec<String>, JsonRpcError> {
"sign" => SIGN,
"write" => WRITE,
"read" => READ,
_ => return Err(JsonRpcError::INVALID_PARAMS),
_ => return Err(JsonRpcError::invalid_params("unknown permission", None)),
}
.iter()
.map(ToString::to_string)
Expand Down
1 change: 0 additions & 1 deletion src/daemon/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ pub(super) async fn start(
shutdown_send,
)
.await
.map_err(|err| anyhow::anyhow!("{:?}", serde_json::to_string(&err)))
});
} else {
debug!("RPC disabled.");
Expand Down
62 changes: 44 additions & 18 deletions src/rpc/error.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,66 @@
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use std::fmt::Display;
use std::fmt::{self, Display};

use jsonrpsee::types::error::{
ErrorObjectOwned, INTERNAL_ERROR_CODE, INVALID_PARAMS_CODE, PARSE_ERROR_CODE,
};
use jsonrpsee::types::error::{self, ErrorCode, ErrorObjectOwned};

#[derive(derive_more::From, derive_more::Into, Debug)]
#[derive(derive_more::From, derive_more::Into, Debug, PartialEq)]
pub struct JsonRpcError {
inner: ErrorObjectOwned,
}

impl JsonRpcError {
fn new(code: i32, message: impl Display, data: impl Into<Option<serde_json::Value>>) -> Self {
pub fn new(
code: i32,
message: impl Display,
data: impl Into<Option<serde_json::Value>>,
) -> Self {
Self {
inner: ErrorObjectOwned::owned(code, message.to_string(), data.into()),
}
}
pub fn parse_error(message: impl Display, data: impl Into<Option<serde_json::Value>>) -> Self {
Self::new(PARSE_ERROR_CODE, message, data)
pub fn message(&self) -> &str {
self.inner.message()
}
pub fn internal_error(
message: impl Display,
data: impl Into<Option<serde_json::Value>>,
) -> Self {
Self::new(INTERNAL_ERROR_CODE, message, data)
pub fn known_code(&self) -> ErrorCode {
self.inner.code().into()
}
pub fn invalid_params(
message: impl Display,
data: impl Into<Option<serde_json::Value>>,
) -> Self {
Self::new(INVALID_PARAMS_CODE, message, data)
}

impl Display for JsonRpcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("JSON-RPC error:\n")?;
f.write_fmt(format_args!("\tcode: {}\n", self.inner.code()))?;
f.write_fmt(format_args!("\tmessage: {}\n", self.inner.message()))?;
if let Some(data) = self.inner.data() {
f.write_fmt(format_args!("\tdata: {}\n", data))?
}
Ok(())
}
}

impl std::error::Error for JsonRpcError {}

macro_rules! ctor {
($($ctor:ident { $code:expr })*) => {
$(
impl JsonRpcError {
pub fn $ctor(message: impl Display, data: impl Into<Option<serde_json::Value>>) -> Self {
Self::new($code, message, data)
}
}
)*
}
}

ctor! {
parse_error { error::PARSE_ERROR_CODE }
internal_error { error::INTERNAL_ERROR_CODE }
invalid_params { error::INVALID_PARAMS_CODE }
method_not_found { error::METHOD_NOT_FOUND_CODE }
}

macro_rules! from2internal {
($($ty:ty),* $(,)?) => {
$(
Expand Down
32 changes: 12 additions & 20 deletions src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ mod beacon_api;
mod chain_api;
mod channel;
mod common_api;
mod error;
mod eth_api;
mod gas_api;
mod mpool_api;
Expand All @@ -18,9 +17,11 @@ mod state_api;
mod sync_api;
mod wallet_api;

mod error;
pub use error::JsonRpcError;

use std::net::SocketAddr;
use std::sync::Arc;
use std::{error::Error as StdError, fmt::Display};

use crate::key_management::KeyStore;
use crate::rpc::auth_layer::AuthLayer;
Expand All @@ -43,7 +44,6 @@ use hyper::service::{make_service_fn, service_fn};
use jsonrpsee::{
core::RegisterMethodError,
server::{stop_channel, RpcModule, RpcServiceBuilder, Server, StopHandle, TowerServiceBuilder},
types::{error::ErrorCode as RpcErrorCode, ErrorObjectOwned as RpcError},
Methods,
};
use tokio::sync::mpsc::Sender;
Expand All @@ -70,7 +70,7 @@ pub async fn start_rpc<DB>(
rpc_endpoint: SocketAddr,
forest_version: &'static str,
shutdown_send: Sender<()>,
) -> Result<(), RpcError>
) -> anyhow::Result<()>
where
DB: Blockstore + Send + Sync + 'static,
{
Expand All @@ -86,18 +86,15 @@ where
u64::from(state.state_manager.chain_config().block_delay_secs),
forest_version,
shutdown_send,
)
.map_err(to_rpc_err)?;
)?;

let mut pubsub_module = FilRpcModule::default();

pubsub_module
.register_channel("Filecoin.ChainNotify", {
let state_clone = state.clone();
move |params| chain_api::chain_notify(params, &state_clone)
})
.map_err(to_rpc_err)?;
module.merge(pubsub_module).map_err(to_rpc_err)?;
pubsub_module.register_channel("Filecoin.ChainNotify", {
let state_clone = state.clone();
move |params| chain_api::chain_notify(params, &state_clone)
})?;
module.merge(pubsub_module)?;

let (stop_handle, _handle) = stop_channel();

Expand All @@ -115,7 +112,7 @@ where
let per_conn = per_conn.clone();

async move {
Ok::<_, Box<dyn StdError + Send + Sync>>(service_fn(move |req| {
anyhow::Ok(service_fn(move |req| {
let PerConnection {
methods,
stop_handle,
Expand All @@ -141,8 +138,7 @@ where
info!("Ready for RPC connections");
hyper::Server::bind(&rpc_endpoint)
.serve(make_service)
.await
.map_err(to_rpc_err)?;
.await?;

info!("Stopped accepting RPC connections");

Expand Down Expand Up @@ -324,10 +320,6 @@ where
Ok(())
}

fn to_rpc_err(e: impl Display) -> RpcError {
RpcError::owned::<String>(RpcErrorCode::InternalError.code(), e.to_string(), None)
}

#[cfg(test)]
mod tests {
use std::sync::Arc;
Expand Down
Loading
Loading