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: migrate node to trait RpcEndpoint #4204

Merged
merged 4 commits into from
Apr 17, 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
5 changes: 1 addition & 4 deletions src/cli/subcommands/attach_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,10 +324,7 @@ impl AttachCommand {
// Add custom object that mimics `module.exports`
set_module(context);

bind_request!(context, api,
// Node API
"node_status" => |()| ApiInfo::node_status_req(),
);
bind_request!(context, api,);
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we get rid of this line?


// Bind send_message, sleep, sleep_tipsets
bind_async(context, &api, "send_message", send_message);
Expand Down
2 changes: 1 addition & 1 deletion src/cli/subcommands/info_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl InfoCommand {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api.clone());
let (node_status, head, network, start_time, default_wallet_address) = tokio::try_join!(
api.node_status().map_err(ClientError::from),
NodeStatus::call(&client, ()),
ChainHead::call(&client, ()),
api.state_network_name().map_err(ClientError::from),
StartTime::call(&client, ()),
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/auth_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ static ACCESS_MAP: Lazy<HashMap<&str, Access>> = Lazy::new(|| {
access.insert(net::NetVersion::NAME, Access::Read);

// Node API
access.insert(node::NODE_STATUS, Access::Read);
access.insert(node::NodeStatus::NAME, Access::Read);

// Eth API
access.insert(eth::ETH_ACCOUNTS, Access::Read);
Expand Down
132 changes: 70 additions & 62 deletions src/rpc/methods/node.rs
Original file line number Diff line number Diff line change
@@ -1,90 +1,98 @@
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
#![allow(clippy::unused_async)]

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::rpc::error::ServerError;
use crate::rpc::Ctx;
use crate::rpc::{ApiVersion, Ctx, RpcMethod, ServerError};
use fvm_ipld_blockstore::Blockstore;

pub const NODE_STATUS: &str = "Filecoin.NodeStatus";
pub type NodeStatusResult = NodeStatus;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::lotus_json::lotus_json_with_self;
macro_rules! for_each_method {
($callback:ident) => {
$callback!(crate::rpc::node::NodeStatus);
};
}
pub(crate) use for_each_method;

pub enum NodeStatus {}
impl RpcMethod<0> for NodeStatus {
const NAME: &'static str = "Filecoin.NodeStatus";
const PARAM_NAMES: [&'static str; 0] = [];
const API_VERSION: ApiVersion = ApiVersion::V0;

type Params = ();
type Ok = NodeStatusResult;

async fn handle(ctx: Ctx<impl Blockstore>, (): Self::Params) -> Result<Self::Ok, ServerError> {
let mut node_status = NodeStatusResult::default();

let head = ctx.state_manager.chain_store().heaviest_tipset();
let cur_duration: Duration = SystemTime::now().duration_since(UNIX_EPOCH)?;

let ts = head.min_timestamp();
let cur_duration_secs = cur_duration.as_secs();
let behind = if ts <= cur_duration_secs + 1 {
cur_duration_secs.saturating_sub(ts)
} else {
return Err(anyhow::anyhow!(
"System time should not be behind tipset timestamp, please sync the system clock."
)
.into());
};

let chain_finality = ctx.state_manager.chain_config().policy.chain_finality;

node_status.sync_status.epoch = head.epoch() as u64;
node_status.sync_status.behind = behind;

if head.epoch() > chain_finality {
let mut block_count = 0;
let mut ts = head;

for _ in 0..100 {
block_count += ts.block_headers().len();
let tsk = ts.parents();
ts = ctx.chain_store.chain_index.load_required_tipset(tsk)?;
}

node_status.chain_status.blocks_per_tipset_last_100 = block_count as f64 / 100.;

for _ in 100..chain_finality {
block_count += ts.block_headers().len();
let tsk = ts.parents();
ts = ctx.chain_store.chain_index.load_required_tipset(tsk)?;
}

node_status.chain_status.blocks_per_tipset_last_finality =
block_count as f64 / chain_finality as f64;
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
Ok(node_status)
}
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, JsonSchema)]
pub struct NodeSyncStatus {
pub epoch: u64,
pub behind: u64,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
#[derive(Debug, Serialize, Deserialize, Default, Clone, JsonSchema)]
pub struct NodePeerStatus {
pub peers_to_publish_msgs: u32,
pub peers_to_publish_blocks: u32,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
#[derive(Debug, Serialize, Deserialize, Default, Clone, JsonSchema)]
pub struct NodeChainStatus {
pub blocks_per_tipset_last_100: f64,
pub blocks_per_tipset_last_finality: f64,
}

#[derive(Debug, Deserialize, Default, Serialize, Clone)]
pub struct NodeStatus {
#[derive(Debug, Deserialize, Default, Serialize, Clone, JsonSchema)]
pub struct NodeStatusResult {
pub sync_status: NodeSyncStatus,
pub peer_status: NodePeerStatus,
pub chain_status: NodeChainStatus,
}

lotus_json_with_self!(NodeStatus);

pub async fn node_status<DB: Blockstore>(data: Ctx<DB>) -> Result<NodeStatusResult, ServerError> {
let mut node_status = NodeStatusResult::default();

let head = data.state_manager.chain_store().heaviest_tipset();
let cur_duration: Duration = SystemTime::now().duration_since(UNIX_EPOCH)?;

let ts = head.min_timestamp();
let cur_duration_secs = cur_duration.as_secs();
let behind = if ts <= cur_duration_secs + 1 {
cur_duration_secs.saturating_sub(ts)
} else {
return Err(anyhow::anyhow!(
"System time should not be behind tipset timestamp, please sync the system clock."
)
.into());
};

let chain_finality = data.state_manager.chain_config().policy.chain_finality;

node_status.sync_status.epoch = head.epoch() as u64;
node_status.sync_status.behind = behind;

if head.epoch() > chain_finality {
let mut block_count = 0;
let mut ts = head;

for _ in 0..100 {
block_count += ts.block_headers().len();
let tsk = ts.parents();
ts = data.chain_store.chain_index.load_required_tipset(tsk)?;
}

node_status.chain_status.blocks_per_tipset_last_100 = block_count as f64 / 100.;

for _ in 100..chain_finality {
block_count += ts.block_headers().len();
let tsk = ts.parents();
ts = data.chain_store.chain_index.load_required_tipset(tsk)?;
}

node_status.chain_status.blocks_per_tipset_last_finality =
block_count as f64 / chain_finality as f64;
}

Ok(node_status)
}
6 changes: 2 additions & 4 deletions src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ mod auth_layer;
mod channel;
mod client;

// Other RPC-specific modules
pub use client::Client;
pub use error::ServerError;
use reflect::Ctx;
Expand Down Expand Up @@ -49,6 +48,7 @@ pub mod prelude {
mpool::for_each_method!(export);
net::for_each_method!(export);
state::for_each_method!(export);
node::for_each_method!(export);
sync::for_each_method!(export);
wallet::for_each_method!(export);
}
Expand Down Expand Up @@ -210,6 +210,7 @@ where
mpool::for_each_method!(register);
net::for_each_method!(register);
state::for_each_method!(register);
node::for_each_method!(register);
sync::for_each_method!(register);
wallet::for_each_method!(register);
module.finish()
Expand All @@ -222,7 +223,6 @@ where
{
use eth::*;
use gas::*;
use node::*;

// State API
module.register_async_method(STATE_CALL, state_call::<DB>)?;
Expand Down Expand Up @@ -291,8 +291,6 @@ where
module.register_async_method(GAS_ESTIMATE_FEE_CAP, gas_estimate_fee_cap::<DB>)?;
module.register_async_method(GAS_ESTIMATE_GAS_PREMIUM, gas_estimate_gas_premium::<DB>)?;
module.register_async_method(GAS_ESTIMATE_MESSAGE_GAS, gas_estimate_message_gas::<DB>)?;
// Node API
module.register_async_method(NODE_STATUS, |_, state| node_status::<DB>(state))?;
// Eth API
module.register_async_method(ETH_ACCOUNTS, |_, _| eth_accounts())?;
module.register_async_method(ETH_BLOCK_NUMBER, |_, state| eth_block_number::<DB>(state))?;
Expand Down
59 changes: 59 additions & 0 deletions src/rpc/snapshots/forest_filecoin__rpc__tests__openrpc.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 0 additions & 5 deletions src/rpc_client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
mod chain_ops;
mod eth_ops;
mod gas_ops;
mod node_ops;
mod state_ops;

use crate::libp2p::{Multiaddr, Protocol};
Expand Down Expand Up @@ -174,10 +173,6 @@ impl<T> RpcRequest<T> {
timeout: self.timeout,
}
}
/// Discard type information about the response.
pub fn lower(self) -> RpcRequest {
self.map_ty()
}
}

impl<T> ToRpcParams for RpcRequest<T> {
Expand Down
16 changes: 0 additions & 16 deletions src/rpc_client/node_ops.rs

This file was deleted.

Loading