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 rpc_client::ApiInfo #4280

Merged
merged 10 commits into from
May 2, 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
8 changes: 4 additions & 4 deletions src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ use thiserror::Error;
/// constant string that is used to identify the JWT secret key in `KeyStore`
pub const JWT_IDENTIFIER: &str = "auth-jwt-private";
/// Admin permissions
pub static ADMIN: &[&str] = &["read", "write", "sign", "admin"];
pub const ADMIN: &[&str] = &["read", "write", "sign", "admin"];
/// Signing permissions
pub static SIGN: &[&str] = &["read", "write", "sign"];
pub const SIGN: &[&str] = &["read", "write", "sign"];
/// Writing permissions
pub static WRITE: &[&str] = &["read", "write"];
pub const WRITE: &[&str] = &["read", "write"];
/// Reading permissions
pub static READ: &[&str] = &["read"];
pub const READ: &[&str] = &["read"];

/// Error enumeration for Authentication
#[derive(Debug, Error, Serialize, Deserialize)]
Expand Down
31 changes: 14 additions & 17 deletions src/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ use std::ffi::OsString;
use crate::cli::subcommands::Cli;
use crate::cli_shared::logger;
use crate::daemon::get_actual_chain_name;
use crate::rpc::{self, prelude::*};
use crate::shim::address::{CurrentNetwork, Network};
use crate::{
rpc::{self, prelude::*},
rpc_client::ApiInfo,
};
use clap::Parser;

use super::subcommands::Subcommand;
Expand All @@ -22,7 +19,7 @@ where
// Capture Cli inputs
let Cli { token, cmd } = Cli::parse_from(args);

let api = ApiInfo::from_env()?.set_token(token);
let client = rpc::Client::default_or_from_env(token.as_deref())?;

tokio::runtime::Builder::new_multi_thread()
.enable_all()
Expand All @@ -31,26 +28,26 @@ where
.block_on(async {
logger::setup_logger(&crate::cli_shared::cli::CliOpts::default());

if let Ok(name) = StateNetworkName::call(&rpc::Client::from(api.clone()), ()).await {
if let Ok(name) = StateNetworkName::call(&client, ()).await {
if get_actual_chain_name(&name) != "mainnet" {
CurrentNetwork::set_global(Network::Testnet);
}
}

// Run command
match cmd {
Subcommand::Chain(cmd) => cmd.run(rpc::Client::from(api)).await,
Subcommand::Auth(cmd) => cmd.run(api).await,
Subcommand::Net(cmd) => cmd.run(rpc::Client::from(api)).await,
Subcommand::Sync(cmd) => cmd.run(rpc::Client::from(api)).await,
Subcommand::Mpool(cmd) => cmd.run(api).await,
Subcommand::State(cmd) => cmd.run(api).await,
Subcommand::Chain(cmd) => cmd.run(client).await,
Subcommand::Auth(cmd) => cmd.run(client).await,
Subcommand::Net(cmd) => cmd.run(client).await,
Subcommand::Sync(cmd) => cmd.run(client).await,
Subcommand::Mpool(cmd) => cmd.run(client).await,
Subcommand::State(cmd) => cmd.run(client).await,
Subcommand::Config(cmd) => cmd.run(&mut std::io::stdout()),
Subcommand::Send(cmd) => cmd.run(rpc::Client::from(api)).await,
Subcommand::Info(cmd) => cmd.run(api).await,
Subcommand::Snapshot(cmd) => cmd.run(api).await,
Subcommand::Attach(cmd) => cmd.run(api),
Subcommand::Shutdown(cmd) => cmd.run(rpc::Client::from(api)).await,
Subcommand::Send(cmd) => cmd.run(client).await,
Subcommand::Info(cmd) => cmd.run(client).await,
Subcommand::Snapshot(cmd) => cmd.run(client).await,
Subcommand::Attach(cmd) => cmd.run(client),
Subcommand::Shutdown(cmd) => cmd.run(client).await,
}
})
}
47 changes: 24 additions & 23 deletions src/cli/subcommands/attach_cmd.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::rpc_client::ApiInfo;
use crate::rpc;
use std::path::PathBuf;

#[derive(Debug, clap::Args)]
Expand All @@ -17,14 +17,14 @@ pub struct AttachCommand {

impl AttachCommand {
#[cfg(not(feature = "attach"))]
pub fn run(self, _api: ApiInfo) -> anyhow::Result<()> {
pub fn run(self, _: rpc::Client) -> anyhow::Result<()> {
tracing::warn!("`attach` command is unavailable, forest binaries need to be recompiled with `attach` feature");
Ok(())
}

#[cfg(feature = "attach")]
pub fn run(self, api: ApiInfo) -> anyhow::Result<()> {
self.run_inner(api)
pub fn run(self, client: rpc::Client) -> anyhow::Result<()> {
self.run_inner(client)
}
}

Expand All @@ -33,16 +33,14 @@ mod inner {
use std::{
fs::{canonicalize, read_to_string, OpenOptions},
str::FromStr,
sync::Arc,
};

use super::*;
use crate::chain::ChainEpochDelta;
use crate::chain_sync::SyncStage;
use crate::rpc_client::*;
use crate::rpc::prelude::*;
use crate::shim::{address::Address, message::Message};
use crate::{
chain::ChainEpochDelta,
rpc::{self, prelude::*},
};
use crate::{cli::humantoken, message::SignedMessage};
use boa_engine::{
object::{builtins::JsArray, FunctionObjectBuilder},
Expand Down Expand Up @@ -212,9 +210,9 @@ mod inner {

fn bind_async<T: DeserializeOwned, R: Serialize, Fut>(
context: &mut Context,
api: &ApiInfo,
client: Arc<rpc::Client>,
name: &'static str,
req: impl Fn(T, ApiInfo) -> Fut + 'static,
req: impl Fn(T, Arc<rpc::Client>) -> Fut + 'static,
) where
Fut: Future<Output = anyhow::Result<R>>,
{
Expand All @@ -223,7 +221,7 @@ mod inner {
// not get traced. We're safe because we do not use any GC'ed variables.
let js_func = FunctionObjectBuilder::new(context.realm(), unsafe {
NativeFunction::from_closure({
let api = api.clone();
let client = client.clone();
move |_this, params, context| {
let handle = tokio::runtime::Handle::current();

Expand All @@ -238,7 +236,7 @@ mod inner {
let args = serde_json::from_value(
value.to_json(context).map_err(|e| anyhow::anyhow!("{e}"))?,
)?;
handle.block_on(req(args, api.clone()))
handle.block_on(req(args, client.clone()))
});
check_result(context, result)
}
Expand Down Expand Up @@ -270,7 +268,7 @@ mod inner {

async fn send_message(
params: SendMessageParams,
api: ApiInfo,
client: Arc<rpc::Client>,
) -> anyhow::Result<SignedMessage> {
let (from, to, value) = params;

Expand All @@ -279,20 +277,22 @@ mod inner {
Address::from_str(&to)?,
humantoken::parse(&value)?, // Convert forest_shim::TokenAmount to TokenAmount3
);
Ok(MpoolPushMessage::call(&rpc::Client::from(api), (message, None)).await?)
Ok(MpoolPushMessage::call(&client, (message, None)).await?)
}

type SleepParams = (u64,);
type SleepResult = ();

async fn sleep(params: SleepParams, _api: ApiInfo) -> anyhow::Result<SleepResult> {
async fn sleep(params: SleepParams, _: Arc<rpc::Client>) -> anyhow::Result<SleepResult> {
let secs = params.0;
time::sleep(time::Duration::from_secs(secs)).await;
Ok(())
}

async fn sleep_tipsets(epochs: ChainEpochDelta, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api);
async fn sleep_tipsets(
epochs: ChainEpochDelta,
client: Arc<rpc::Client>,
) -> anyhow::Result<()> {
let mut epoch = None;
loop {
let state = SyncState::call(&client, ()).await?;
Expand All @@ -311,7 +311,8 @@ mod inner {
}

impl AttachCommand {
fn setup_context(&self, context: &mut Context, api: ApiInfo) {
fn setup_context(&self, context: &mut Context, client: rpc::Client) {
let client = Arc::new(client);
let console = Console::init(context);
context
.register_global_property(JsString::from(Console::NAME), console, Attribute::all())
Expand Down Expand Up @@ -344,9 +345,9 @@ mod inner {
bind_request!(context, api,);

// Bind send_message, sleep, sleep_tipsets
bind_async(context, &api, "send_message", send_message);
bind_async(context, &api, "seep", sleep);
bind_async(context, &api, "sleep_tipsets", sleep_tipsets);
bind_async(context, client.clone(), "send_message", send_message);
bind_async(context, client.clone(), "seep", sleep);
bind_async(context, client.clone(), "sleep_tipsets", sleep_tipsets);
}

fn import_prelude(&self, context: &mut Context) -> anyhow::Result<()> {
Expand All @@ -368,7 +369,7 @@ mod inner {
Ok(())
}

pub(super) fn run_inner(self, api: ApiInfo) -> anyhow::Result<()> {
pub(super) fn run_inner(self, api: rpc::Client) -> anyhow::Result<()> {
let mut context = Context::default();
self.setup_context(&mut context, api);

Expand Down
17 changes: 8 additions & 9 deletions src/cli/subcommands/auth_cmd.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::rpc_client::ApiInfo;
use crate::{
auth::*,
rpc::{self, auth::AuthNewParams, prelude::*},
};
use chrono::Duration;
use clap::Subcommand;
use std::str::FromStr;

use super::print_rpc_res_bytes;

Expand All @@ -20,7 +18,7 @@ pub enum AuthCommands {
#[arg(short, long)]
perm: String,
/// Token is revoked after this duration
#[arg(long, default_value_t = humantime::Duration::from_str("2 months").expect("infallible"))]
#[arg(long, default_value = "2 months")]
expire_in: humantime::Duration,
},
/// Get RPC API Information
Expand All @@ -29,7 +27,7 @@ pub enum AuthCommands {
#[arg(short, long)]
perm: String,
/// Token is revoked after this duration
#[arg(long, default_value_t = humantime::Duration::from_str("2 months").expect("infallible"))]
#[arg(long, default_value = "2 months")]
expire_in: humantime::Duration,
},
}
Expand All @@ -48,8 +46,7 @@ fn process_perms(perm: String) -> Result<Vec<String>, rpc::ServerError> {
}

impl AuthCommands {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api.clone());
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
match self {
Self::CreateToken { perm, expire_in } => {
let perm: String = perm.parse()?;
Expand All @@ -62,9 +59,11 @@ impl AuthCommands {
let perm: String = perm.parse()?;
let perms = process_perms(perm)?;
let token_exp = Duration::from_std(expire_in.into())?;
let token = AuthNew::call(&client, (AuthNewParams { perms, token_exp },)).await?;
let new_api = api.set_token(Some(String::from_utf8(token)?));
println!("FULLNODE_API_INFO=\"{}\"", new_api);
let token = String::from_utf8(
AuthNew::call(&client, (AuthNewParams { perms, token_exp },)).await?,
)?;
let addr = multiaddr::from_url(client.base_url().as_str())?;
println!("FULLNODE_API_INFO=\"{}:{}\"", token, addr);
Ok(())
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/cli/subcommands/info_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::blocks::Tipset;
use crate::cli::humantoken::TokenAmountPretty;
use crate::rpc::{self, prelude::*};
use crate::rpc_client::ApiInfo;
use crate::shim::address::Address;
use crate::shim::clock::{ChainEpoch, BLOCKS_PER_EPOCH, EPOCH_DURATION_SECONDS};
use crate::shim::econ::TokenAmount;
Expand Down Expand Up @@ -148,8 +147,7 @@ impl NodeStatusInfo {
}

impl InfoCommand {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api.clone());
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
let (node_status, head, network, start_time, default_wallet_address) = tokio::try_join!(
NodeStatus::call(&client, ()),
ChainHead::call(&client, ()),
Expand Down
4 changes: 1 addition & 3 deletions src/cli/subcommands/mpool_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::blocks::Tipset;
use crate::lotus_json::HasLotusJson as _;
use crate::message::SignedMessage;
use crate::rpc::{self, prelude::*, types::ApiTipsetKey};
use crate::rpc_client::ApiInfo;
use crate::shim::address::StrictAddress;
use crate::shim::message::Message;
use crate::shim::{address::Address, econ::TokenAmount};
Expand Down Expand Up @@ -208,8 +207,7 @@ fn print_stats(stats: &[MpStat], basefee_lookback: u32) {
}

impl MpoolCommands {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api.clone());
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
match self {
Self::Pending {
local,
Expand Down
6 changes: 2 additions & 4 deletions src/cli/subcommands/snapshot_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::chain_sync::SyncConfig;
use crate::cli_shared::snapshot::{self, TrustedVendor};
use crate::rpc::types::ApiTipsetKey;
use crate::rpc::{self, chain::ChainExportParams, prelude::*};
use crate::rpc_client::ApiInfo;
use anyhow::Context as _;
use chrono::DateTime;
use clap::Subcommand;
Expand Down Expand Up @@ -39,8 +38,7 @@ pub enum SnapshotCommands {
}

impl SnapshotCommands {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
let client = rpc::Client::from(api.clone());
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
match self {
Self::Export {
output_path,
Expand Down Expand Up @@ -114,7 +112,7 @@ impl SnapshotCommands {
});
// Manually construct RpcRequest because snapshot export could
// take a few hours on mainnet
let hash_result = api
let hash_result = client
.call(ChainExport::request((params,))?.with_timeout(Duration::MAX))
.await?;

Expand Down
7 changes: 3 additions & 4 deletions src/cli/subcommands/state_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
use std::path::PathBuf;
use std::time::Duration;

use crate::rpc::RpcMethodExt as _;
use crate::rpc::{self, prelude::*};
use crate::shim::clock::ChainEpoch;
use crate::shim::econ::TokenAmount;
use crate::{rpc::state::StateFetchRoot, rpc_client::ApiInfo};
use cid::Cid;
use clap::Subcommand;
use serde_tuple::{self, Deserialize_tuple, Serialize_tuple};
Expand All @@ -34,10 +33,10 @@ pub enum StateCommands {
}

impl StateCommands {
pub async fn run(self, api: ApiInfo) -> anyhow::Result<()> {
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
match self {
Self::Fetch { root, save_to_file } => {
let ret = api
let ret = client
.call(
StateFetchRoot::request((root, save_to_file))?.with_timeout(Duration::MAX),
)
Expand Down
4 changes: 1 addition & 3 deletions src/cli_shared/cli/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ use std::{
str::FromStr,
};

// todo: move this to healthcheck module
use crate::rpc_client::DEFAULT_PORT;
use chrono::Duration;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -98,7 +96,7 @@ impl Default for Client {
buffer_size: BufferSize::default(),
encrypt_keystore: true,
metrics_address: FromStr::from_str("0.0.0.0:6116").unwrap(),
rpc_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), DEFAULT_PORT),
rpc_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), crate::rpc::DEFAULT_PORT),
healthcheck_address: SocketAddr::new(
IpAddr::V4(Ipv4Addr::LOCALHOST),
crate::health::DEFAULT_HEALTHCHECK_PORT,
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ mod message_pool;
mod metrics;
mod networks;
mod rpc;
mod rpc_client;
mod shim;
mod state_manager;
mod state_migration;
Expand Down
Loading
Loading