Skip to content

Commit

Permalink
[CLI][Rest] added default custom header (aptos-labs#8368)
Browse files Browse the repository at this point in the history
* added default custom header

* fixes on comments

* moved the client_builder to new file

* fixes from comment
  • Loading branch information
0xmigo authored May 31, 2023
1 parent f2b84c8 commit 4beb914
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 45 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions aptos
101 changes: 101 additions & 0 deletions crates/aptos-rest-client/src/client_builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright © Aptos Foundation
// SPDX-License-Identifier: Apache-2.0

use crate::{
get_version_path_with_base, Client, DEFAULT_VERSION_PATH_BASE, X_APTOS_SDK_HEADER_VALUE,
};
use anyhow::Result;
use aptos_api_types::X_APTOS_CLIENT;
use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Client as ReqwestClient, ClientBuilder as ReqwestClientBuilder,
};
use std::{str::FromStr, time::Duration};
use url::Url;

pub enum AptosBaseUrl {
Mainnet,
Devnet,
Testnet,
Custom(Url),
}

impl AptosBaseUrl {
pub fn to_url(&self) -> Url {
match self {
AptosBaseUrl::Mainnet => {
Url::from_str("https://fullnode.mainnet.aptoslabs.com").unwrap()
},
AptosBaseUrl::Devnet => Url::from_str("https://fullnode.devnet.aptoslabs.com").unwrap(),
AptosBaseUrl::Testnet => {
Url::from_str("https://fullnode.testnet.aptoslabs.com").unwrap()
},
AptosBaseUrl::Custom(url) => url.to_owned(),
}
}
}

pub struct ClientBuilder {
reqwest_builder: ReqwestClientBuilder,
version_path_base: String,
base_url: Url,
timeout: Duration,
headers: HeaderMap,
}

impl ClientBuilder {
pub fn new(aptos_base_url: AptosBaseUrl) -> Self {
let mut headers = HeaderMap::new();
headers.insert(
X_APTOS_CLIENT,
HeaderValue::from_static(X_APTOS_SDK_HEADER_VALUE),
);

Self {
reqwest_builder: ReqwestClient::builder(),
base_url: aptos_base_url.to_url(),
version_path_base: DEFAULT_VERSION_PATH_BASE.to_string(),
timeout: Duration::from_secs(10), // Default to 10 seconds
headers,
}
}

pub fn base_url(mut self, base_url: Url) -> Self {
self.base_url = base_url;
self
}

pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}

pub fn header(mut self, header_key: &str, header_val: &str) -> Result<Self> {
self.headers.insert(
HeaderName::from_str(header_key)?,
HeaderValue::from_str(header_val)?,
);
Ok(self)
}

pub fn version_path_base(mut self, version_path_base: String) -> Self {
self.version_path_base = version_path_base;
self
}

pub fn build(self) -> Client {
let version_path_base = get_version_path_with_base(self.base_url.clone());

Client {
inner: self
.reqwest_builder
.default_headers(self.headers)
.timeout(self.timeout)
.cookie_store(true)
.build()
.unwrap(),
base_url: self.base_url,
version_path_base,
}
}
}
59 changes: 22 additions & 37 deletions crates/aptos-rest-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ pub mod faucet;
pub use faucet::FaucetClient;
pub mod response;
pub use response::Response;
pub mod client_builder;
pub mod state;
pub mod types;

pub use crate::client_builder::{AptosBaseUrl, ClientBuilder};
use crate::{
aptos::{AptosVersion, Balance},
error::RestError,
Expand Down Expand Up @@ -50,7 +52,6 @@ use tokio::time::Instant;
pub use types::{deserialize_from_prefixed_hex_string, Account, Resource};
use url::Url;

pub const USER_AGENT: &str = concat!("aptos-client-sdk-rust / ", env!("CARGO_PKG_VERSION"));
pub const DEFAULT_VERSION_PATH_BASE: &str = "v1/";
const DEFAULT_MAX_WAIT_MS: u64 = 60000;
const DEFAULT_INTERVAL_MS: u64 = 1000;
Expand All @@ -59,6 +60,7 @@ static DEFAULT_INTERVAL_DURATION: Duration = Duration::from_millis(DEFAULT_INTER
const DEFAULT_MAX_SERVER_LAG_WAIT_DURATION: Duration = Duration::from_secs(60);
const RESOURCES_PER_CALL_PAGINATION: u64 = 9999;
const MODULES_PER_CALL_PAGINATION: u64 = 1000;
const X_APTOS_SDK_HEADER_VALUE: &str = concat!("aptos-rust-sdk/", env!("CARGO_PKG_VERSION"));

type AptosResult<T> = Result<T, RestError>;

Expand All @@ -70,45 +72,12 @@ pub struct Client {
}

impl Client {
pub fn new_with_timeout(base_url: Url, timeout: Duration) -> Self {
Client::new_with_timeout_and_user_agent(base_url, timeout, USER_AGENT)
}

pub fn new_with_timeout_and_user_agent(
base_url: Url,
timeout: Duration,
user_agent: &str,
) -> Self {
let inner = ReqwestClient::builder()
.timeout(timeout)
.user_agent(user_agent)
.cookie_store(true)
.build()
.unwrap();

// If the user provided no version in the path, use the default. If the
// provided version has no trailing slash, add it, otherwise url.join
// will ignore the version path base.
let version_path_base = match base_url.path() {
"/" => DEFAULT_VERSION_PATH_BASE.to_string(),
path => {
if !path.ends_with('/') {
format!("{}/", path)
} else {
path.to_string()
}
},
};

Self {
inner,
base_url,
version_path_base,
}
pub fn builder(aptos_base_url: AptosBaseUrl) -> ClientBuilder {
ClientBuilder::new(aptos_base_url)
}

pub fn new(base_url: Url) -> Self {
Self::new_with_timeout(base_url, Duration::from_secs(10))
Self::builder(AptosBaseUrl::Custom(base_url)).build()
}

pub fn path_prefix_string(&self) -> String {
Expand Down Expand Up @@ -1583,6 +1552,22 @@ impl Client {
}
}

// If the user provided no version in the path, use the default. If the
// provided version has no trailing slash, add it, otherwise url.join
// will ignore the version path base.
pub fn get_version_path_with_base(base_url: Url) -> String {
match base_url.path() {
"/" => DEFAULT_VERSION_PATH_BASE.to_string(),
path => {
if !path.ends_with('/') {
format!("{}/", path)
} else {
path.to_string()
}
},
}
}

pub fn retriable_with_404(status_code: StatusCode, aptos_error: Option<AptosError>) -> bool {
retriable(status_code, aptos_error) | matches!(status_code, StatusCode::NOT_FOUND)
}
Expand Down
1 change: 1 addition & 0 deletions crates/aptos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ rust-version = { workspace = true }

[dependencies]
anyhow = { workspace = true }
aptos-api-types = { workspace = true }
aptos-backup-cli = { workspace = true }
aptos-bitvec = { workspace = true }
aptos-build-info = { workspace = true }
Expand Down
14 changes: 8 additions & 6 deletions crates/aptos/src/common/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use aptos_logger::Level;
use aptos_rest_client::{
aptos_api_types::{EntryFunctionId, HashValue, MoveType, ViewRequest},
error::RestError,
Client, Transaction,
AptosBaseUrl, Client, Transaction,
};
use aptos_sdk::{transaction_builder::TransactionFactory, types::LocalAccount};
use aptos_types::{
Expand Down Expand Up @@ -63,6 +63,9 @@ const ACCEPTED_CLOCK_SKEW_US: u64 = 5 * US_IN_SECS;
pub const DEFAULT_EXPIRATION_SECS: u64 = 30;
pub const DEFAULT_PROFILE: &str = "default";

// Custom header value to identify the client
const X_APTOS_CLIENT_VALUE: &str = concat!("aptos-cli/", env!("CARGO_PKG_VERSION"));

/// A common result to be returned to users
pub type CliResult = Result<String, String>;

Expand Down Expand Up @@ -905,11 +908,10 @@ impl RestOptions {
}

pub fn client(&self, profile: &ProfileOptions) -> CliTypedResult<Client> {
Ok(Client::new_with_timeout_and_user_agent(
self.url(profile)?,
Duration::from_secs(self.connection_timeout_secs),
USER_AGENT,
))
Ok(Client::builder(AptosBaseUrl::Custom(self.url(profile)?))
.timeout(Duration::from_secs(self.connection_timeout_secs))
.header(aptos_api_types::X_APTOS_CLIENT, X_APTOS_CLIENT_VALUE)?
.build())
}
}

Expand Down
1 change: 1 addition & 0 deletions sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ rust-version = { workspace = true }

[dependencies]
anyhow = { workspace = true }
aptos-api-types = { workspace = true }
aptos-cached-packages = { workspace = true }
aptos-crypto = { workspace = true }
aptos-global-constants = { workspace = true }
Expand Down
6 changes: 4 additions & 2 deletions testsuite/forge/src/interface/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{Result, Version};
use anyhow::anyhow;
use aptos_config::{config::NodeConfig, network_id::NetworkId};
use aptos_inspection_service::inspection_client::InspectionClient;
use aptos_rest_client::Client as RestClient;
use aptos_rest_client::{AptosBaseUrl, Client as RestClient};
use aptos_sdk::types::PeerId;
use std::{
collections::HashMap,
Expand Down Expand Up @@ -144,7 +144,9 @@ pub trait NodeExt: Node {

/// Return REST API client of this Node
fn rest_client_with_timeout(&self, timeout: Duration) -> RestClient {
RestClient::new_with_timeout(self.rest_api_endpoint(), timeout)
RestClient::builder(AptosBaseUrl::Custom(self.rest_api_endpoint()))
.timeout(timeout)
.build()
}

/// Return an InspectionClient for this Node
Expand Down

0 comments on commit 4beb914

Please sign in to comment.