aws-sdk-agentregistry 1.0.0

AWS SDK for Agent Registry
Documentation
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub use ::aws_smithy_runtime_api::client::endpoint::EndpointFuture;
pub use ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver;
pub use ::aws_smithy_types::endpoint::Endpoint;

/// Interceptor that tracks endpoint override business metric.
#[derive(Debug, Default)]
pub(crate) struct EndpointOverrideFeatureTrackerInterceptor;

#[::aws_smithy_runtime_api::client::interceptors::dyn_dispatch_hint]
impl ::aws_smithy_runtime_api::client::interceptors::Intercept for EndpointOverrideFeatureTrackerInterceptor {
    fn name(&self) -> &'static str {
        "EndpointOverrideFeatureTrackerInterceptor"
    }

    fn read_before_execution(
        &self,
        _context: &::aws_smithy_runtime_api::client::interceptors::context::BeforeSerializationInterceptorContextRef<'_>,
        cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
    ) -> ::std::result::Result<(), ::aws_smithy_runtime_api::box_error::BoxError> {
        if cfg.load::<::aws_types::endpoint_config::EndpointUrl>().is_some() {
            cfg.interceptor_state()
                .store_append(::aws_runtime::sdk_feature::AwsSdkFeature::EndpointOverride);
        }
        ::std::result::Result::Ok(())
    }
}

#[cfg(test)]
mod test {

    /// Region us-west-2 -> region-based prod host.
    #[test]
    fn test_1() {
        let params = crate::config::endpoint::Params::builder()
            .region("us-west-2".to_string())
            .build()
            .expect("invalid params");
        let resolver = crate::config::endpoint::DefaultResolver::new();
        let endpoint = resolver.resolve_endpoint(&params);
        let endpoint = endpoint.expect("Expected valid endpoint: https://agent-registry.us-west-2.api.aws");
        assert_eq!(
            endpoint,
            ::aws_smithy_types::endpoint::Endpoint::builder()
                .url("https://agent-registry.us-west-2.api.aws")
                .build()
        );
    }

    /// Region us-east-1 -> region-based prod host.
    #[test]
    fn test_2() {
        let params = crate::config::endpoint::Params::builder()
            .region("us-east-1".to_string())
            .build()
            .expect("invalid params");
        let resolver = crate::config::endpoint::DefaultResolver::new();
        let endpoint = resolver.resolve_endpoint(&params);
        let endpoint = endpoint.expect("Expected valid endpoint: https://agent-registry.us-east-1.api.aws");
        assert_eq!(
            endpoint,
            ::aws_smithy_types::endpoint::Endpoint::builder()
                .url("https://agent-registry.us-east-1.api.aws")
                .build()
        );
    }

    /// Endpoint override wins over region.
    #[test]
    fn test_3() {
        let params = crate::config::endpoint::Params::builder()
            .region("us-west-2".to_string())
            .endpoint("https://custom.example.aws.dev".to_string())
            .build()
            .expect("invalid params");
        let resolver = crate::config::endpoint::DefaultResolver::new();
        let endpoint = resolver.resolve_endpoint(&params);
        let endpoint = endpoint.expect("Expected valid endpoint: https://custom.example.aws.dev");
        assert_eq!(
            endpoint,
            ::aws_smithy_types::endpoint::Endpoint::builder()
                .url("https://custom.example.aws.dev")
                .build()
        );
    }
}

/// Endpoint resolver trait specific to Agent Registry
pub trait ResolveEndpoint: ::std::marker::Send + ::std::marker::Sync + ::std::fmt::Debug {
    /// Resolve an endpoint with the given parameters
    fn resolve_endpoint<'a>(&'a self, params: &'a crate::config::endpoint::Params) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a>;

    /// Convert this service-specific resolver into a `SharedEndpointResolver`
    ///
    /// The resulting resolver will downcast `EndpointResolverParams` into `crate::config::endpoint::Params`.
    fn into_shared_resolver(self) -> ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver
    where
        Self: Sized + 'static,
    {
        ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver::new(DowncastParams(self))
    }
}

#[derive(Debug)]
struct DowncastParams<T>(T);
impl<T> ::aws_smithy_runtime_api::client::endpoint::ResolveEndpoint for DowncastParams<T>
where
    T: ResolveEndpoint,
{
    fn resolve_endpoint<'a>(
        &'a self,
        params: &'a ::aws_smithy_runtime_api::client::endpoint::EndpointResolverParams,
    ) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a> {
        let ep = match params.get::<crate::config::endpoint::Params>() {
            Some(params) => self.0.resolve_endpoint(params),
            None => ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(Err("params of expected type was not present".into())),
        };
        ep
    }
}

#[derive(Debug)]
/// The default endpoint resolver.
pub struct DefaultResolver {
    endpoint_cache: ::arc_swap::ArcSwap<::std::option::Option<(Params, ::aws_smithy_types::endpoint::Endpoint)>>,
}

impl Default for DefaultResolver {
    fn default() -> Self {
        Self::new()
    }
}

impl DefaultResolver {
    /// Create a new DefaultResolver
    pub fn new() -> Self {
        Self {
            endpoint_cache: ::arc_swap::ArcSwap::from_pointee(None),
        }
    }

    #[allow(
        unused_variables,
        unused_parens,
        clippy::double_parens,
        clippy::useless_conversion,
        clippy::bool_comparison,
        clippy::comparison_to_empty,
        clippy::needless_borrow,
        clippy::useless_asref,
        clippy::redundant_closure_call,
        clippy::clone_on_copy,
        clippy::single_char_add_str
    )]
    fn resolve_endpoint<'a>(
        &'a self,
        params: &'a crate::config::endpoint::Params,
    ) -> ::std::result::Result<::aws_smithy_types::endpoint::Endpoint, ::aws_smithy_runtime_api::box_error::BoxError> {
        let mut _diagnostic_collector = crate::endpoint_lib::diagnostic::DiagnosticCollector::new();
        #[allow(unused_mut)]
        let mut context = ConditionContext::default();

        // Param bindings
        let region = &params.region;
        let endpoint = &params.endpoint;

        let mut current_ref: i32 = 2;
        loop {
            match current_ref {
                ref_val if ref_val >= 100_000_000 => {
                    return match (ref_val - 100_000_000) as usize {
                        0 => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
                            "No endpoint rule matched",
                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
                        1 => {
                            let endpoint = params.endpoint.as_deref().unwrap_or_default();
                            ::std::result::Result::Ok(::aws_smithy_types::endpoint::Endpoint::builder().url(endpoint.to_owned()).build())
                        }
                        2 => {
                            let region = params.region.as_deref().unwrap_or_default();
                            ::std::result::Result::Ok(
                                ::aws_smithy_types::endpoint::Endpoint::builder()
                                    .url({
                                        let mut out = String::new();
                                        out.push_str("https://agent-registry.");
                                        #[allow(clippy::needless_borrow)]
                                        out.push_str(&region.as_ref());
                                        out.push_str(".api.aws");
                                        out
                                    })
                                    .build(),
                            )
                        }
                        3 => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
                            "Unable to resolve an Agent Registry endpoint: Region was not set and no explicit Endpoint override was provided."
                                .to_string(),
                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
                        _ => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
                            "No endpoint rule matched",
                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
                    };
                }
                1 | -1 => {
                    return ::std::result::Result::Err(
                        Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message("No endpoint rule matched"))
                            as ::aws_smithy_runtime_api::box_error::BoxError,
                    )
                }
                ref_val => {
                    let is_complement = ref_val < 0;
                    let node = &NODES[(ref_val.unsigned_abs() as usize) - 1];
                    let condition_result = match node.condition_index {
                        0 => endpoint.is_some(),
                        1 => region.is_some(),
                        _ => unreachable!("Invalid condition index"),
                    };
                    current_ref = if is_complement ^ condition_result { node.high_ref } else { node.low_ref };
                }
            }
        }
    }
}

impl crate::config::endpoint::ResolveEndpoint for DefaultResolver {
    fn resolve_endpoint<'a>(&'a self, params: &'a crate::config::endpoint::Params) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a> {
        // Check single-entry cache (lock-free read via ArcSwap)
        let cached = self.endpoint_cache.load();
        if let Some((cached_params, cached_endpoint)) = cached.as_ref() {
            if cached_params == params {
                return ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(::std::result::Result::Ok(cached_endpoint.clone()));
            }
        }
        drop(cached);
        let result = self.resolve_endpoint(params);
        if let ::std::result::Result::Ok(ref endpoint) = result {
            self.endpoint_cache.store(::std::sync::Arc::new(Some((params.clone(), endpoint.clone()))));
        }
        ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(result)
    }
}
const NODES: [crate::endpoint_lib::bdd_interpreter::BddNode; 3] = [
    crate::endpoint_lib::bdd_interpreter::BddNode {
        condition_index: -1,
        high_ref: 1,
        low_ref: -1,
    },
    crate::endpoint_lib::bdd_interpreter::BddNode {
        condition_index: 0,
        high_ref: 100000001,
        low_ref: 3,
    },
    crate::endpoint_lib::bdd_interpreter::BddNode {
        condition_index: 1,
        high_ref: 100000002,
        low_ref: 100000003,
    },
];
// These are all optional since they are set by conditions and will
// all be unset when we start evaluation
#[derive(Default)]
#[allow(unused_lifetimes)]
pub(crate) struct ConditionContext<'a> {
    // Sometimes none of the members reference the lifetime, this makes it still valid
    phantom: std::marker::PhantomData<&'a ()>,
}

#[non_exhaustive]
#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)]
/// Configuration parameters for resolving the correct endpoint
pub struct Params {
    /// The AWS region of the service.
    pub(crate) region: ::std::option::Option<::std::string::String>,
    /// Override the endpoint used to send requests.
    pub(crate) endpoint: ::std::option::Option<::std::string::String>,
}
impl Params {
    /// Create a builder for [`Params`]
    pub fn builder() -> crate::config::endpoint::ParamsBuilder {
        crate::config::endpoint::ParamsBuilder::default()
    }
    /// The AWS region of the service.
    pub fn region(&self) -> ::std::option::Option<&str> {
        self.region.as_deref()
    }
    /// Override the endpoint used to send requests.
    pub fn endpoint(&self) -> ::std::option::Option<&str> {
        self.endpoint.as_deref()
    }
}

/// Builder for [`Params`]
#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug)]
pub struct ParamsBuilder {
    region: ::std::option::Option<::std::string::String>,
    endpoint: ::std::option::Option<::std::string::String>,
}
impl ParamsBuilder {
    /// Consume this builder, creating [`Params`].
    pub fn build(self) -> ::std::result::Result<crate::config::endpoint::Params, crate::config::endpoint::InvalidParams> {
        if let Some(region) = &self.region {
            if !crate::endpoint_lib::host::is_valid_host_label(
                region.as_ref() as &str,
                true,
                &mut crate::endpoint_lib::diagnostic::DiagnosticCollector::new(),
            ) {
                return Err(crate::config::endpoint::InvalidParams::invalid_value(
                    "region",
                    "must be a valid host label",
                ));
            }
        };
        Ok(
            #[allow(clippy::unnecessary_lazy_evaluations)]
            crate::config::endpoint::Params {
                region: self.region,
                endpoint: self.endpoint,
            },
        )
    }
    /// Sets the value for region
    ///
    /// The AWS region of the service.
    pub fn region(mut self, value: impl Into<::std::string::String>) -> Self {
        self.region = Some(value.into());
        self
    }

    /// Sets the value for region
    ///
    /// The AWS region of the service.
    pub fn set_region(mut self, param: Option<::std::string::String>) -> Self {
        self.region = param;
        self
    }
    /// Sets the value for endpoint
    ///
    /// Override the endpoint used to send requests.
    pub fn endpoint(mut self, value: impl Into<::std::string::String>) -> Self {
        self.endpoint = Some(value.into());
        self
    }

    /// Sets the value for endpoint
    ///
    /// Override the endpoint used to send requests.
    pub fn set_endpoint(mut self, param: Option<::std::string::String>) -> Self {
        self.endpoint = param;
        self
    }
}

/// An error that occurred during endpoint resolution
#[derive(Debug)]
pub struct InvalidParams {
    field: std::borrow::Cow<'static, str>,
    kind: InvalidParamsErrorKind,
}

/// The kind of invalid parameter error
#[derive(Debug)]
enum InvalidParamsErrorKind {
    MissingField,
    InvalidValue { message: &'static str },
}

impl InvalidParams {
    #[allow(dead_code)]
    fn missing(field: &'static str) -> Self {
        Self {
            field: field.into(),
            kind: InvalidParamsErrorKind::MissingField,
        }
    }

    #[allow(dead_code)]
    fn invalid_value(field: &'static str, message: &'static str) -> Self {
        Self {
            field: field.into(),
            kind: InvalidParamsErrorKind::InvalidValue { message },
        }
    }
}

impl std::fmt::Display for InvalidParams {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            InvalidParamsErrorKind::MissingField => write!(f, "a required field was missing: `{}`", self.field),
            InvalidParamsErrorKind::InvalidValue { message } => write!(f, "invalid value for field: `{}` - {}", self.field, message),
        }
    }
}

impl std::error::Error for InvalidParams {}