use std::env;
use std::time::Duration;
use cloudflare::framework::async_api;
use cloudflare::framework::auth::Credentials;
use cloudflare::framework::response::ApiFailure;
use cloudflare::framework::{Environment, HttpApiClient, HttpApiClientConfig};
use http::StatusCode;
use anyhow::Result;
use crate::http::{feature::headers, DEFAULT_HTTP_TIMEOUT_SECONDS};
use crate::settings::global_user::GlobalUser;
use crate::terminal::emoji;
use crate::terminal::message::{Message, StdOut};
const CF_API_BASE_URL: &str = "CF_API_BASE_URL";
pub fn get_environment() -> Result<Environment> {
let env_hostname = match env::var(CF_API_BASE_URL) {
Ok(value) => {
if let Ok(url) = url::Url::parse(&value) {
url
} else {
anyhow::bail!("Failed to parse URL from environment variable. Please make sure your API endpoint URL is valid.")
}
}
Err(_) => return Ok(Environment::Production),
};
Ok(Environment::Custom(env_hostname))
}
pub fn cf_v4_client(user: &GlobalUser) -> Result<HttpApiClient> {
let config = HttpApiClientConfig {
http_timeout: Duration::from_secs(DEFAULT_HTTP_TIMEOUT_SECONDS),
default_headers: headers(None),
};
let environment = get_environment()?;
HttpApiClient::new(Credentials::from(user.to_owned()), config, environment)
}
pub fn cf_v4_api_client_async(user: &GlobalUser) -> Result<async_api::Client> {
let config = HttpApiClientConfig {
http_timeout: Duration::from_secs(DEFAULT_HTTP_TIMEOUT_SECONDS),
default_headers: headers(None),
};
let environment = get_environment()?;
async_api::Client::new(Credentials::from(user.to_owned()), config, environment)
}
pub fn format_error(e: ApiFailure, err_helper: Option<&dyn Fn(u16) -> &'static str>) -> String {
match e {
ApiFailure::Error(status, api_errors) => {
print_status_code_context(status);
let mut complete_err = "".to_string();
for error in api_errors.errors {
let error_msg = format!("{} Code {}: {}\n", emoji::WARN, error.code, error.message);
if let Some(annotate_help) = err_helper {
let suggestion_text = annotate_help(error.code);
let help_msg = format!("{} {}\n", emoji::SLEUTH, suggestion_text);
complete_err.push_str(&format!("{}{}", error_msg, help_msg));
} else {
complete_err.push_str(&error_msg)
}
}
complete_err.trim_end().to_string() }
ApiFailure::Invalid(reqwest_err) => format!("{} Error: {}", emoji::WARN, reqwest_err),
}
}
fn print_status_code_context(status_code: StatusCode) {
match status_code {
StatusCode::PAYLOAD_TOO_LARGE => StdOut::warn("Returned status code 413, Payload Too Large. Please make sure your upload is less than 100MB in size"),
StatusCode::GATEWAY_TIMEOUT => StdOut::warn("Returned status code 504, Gateway Timeout. Please try again in a few seconds"),
_ => (),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gets_environment_tests() {
let url = "https://github.com/cloudflare/wrangler-legacy";
env::set_var(CF_API_BASE_URL, url);
let test_environment_url = url::Url::from(&get_environment().unwrap());
let expected_environment_url = url::Url::parse(url).unwrap();
assert_eq!(test_environment_url, expected_environment_url);
env::remove_var(CF_API_BASE_URL);
let url = "thisisaninvalidurl";
env::set_var(CF_API_BASE_URL, url);
let test_environment = get_environment();
assert!(test_environment.is_err());
env::remove_var(CF_API_BASE_URL);
env::remove_var(CF_API_BASE_URL);
let test_environment_url = url::Url::from(&get_environment().unwrap());
let expected_environment_url = url::Url::from(&Environment::Production);
assert_eq!(test_environment_url, expected_environment_url);
}
}