Skip to content

Commit

Permalink
[rooch-networkgh-2406] add proxy config to env file.
Browse files Browse the repository at this point in the history
  • Loading branch information
Feliciss committed Aug 24, 2024
1 parent afb6803 commit 2d36fa5
Show file tree
Hide file tree
Showing 9 changed files with 254 additions and 79 deletions.
241 changes: 171 additions & 70 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ tonic = { version = "0.8", features = ["gzip"] }
tracing = "0.1.37"
tracing-appender = "0.2.2"
tracing-subscriber = { version = "0.3.15" }
reqwest = { version = "0.12.7", features = ["json"] }

codespan-reporting = "0.11.1"
codespan = "0.11.1"
Expand Down
2 changes: 2 additions & 0 deletions crates/rooch-rpc-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ jsonrpsee = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
hex = { workspace = true }
reqwest = { workspace = true }
axum = { workspace = true }

move-core-types = { workspace = true }

Expand Down
7 changes: 7 additions & 0 deletions crates/rooch-rpc-client/src/client_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ pub struct Env {
pub alias: String,
pub rpc: String,
pub ws: Option<String>,
pub proxy: Option<String>,
}

impl Env {
Expand All @@ -83,6 +84,9 @@ impl Env {
if let Some(ws_url) = &self.ws {
builder = builder.ws_url(ws_url);
}
if let Some(proxy_url) = &self.proxy {
builder = builder.proxy_url(proxy_url);
}

builder.build(&self.rpc).await
}
Expand All @@ -92,6 +96,7 @@ impl Env {
alias: BuiltinChainID::Dev.chain_name(),
rpc: ROOCH_DEV_NET_URL.into(),
ws: None,
proxy: None,
}
}

Expand All @@ -100,6 +105,7 @@ impl Env {
alias: BuiltinChainID::Test.chain_name(),
rpc: ROOCH_TEST_NET_URL.into(),
ws: None,
proxy: None,
}
}

Expand All @@ -121,6 +127,7 @@ impl Default for Env {
alias: BuiltinChainID::Local.chain_name(),
rpc: ServerConfig::default().url(false),
ws: None,
proxy: None,
}
}
}
Expand Down
47 changes: 47 additions & 0 deletions crates/rooch-rpc-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ use moveos_types::{
function_return_value::FunctionResult, module_binding::MoveFunctionCaller,
moveos_std::tx_context::TxContext, transaction::FunctionCall,
};
use reqwest::Proxy;
use rooch_client::RoochRpcClient;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
Expand All @@ -27,6 +29,7 @@ pub mod wallet_context;
pub struct ClientBuilder {
request_timeout: Duration,
ws_url: Option<String>,
proxy_url: Option<String>,
}

impl ClientBuilder {
Expand All @@ -40,6 +43,11 @@ impl ClientBuilder {
self
}

pub fn proxy_url(mut self, url: impl AsRef<str>) -> Self {
self.proxy_url = Some(url.as_ref().to_string());
self
}

pub async fn build(self, http: impl AsRef<str>) -> Result<Client> {
// TODO: add verison info

Expand All @@ -50,9 +58,24 @@ impl ClientBuilder {
.build(http)?,
);

if let Some(proxy_url) = self.proxy_url {
let reqwest_client = Some(Arc::new(
reqwest::Client::builder()
.proxy(Proxy::https(proxy_url.clone())?)
.proxy(Proxy::all(proxy_url)?)
.build()?,
));
return Ok(Client {
http: http_client.clone(),
rooch: RoochRpcClient::new(http_client.clone()),
reqwest: reqwest_client,
});
};

Ok(Client {
http: http_client.clone(),
rooch: RoochRpcClient::new(http_client.clone()),
reqwest: None,
})
}
}
Expand All @@ -62,13 +85,15 @@ impl Default for ClientBuilder {
Self {
request_timeout: Duration::from_secs(60),
ws_url: None,
proxy_url: None,
}
}
}

#[derive(Clone)]
pub struct Client {
http: Arc<HttpClient>,
reqwest: Option<Arc<reqwest::Client>>,
pub rooch: RoochRpcClient,
}

Expand All @@ -86,6 +111,28 @@ impl Client {
) -> Result<serde_json::Value> {
Ok(self.http.request(method, params).await?)
}

pub async fn request_by_proxy(
&self,
url: &str,
method: &str,
params: Vec<serde_json::Value>,
) -> Result<serde_json::Value> {
if let Some(reqwest) = &self.reqwest {
let response = reqwest
.post(url)
.header("Content-Type", "application/json")
.json(&json!({
"method": method,
"params": params,
}))
.send()
.await?;
return Ok(response.json::<serde_json::Value>().await?);
};

Ok(serde_json::Value::Null)
}
}

impl MoveFunctionCaller for Client {
Expand Down
11 changes: 10 additions & 1 deletion crates/rooch/src/commands/env/commands/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,23 @@ pub struct AddCommand {
pub rpc: String,
#[clap(long, value_hint = ValueHint::Url)]
pub ws: Option<String>,
#[clap(long, value_hint = ValueHint::Url)]
pub proxy: Option<String>,
}

impl AddCommand {
pub async fn execute(self) -> RoochResult<()> {
let mut context = self.context_options.build()?;
let AddCommand { alias, rpc, ws, .. } = self;
let AddCommand {
alias,
rpc,
ws,
proxy,
..
} = self;
let env = Env {
ws,
proxy,
rpc,
alias: alias.clone(),
};
Expand Down
12 changes: 7 additions & 5 deletions crates/rooch/src/commands/env/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ impl ListCommand {
let context = self.context_options.build()?;

println!(
"{:^24} | {:^48} | {:^48} | {:^12}",
"Env Alias", "RPC URL", "Websocket URL", "Active Env"
"{:^24} | {:^48} | {:^48} | {:^48} | {:^12}",
"Env Alias", "RPC URL", "Websocket URL", "Proxy", "Active Env"
);
println!("{}", ["-"; 153].join(""));
println!("{}", ["-"; 203].join(""));

for env in context.client_config.envs.iter() {
let mut active = "";
Expand All @@ -29,9 +29,11 @@ impl ListCommand {
}

let ws = env.ws.clone().unwrap_or("Null".to_owned());
let proxy = env.proxy.clone().unwrap_or("Null".to_owned());

println!(
"{:^24} | {:^48} | {:^48} | {:^12}",
env.alias, env.rpc, ws, active
"{:^24} | {:^48} | {:^48} | {:^48} | {:^12}",
env.alias, env.rpc, ws, proxy, active
)
}

Expand Down
2 changes: 2 additions & 0 deletions crates/rooch/src/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl CommandAction<()> for Init {
alias: "custom".to_string(),
rpc: chain_url[1].to_owned(),
ws: None,
proxy: None,
})
}

Expand Down Expand Up @@ -112,6 +113,7 @@ impl CommandAction<()> for Init {
alias,
rpc: url,
ws: None,
proxy: None,
}
})
}
Expand Down
10 changes: 7 additions & 3 deletions crates/rooch/src/commands/rpc/commands/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub struct RequestCommand {

#[clap(flatten)]
pub(crate) context_options: WalletContextOptions,

/// Return command outputs in json format
#[clap(long, default_value = "false")]
json: bool,
Expand All @@ -36,7 +35,8 @@ pub struct RequestCommand {
#[async_trait]
impl CommandAction<serde_json::Value> for RequestCommand {
async fn execute(self) -> RoochResult<serde_json::Value> {
let client = self.context_options.build()?.get_client().await?;
let context = self.context_options.build()?;
let client = context.get_client().await?;
let params = match self.params {
Some(serde_json::Value::Array(array)) => array,
Some(value) => {
Expand All @@ -51,7 +51,11 @@ impl CommandAction<serde_json::Value> for RequestCommand {
}
None => vec![],
};
Ok(client.request(self.method.as_str(), params).await?)
let active_env = context.client_config.get_active_env()?;

Ok(client
.request_by_proxy(&active_env.rpc, self.method.as_str(), params)
.await?)
}

/// Executes the command, and serializes it to the common JSON output type
Expand Down

0 comments on commit 2d36fa5

Please sign in to comment.