use std::str::FromStr;
use aws_smithy_types::retry::{RetryConfigBuilder, RetryConfigErr, RetryMode};
use aws_types::os_shim_internal::{Env, Fs};
use crate::provider_config::ProviderConfig;
#[derive(Debug, Default)]
pub struct ProfileFileRetryConfigProvider {
fs: Fs,
env: Env,
profile_override: Option<String>,
}
#[derive(Default)]
pub struct Builder {
config: Option<ProviderConfig>,
profile_override: Option<String>,
}
impl Builder {
pub fn configure(mut self, config: &ProviderConfig) -> Self {
self.config = Some(config.clone());
self
}
pub fn profile_name(mut self, profile_name: impl Into<String>) -> Self {
self.profile_override = Some(profile_name.into());
self
}
pub fn build(self) -> ProfileFileRetryConfigProvider {
let conf = self.config.unwrap_or_default();
ProfileFileRetryConfigProvider {
env: conf.env(),
fs: conf.fs(),
profile_override: self.profile_override,
}
}
}
impl ProfileFileRetryConfigProvider {
pub fn new() -> Self {
Self {
fs: Fs::real(),
env: Env::real(),
profile_override: None,
}
}
pub fn builder() -> Builder {
Builder::default()
}
pub async fn retry_config_builder(&self) -> Result<RetryConfigBuilder, RetryConfigErr> {
let profile = match super::parser::load(&self.fs, &self.env).await {
Ok(profile) => profile,
Err(err) => {
tracing::warn!(err = %err, "failed to parse profile");
return Ok(RetryConfigBuilder::new());
}
};
let selected_profile = self
.profile_override
.as_deref()
.unwrap_or_else(|| profile.selected_profile());
let selected_profile = match profile.get_profile(selected_profile) {
Some(profile) => profile,
None => {
tracing::warn!("failed to get selected '{}' profile", selected_profile);
return Ok(RetryConfigBuilder::new());
}
};
let max_attempts = match selected_profile.get("max_attempts") {
Some(max_attempts) => match max_attempts.parse::<u32>() {
Ok(max_attempts) if max_attempts == 0 => {
return Err(RetryConfigErr::MaxAttemptsMustNotBeZero {
set_by: "aws profile".into(),
});
}
Ok(max_attempts) => Some(max_attempts),
Err(source) => {
return Err(RetryConfigErr::FailedToParseMaxAttempts {
set_by: "aws profile".into(),
source,
});
}
},
None => None,
};
let retry_mode = match selected_profile.get("retry_mode") {
Some(retry_mode) => match RetryMode::from_str(retry_mode) {
Ok(retry_mode) => Some(retry_mode),
Err(retry_mode_err) => {
return Err(RetryConfigErr::InvalidRetryMode {
set_by: "aws profile".into(),
source: retry_mode_err,
});
}
},
None => None,
};
let mut retry_config_builder = RetryConfigBuilder::new();
retry_config_builder
.set_max_attempts(max_attempts)
.set_mode(retry_mode);
Ok(retry_config_builder)
}
}