Skip to content

Commit

Permalink
refactor(cli): fix clipages not building by using async reqwest
Browse files Browse the repository at this point in the history
  • Loading branch information
Meshiest committed Dec 6, 2024
1 parent d4e254a commit 87f1050
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 53 deletions.
2 changes: 1 addition & 1 deletion crates/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ clap_complete.workspace = true
clap-stdin.workspace = true
futures-util.workspace = true
http.workspace = true
reqwest = { workspace = true, features = ["blocking", "json"] }
reqwest = { workspace = true, features = ["json"] }
rustls.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand Down
4 changes: 2 additions & 2 deletions crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct Cli {

impl Cli {
/// Runs the subcommand.
pub fn run(self) -> Result<()> {
self.subcommand.run(&self.url)
pub async fn run(self) -> Result<()> {
self.subcommand.run(&self.url).await
}
}
21 changes: 11 additions & 10 deletions crates/cli/src/commands/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::str::FromStr;

use anyhow::Result;
use clap::{error::ErrorKind, ArgGroup, CommandFactory, Parser, ValueHint};
use reqwest::blocking::{Client, Response};
use reqwest::{Client, Response};
use serde_json::json;
use snops_common::state::AgentId;

Expand Down Expand Up @@ -85,7 +85,7 @@ enum AgentCommands {
}

impl Agent {
pub fn run(self, url: &str, client: Client) -> Result<Response> {
pub async fn run(self, url: &str, client: Client) -> Result<Response> {
use AgentCommands::*;
Ok(match self.command {
Find {
Expand Down Expand Up @@ -116,12 +116,13 @@ impl Agent {
"include_offline": include_offline,
"local_pk": local_pk,
}))
.send()?
.send()
.await?
}
List => {
let ep = format!("{url}/api/v1/agents");

client.get(ep).send()?
client.get(ep).send().await?
}
_ if self.id == AgentId::from_str(DUMMY_ID).unwrap() => {
let mut cmd = Cli::command();
Expand All @@ -134,32 +135,32 @@ impl Agent {
Info => {
let ep = format!("{url}/api/v1/agents/{}", self.id);

client.get(ep).send()?
client.get(ep).send().await?
}
Kill => {
let ep = format!("{url}/api/v1/agents/{}/kill", self.id);

client.post(ep).send()?
client.post(ep).send().await?
}
Status => {
let ep = format!("{url}/api/v1/agents/{}/status", self.id);

client.get(ep).send()?
client.get(ep).send().await?
}
Tps => {
let ep = format!("{url}/api/v1/agents/{}/tps", self.id);

client.get(ep).send()?
client.get(ep).send().await?
}
SetLogLevel { level } => {
let ep = format!("{url}/api/v1/agents/{}/log/{level}", self.id);

client.post(ep).send()?
client.post(ep).send().await?
}

SetSnarkosLogLevel { verbosity } => {
let ep = format!("{url}/api/v1/agents/{}/aot/log/{verbosity}", self.id);
client.post(ep).send()?
client.post(ep).send().await?
}
})
}
Expand Down
20 changes: 10 additions & 10 deletions crates/cli/src/commands/env/action/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, str::FromStr, sync::Arc};
use anyhow::Result;
use clap::Parser;
use clap_stdin::FileOrStdin;
use reqwest::blocking::{Client, RequestBuilder, Response};
use reqwest::{Client, RequestBuilder, Response};
use serde_json::json;
use snops_cli::events::EventsClient;
use snops_common::{
Expand Down Expand Up @@ -91,7 +91,7 @@ pub enum Action {
Execute {
/// Private key to use, can be `committee.0` to use committee member 0's
/// key
#[clap(long, short)]
#[clap(long)]
private_key: Option<KeySource>,
/// Private key to use for the fee. Defaults to the same as
/// --private-key
Expand Down Expand Up @@ -167,7 +167,7 @@ pub enum Action {
#[clap(long, short)]
binary: Option<InternedId>,
/// Configure the private key for a node.
#[clap(long, short)]
#[clap(long)]
private_key: Option<KeySource>,
#[clap(long = "async")]
async_mode: bool,
Expand Down Expand Up @@ -200,7 +200,7 @@ impl Action {
let ep = format!("{url}/api/v1/env/{env_id}/action/offline");
let req = client.post(ep).json(&WithTargets::from(nodes));
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait(url, req, env_id).await?;
std::process::exit(0);
Expand All @@ -210,7 +210,7 @@ impl Action {
let ep = format!("{url}/api/v1/env/{env_id}/action/online");
let req = client.post(ep).json(&WithTargets::from(nodes));
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait(url, req, env_id).await?;
std::process::exit(0);
Expand All @@ -220,7 +220,7 @@ impl Action {
let ep = format!("{url}/api/v1/env/{env_id}/action/reboot");
let req = client.post(ep).json(&WithTargets::from(nodes));
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait(url, req, env_id).await?;
std::process::exit(0);
Expand Down Expand Up @@ -271,7 +271,7 @@ impl Action {

let req = client.post(ep).query(&[("async", "true")]).json(&json);
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait_tx(url, req).await?;
std::process::exit(0);
Expand Down Expand Up @@ -310,7 +310,7 @@ impl Action {

let req = client.post(ep).query(&[("async", "true")]).json(&json);
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait_tx(url, req).await?;
std::process::exit(0);
Expand Down Expand Up @@ -366,7 +366,7 @@ impl Action {
let req = client.post(ep).json(&json!(vec![json]));

if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait(url, req, env_id).await?;
std::process::exit(0);
Expand All @@ -379,7 +379,7 @@ impl Action {
pub async fn post_and_wait_tx(url: &str, req: RequestBuilder) -> Result<()> {
use snops_common::events::EventFilter::*;

let tx_id: String = req.send()?.json()?;
let tx_id: String = req.send().await?.json().await?;

let mut events = EventsClient::open_with_filter(url, TransactionIs(Arc::new(tx_id))).await?;

Expand Down
44 changes: 22 additions & 22 deletions crates/cli/src/commands/env/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use action::post_and_wait_tx;
use anyhow::Result;
use clap::{Parser, ValueHint};
use clap_stdin::FileOrStdin;
use reqwest::blocking::{Client, RequestBuilder, Response};
use reqwest::{Client, RequestBuilder, Response};
use snops_cli::events::EventsClient;
use snops_common::{
action_models::AleoValue,
Expand Down Expand Up @@ -141,12 +141,12 @@ impl Env {
Agent { key } => {
let ep = format!("{url}/api/v1/env/{id}/agents/{key}");

client.get(ep).send()?
client.get(ep).send().await?
}
Agents => {
let ep = format!("{url}/api/v1/env/{id}/agents");

client.get(ep).send()?
client.get(ep).send().await?
}
Auth {
async_mode,
Expand All @@ -162,7 +162,7 @@ impl Env {
}

if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait_tx(url, req).await?;
std::process::exit(0);
Expand All @@ -171,43 +171,43 @@ impl Env {
Balance { address: key } => {
let ep = format!("{url}/api/v1/env/{id}/balance/{key}");

client.get(ep).json(&key).send()?
client.get(ep).json(&key).send().await?
}
Block { height_or_hash } => {
let ep = format!("{url}/api/v1/env/{id}/block/{height_or_hash}");

client.get(ep).send()?
client.get(ep).send().await?
}
Delete => {
let ep = format!("{url}/api/v1/env/{id}");

client.delete(ep).send()?
client.delete(ep).send().await?
}
Info => {
let ep = format!("{url}/api/v1/env/{id}/info");

client.get(ep).send()?
client.get(ep).send().await?
}
List => {
let ep = format!("{url}/api/v1/env/list");

client.get(ep).send()?
client.get(ep).send().await?
}
Topology => {
let ep = format!("{url}/api/v1/env/{id}/topology");

client.get(ep).send()?
client.get(ep).send().await?
}
TopologyResolved => {
let ep = format!("{url}/api/v1/env/{id}/topology/resolved");

client.get(ep).send()?
client.get(ep).send().await?
}
Apply { spec, async_mode } => {
let ep = format!("{url}/api/v1/env/{id}/apply");
let req = client.post(ep).body(spec.contents()?);
if async_mode {
req.send()?
req.send().await?
} else {
post_and_wait(url, req, id).await?;
std::process::exit(0);
Expand All @@ -231,38 +231,38 @@ impl Env {
}
};

client.get(ep).send()?
client.get(ep).send().await?
}
Mappings { program } => {
let ep = format!("{url}/api/v1/env/{id}/program/{program}/mappings");

client.get(ep).send()?
client.get(ep).send().await?
}
Program { id: prog } => {
let ep = format!("{url}/api/v1/env/{id}/program/{prog}");

println!("{}", client.get(ep).send()?.text()?);
println!("{}", client.get(ep).send().await?.text().await?);
std::process::exit(0);
}
Storage => {
let ep = format!("{url}/api/v1/env/{id}/storage");

client.get(ep).send()?
client.get(ep).send().await?
}
Transaction { id: hash } => {
let ep = format!("{url}/api/v1/env/{id}/transaction_block/{hash}");

client.get(ep).send()?
client.get(ep).send().await?
}
TransactionDetails { id: hash } => {
let ep = format!("{url}/api/v1/env/{id}/transaction/{hash}");

client.get(ep).send()?
client.get(ep).send().await?
}
Height => {
let ep = format!("{url}/api/v1/env/{id}/height");

client.get(ep).send()?
client.get(ep).send().await?
}
})
}
Expand All @@ -283,17 +283,17 @@ pub async fn post_and_wait(url: &str, req: RequestBuilder, env_id: EnvId) -> Res
)
.await?;

let res = req.send()?;
let res = req.send().await?;

if !res.status().is_success() {
println!(
"{}",
serde_json::to_string_pretty(&res.json::<serde_json::Value>()?)?
serde_json::to_string_pretty(&res.json::<serde_json::Value>().await?)?
);
std::process::exit(1);
}

let mut node_map: HashMap<NodeKey, AgentId> = res.json()?;
let mut node_map: HashMap<NodeKey, AgentId> = res.json().await?;
println!("{}", serde_json::to_string_pretty(&node_map)?);

let filter = node_map
Expand Down
12 changes: 7 additions & 5 deletions crates/cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ pub enum Commands {
}

impl Commands {
#[tokio::main]
pub async fn run(self, url: &str) -> Result<()> {
let client = reqwest::blocking::Client::new();
let client = reqwest::Client::new();

let response = match self {
Commands::Autocomplete { shell } => {
Expand All @@ -52,10 +51,13 @@ impl Commands {
clap_complete::generate(shell, &mut cmd, cmd_name, &mut std::io::stdout());
return Ok(());
}
Commands::Agent(agent) => agent.run(url, client),
Commands::Agent(agent) => agent.run(url, client).await,
Commands::Env(env) => env.run(url, client).await,
Commands::SetLogLevel { level } => {
client.post(format!("{url}/api/v1/log/{level}")).send()?;
client
.post(format!("{url}/api/v1/log/{level}"))
.send()
.await?;
return Ok(());
}
Commands::Events { filter } => {
Expand Down Expand Up @@ -88,7 +90,7 @@ impl Commands {

let value = match response.content_length() {
Some(0) | None => None,
_ => response.json::<Value>().map(Some)?,
_ => response.json::<Value>().await.map(Some)?,
};

println!("{}", serde_json::to_string_pretty(&value)?);
Expand Down
5 changes: 3 additions & 2 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ mod events;
mod commands;
pub(crate) use commands::*;

fn main() -> Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
rustls::crypto::ring::default_provider()
.install_default()
.expect("Failed to install rustls crypto provider");

let cli = cli::Cli::parse();

if let Err(err) = cli.run() {
if let Err(err) = cli.run().await {
eprintln!("⚠️ {err:?}");
exit(1);
}
Expand Down
Loading

0 comments on commit 87f1050

Please sign in to comment.