Skip to content

Commit

Permalink
Add utils::http mod
Browse files Browse the repository at this point in the history
  • Loading branch information
overcat committed Sep 27, 2024
1 parent 60b91c6 commit c7a2a85
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 23 deletions.
3 changes: 2 additions & 1 deletion cmd/soroban-cli/src/commands/contract/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use std::{
};
use toml_edit::{Document, TomlError};

use crate::utils::http;
use crate::{commands::global, print};

const SOROBAN_EXAMPLES_URL: &str = "https://github.com/stellar/soroban-examples.git";
Expand Down Expand Up @@ -260,7 +261,7 @@ impl Runner {
}

fn check_internet_connection() -> bool {
if let Ok(_req) = reqwest::blocking::get(GITHUB_URL) {
if let Ok(_req) = http::blocking_client().get(GITHUB_URL).send() {
return true;
}

Expand Down
11 changes: 8 additions & 3 deletions cmd/soroban-cli/src/commands/snapshot/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use clap::{arg, Parser, ValueEnum};
use futures::StreamExt;
use humantime::format_duration;
use itertools::{Either, Itertools};
use reqwest::Url;
use sha2::{Digest, Sha256};
use soroban_ledger_snapshot::LedgerSnapshot;
use std::{
Expand All @@ -26,7 +25,9 @@ use stellar_xdr::curr::{
use tokio::fs::OpenOptions;
use tokio::io::BufReader;
use tokio_util::io::StreamReader;
use url::Url;

use crate::utils::http;
use crate::{
commands::{config::data, global, HEADING_RPC},
config::{self, locator, network::passphrase},
Expand Down Expand Up @@ -411,7 +412,9 @@ async fn get_history(

print.globe(format!("Downloading history {history_url}"));

let response = reqwest::get(history_url.as_str())
let response = http::client()
.get(history_url.as_str())
.send()
.await
.map_err(Error::DownloadingHistory)?;

Expand Down Expand Up @@ -462,7 +465,9 @@ async fn cache_bucket(

let bucket_url = Url::from_str(&bucket_url).map_err(Error::ParsingBucketUrl)?;

let response = reqwest::get(bucket_url.as_str())
let response = http::client()
.get(bucket_url.as_str())
.send()
.await
.map_err(Error::GettingBucket)?;

Expand Down
2 changes: 1 addition & 1 deletion cmd/soroban-cli/src/config/data.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::rpc::{GetTransactionResponse, GetTransactionResponseRaw, SimulateTransactionResponse};
use directories::ProjectDirs;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use url::Url;

use crate::xdr::{self, WriteXdr};

Expand Down
8 changes: 4 additions & 4 deletions cmd/soroban-cli/src/config/network.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use clap::arg;
use phf::phf_map;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::str::FromStr;
use stellar_strkey::ed25519::PublicKey;
use url::Url;

use super::locator;
use crate::utils::http;
use crate::{
commands::HEADING_RPC,
rpc::{self, Client},
};

use super::locator;
pub mod passphrase;

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -130,7 +130,7 @@ impl Network {
pub async fn fund_address(&self, addr: &PublicKey) -> Result<(), Error> {
let uri = self.helper_url(&addr.to_string()).await?;
tracing::debug!("URL {uri:?}");
let response = reqwest::get(uri.as_str()).await?;
let response = http::client().get(uri.as_str()).send().await?;

let request_successful = response.status().is_success();
let body = response.bytes().await?;
Expand Down
16 changes: 2 additions & 14 deletions cmd/soroban-cli/src/upgrade_check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::config::upgrade_check::UpgradeCheck;
use crate::print::Print;
use crate::utils::http;
use semver::Version;
use serde::Deserialize;
use std::error::Error;
Expand All @@ -8,7 +9,6 @@ use std::time::Duration;

const MINIMUM_CHECK_INTERVAL: Duration = Duration::from_secs(60 * 60 * 24); // 1 day
const CRATES_IO_API_URL: &str = "https://crates.io/api/v1/crates/";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const NO_UPDATE_CHECK_ENV_VAR: &str = "STELLAR_NO_UPDATE_CHECK";

#[derive(Deserialize)]
Expand All @@ -29,19 +29,7 @@ struct Crate {
async fn fetch_latest_crate_info() -> Result<Crate, Box<dyn Error>> {
let crate_name = env!("CARGO_PKG_NAME");
let url = format!("{CRATES_IO_API_URL}{crate_name}");
let client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.default_headers({
// crates.io requires a User-Agent header
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
"User-Agent",
reqwest::header::HeaderValue::from_static(crate_name),
);
headers
})
.build()?;
let resp = client
let resp = http::client()
.get(url)
.send()
.await?
Expand Down
35 changes: 35 additions & 0 deletions cmd/soroban-cli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,41 @@ pub fn get_name_from_stellar_asset_contract_storage(storage: &ScMap) -> Option<S
}
}

pub mod http {
use crate::commands::version;
fn user_agent() -> String {
format!("{}/{}", env!("CARGO_PKG_NAME"), version::pkg())
}

/// Creates and returns a configured reqwest::Client.
///
/// # Panics
///
/// Panics if the Client initialization fails.
pub fn client() -> reqwest::Client {
// Why we panic here:
// 1. Client initialization failures are rare and usually indicate serious issues.
// 2. The application cannot function properly without a working HTTP client.
// 3. This simplifies error handling for callers, as they can assume a valid client.
reqwest::Client::builder()
.user_agent(user_agent())
.build()
.expect("Failed to build reqwest client")
}

/// Creates and returns a configured reqwest::blocking::Client.
///
/// # Panics
///
/// Panics if the Client initialization fails.
pub fn blocking_client() -> reqwest::blocking::Client {
reqwest::blocking::Client::builder()
.user_agent(user_agent())
.build()
.expect("Failed to build reqwest blocking client")
}
}

pub mod rpc {
use soroban_env_host::xdr;
use soroban_rpc::{Client, Error};
Expand Down

0 comments on commit c7a2a85

Please sign in to comment.