Skip to main content

aws_sdk_context/config/
endpoint.rs

1// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
2pub use ::aws_smithy_runtime_api::client::endpoint::EndpointFuture;
3pub use ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver;
4pub use ::aws_smithy_types::endpoint::Endpoint;
5
6/// Interceptor that tracks endpoint override business metric.
7#[derive(Debug, Default)]
8pub(crate) struct EndpointOverrideFeatureTrackerInterceptor;
9
10#[::aws_smithy_runtime_api::client::interceptors::dyn_dispatch_hint]
11impl ::aws_smithy_runtime_api::client::interceptors::Intercept for EndpointOverrideFeatureTrackerInterceptor {
12    fn name(&self) -> &'static str {
13        "EndpointOverrideFeatureTrackerInterceptor"
14    }
15
16    fn read_before_execution(
17        &self,
18        _context: &::aws_smithy_runtime_api::client::interceptors::context::BeforeSerializationInterceptorContextRef<'_>,
19        cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
20    ) -> ::std::result::Result<(), ::aws_smithy_runtime_api::box_error::BoxError> {
21        if cfg.load::<::aws_types::endpoint_config::EndpointUrl>().is_some() {
22            cfg.interceptor_state()
23                .store_append(::aws_runtime::sdk_feature::AwsSdkFeature::EndpointOverride);
24        }
25        ::std::result::Result::Ok(())
26    }
27}
28
29#[cfg(test)]
30mod test {
31
32    /// For custom endpoint with region not set and fips disabled
33    #[test]
34    fn test_1() {
35        let params = crate::config::endpoint::Params::builder()
36            .endpoint("https://example.com".to_string())
37            .use_fips(false)
38            .build_without_validators()
39            .expect("invalid params");
40        let resolver = crate::config::endpoint::DefaultResolver::new();
41        let endpoint = resolver.resolve_endpoint(&params);
42        let endpoint = endpoint.expect("Expected valid endpoint: https://example.com");
43        assert_eq!(
44            endpoint,
45            ::aws_smithy_types::endpoint::Endpoint::builder().url("https://example.com").build()
46        );
47    }
48
49    /// For custom endpoint with fips enabled
50    #[test]
51    fn test_2() {
52        let params = crate::config::endpoint::Params::builder()
53            .endpoint("https://example.com".to_string())
54            .use_fips(true)
55            .build_without_validators()
56            .expect("invalid params");
57        let resolver = crate::config::endpoint::DefaultResolver::new();
58        let endpoint = resolver.resolve_endpoint(&params);
59        let error = endpoint
60            .expect_err("expected error: Invalid Configuration: FIPS and custom endpoint are not supported [For custom endpoint with fips enabled]");
61        assert_eq!(format!("{}", error), "Invalid Configuration: FIPS and custom endpoint are not supported")
62    }
63
64    /// For region us-east-1 with FIPS enabled and DualStack enabled
65    #[test]
66    fn test_3() {
67        let params = crate::config::endpoint::Params::builder()
68            .region("us-east-1".to_string())
69            .use_fips(true)
70            .build_without_validators()
71            .expect("invalid params");
72        let resolver = crate::config::endpoint::DefaultResolver::new();
73        let endpoint = resolver.resolve_endpoint(&params);
74        let endpoint = endpoint.expect("Expected valid endpoint: https://context-fips.us-east-1.api.aws");
75        assert_eq!(
76            endpoint,
77            ::aws_smithy_types::endpoint::Endpoint::builder()
78                .url("https://context-fips.us-east-1.api.aws")
79                .build()
80        );
81    }
82
83    /// For region us-east-1 with FIPS disabled and DualStack enabled
84    #[test]
85    fn test_4() {
86        let params = crate::config::endpoint::Params::builder()
87            .region("us-east-1".to_string())
88            .use_fips(false)
89            .build_without_validators()
90            .expect("invalid params");
91        let resolver = crate::config::endpoint::DefaultResolver::new();
92        let endpoint = resolver.resolve_endpoint(&params);
93        let endpoint = endpoint.expect("Expected valid endpoint: https://context.us-east-1.api.aws");
94        assert_eq!(
95            endpoint,
96            ::aws_smithy_types::endpoint::Endpoint::builder()
97                .url("https://context.us-east-1.api.aws")
98                .build()
99        );
100    }
101
102    /// For region cn-northwest-1 with FIPS enabled and DualStack enabled
103    #[test]
104    fn test_5() {
105        let params = crate::config::endpoint::Params::builder()
106            .region("cn-northwest-1".to_string())
107            .use_fips(true)
108            .build_without_validators()
109            .expect("invalid params");
110        let resolver = crate::config::endpoint::DefaultResolver::new();
111        let endpoint = resolver.resolve_endpoint(&params);
112        let endpoint = endpoint.expect("Expected valid endpoint: https://context-fips.cn-northwest-1.api.amazonwebservices.com.cn");
113        assert_eq!(
114            endpoint,
115            ::aws_smithy_types::endpoint::Endpoint::builder()
116                .url("https://context-fips.cn-northwest-1.api.amazonwebservices.com.cn")
117                .build()
118        );
119    }
120
121    /// For region cn-northwest-1 with FIPS disabled and DualStack enabled
122    #[test]
123    fn test_6() {
124        let params = crate::config::endpoint::Params::builder()
125            .region("cn-northwest-1".to_string())
126            .use_fips(false)
127            .build_without_validators()
128            .expect("invalid params");
129        let resolver = crate::config::endpoint::DefaultResolver::new();
130        let endpoint = resolver.resolve_endpoint(&params);
131        let endpoint = endpoint.expect("Expected valid endpoint: https://context.cn-northwest-1.api.amazonwebservices.com.cn");
132        assert_eq!(
133            endpoint,
134            ::aws_smithy_types::endpoint::Endpoint::builder()
135                .url("https://context.cn-northwest-1.api.amazonwebservices.com.cn")
136                .build()
137        );
138    }
139
140    /// For region us-gov-west-1 with FIPS enabled and DualStack enabled
141    #[test]
142    fn test_7() {
143        let params = crate::config::endpoint::Params::builder()
144            .region("us-gov-west-1".to_string())
145            .use_fips(true)
146            .build_without_validators()
147            .expect("invalid params");
148        let resolver = crate::config::endpoint::DefaultResolver::new();
149        let endpoint = resolver.resolve_endpoint(&params);
150        let endpoint = endpoint.expect("Expected valid endpoint: https://context-fips.us-gov-west-1.api.aws");
151        assert_eq!(
152            endpoint,
153            ::aws_smithy_types::endpoint::Endpoint::builder()
154                .url("https://context-fips.us-gov-west-1.api.aws")
155                .build()
156        );
157    }
158
159    /// For region us-gov-west-1 with FIPS disabled and DualStack enabled
160    #[test]
161    fn test_8() {
162        let params = crate::config::endpoint::Params::builder()
163            .region("us-gov-west-1".to_string())
164            .use_fips(false)
165            .build_without_validators()
166            .expect("invalid params");
167        let resolver = crate::config::endpoint::DefaultResolver::new();
168        let endpoint = resolver.resolve_endpoint(&params);
169        let endpoint = endpoint.expect("Expected valid endpoint: https://context.us-gov-west-1.api.aws");
170        assert_eq!(
171            endpoint,
172            ::aws_smithy_types::endpoint::Endpoint::builder()
173                .url("https://context.us-gov-west-1.api.aws")
174                .build()
175        );
176    }
177
178    /// Missing region
179    #[test]
180    fn test_9() {
181        let params = crate::config::endpoint::Params::builder()
182            .build_without_validators()
183            .expect("invalid params");
184        let resolver = crate::config::endpoint::DefaultResolver::new();
185        let endpoint = resolver.resolve_endpoint(&params);
186        let error = endpoint.expect_err("expected error: Invalid Configuration: Missing Region [Missing region]");
187        assert_eq!(format!("{}", error), "Invalid Configuration: Missing Region")
188    }
189}
190
191/// Endpoint resolver trait specific to AWS Context
192pub trait ResolveEndpoint: ::std::marker::Send + ::std::marker::Sync + ::std::fmt::Debug {
193    /// Resolve an endpoint with the given parameters
194    fn resolve_endpoint<'a>(&'a self, params: &'a crate::config::endpoint::Params) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a>;
195
196    /// Convert this service-specific resolver into a `SharedEndpointResolver`
197    ///
198    /// The resulting resolver will downcast `EndpointResolverParams` into `crate::config::endpoint::Params`.
199    fn into_shared_resolver(self) -> ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver
200    where
201        Self: Sized + 'static,
202    {
203        ::aws_smithy_runtime_api::client::endpoint::SharedEndpointResolver::new(DowncastParams(self))
204    }
205}
206
207#[derive(Debug)]
208struct DowncastParams<T>(T);
209impl<T> ::aws_smithy_runtime_api::client::endpoint::ResolveEndpoint for DowncastParams<T>
210where
211    T: ResolveEndpoint,
212{
213    fn resolve_endpoint<'a>(
214        &'a self,
215        params: &'a ::aws_smithy_runtime_api::client::endpoint::EndpointResolverParams,
216    ) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a> {
217        let ep = match params.get::<crate::config::endpoint::Params>() {
218            Some(params) => self.0.resolve_endpoint(params),
219            None => ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(Err("params of expected type was not present".into())),
220        };
221        ep
222    }
223}
224
225#[derive(Debug)]
226/// The default endpoint resolver.
227pub struct DefaultResolver {
228    partition_resolver: &'static crate::endpoint_lib::partition::PartitionResolver,
229    endpoint_cache: ::arc_swap::ArcSwap<::std::option::Option<(Params, ::aws_smithy_types::endpoint::Endpoint)>>,
230}
231
232impl Default for DefaultResolver {
233    fn default() -> Self {
234        Self::new()
235    }
236}
237
238impl DefaultResolver {
239    /// Create a new DefaultResolver
240    pub fn new() -> Self {
241        Self {
242            partition_resolver: &crate::endpoint_lib::DEFAULT_PARTITION_RESOLVER,
243            endpoint_cache: ::arc_swap::ArcSwap::from_pointee(None),
244        }
245    }
246
247    #[allow(
248        unused_variables,
249        unused_parens,
250        clippy::double_parens,
251        clippy::useless_conversion,
252        clippy::bool_comparison,
253        clippy::comparison_to_empty,
254        clippy::needless_borrow,
255        clippy::useless_asref,
256        clippy::redundant_closure_call,
257        clippy::clone_on_copy,
258        clippy::single_char_add_str
259    )]
260    fn resolve_endpoint<'a>(
261        &'a self,
262        params: &'a crate::config::endpoint::Params,
263    ) -> ::std::result::Result<::aws_smithy_types::endpoint::Endpoint, ::aws_smithy_runtime_api::box_error::BoxError> {
264        let mut _diagnostic_collector = crate::endpoint_lib::diagnostic::DiagnosticCollector::new();
265        #[allow(unused_mut)]
266        let mut context = ConditionContext::default();
267
268        // Param bindings
269        let use_fips = &params.use_fips;
270        let endpoint = &params.endpoint;
271        let region = &params.region;
272
273        let mut current_ref: i32 = 2;
274        loop {
275            match current_ref {
276                ref_val if ref_val >= 100_000_000 => {
277                    return match (ref_val - 100_000_000) as usize {
278                        0 => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
279                            "No endpoint rule matched",
280                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
281                        1 => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
282                            "Invalid Configuration: FIPS and custom endpoint are not supported".to_string(),
283                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
284                        2 => {
285                            let endpoint = params.endpoint.as_deref().unwrap_or_default();
286                            ::std::result::Result::Ok(::aws_smithy_types::endpoint::Endpoint::builder().url(endpoint.to_owned()).build())
287                        }
288                        3 => {
289                            let region = params.region.as_deref().unwrap_or_default();
290                            let partition_result = context.partition_result.as_ref().expect("Guaranteed to have a value by earlier checks.");
291                            ::std::result::Result::Ok(
292                                ::aws_smithy_types::endpoint::Endpoint::builder()
293                                    .url({
294                                        let mut out = String::new();
295                                        out.push_str("https://context-fips.");
296                                        #[allow(clippy::needless_borrow)]
297                                        out.push_str(&region.as_ref());
298                                        out.push_str(".");
299                                        #[allow(clippy::needless_borrow)]
300                                        out.push_str(&partition_result.dual_stack_dns_suffix());
301                                        out
302                                    })
303                                    .build(),
304                            )
305                        }
306                        4 => {
307                            let region = params.region.as_deref().unwrap_or_default();
308                            let partition_result = context.partition_result.as_ref().expect("Guaranteed to have a value by earlier checks.");
309                            ::std::result::Result::Ok(
310                                ::aws_smithy_types::endpoint::Endpoint::builder()
311                                    .url({
312                                        let mut out = String::new();
313                                        out.push_str("https://context.");
314                                        #[allow(clippy::needless_borrow)]
315                                        out.push_str(&region.as_ref());
316                                        out.push_str(".");
317                                        #[allow(clippy::needless_borrow)]
318                                        out.push_str(&partition_result.dual_stack_dns_suffix());
319                                        out
320                                    })
321                                    .build(),
322                            )
323                        }
324                        5 => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
325                            "Invalid Configuration: Missing Region".to_string(),
326                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
327                        _ => ::std::result::Result::Err(Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message(
328                            "No endpoint rule matched",
329                        )) as ::aws_smithy_runtime_api::box_error::BoxError),
330                    };
331                }
332                1 | -1 => {
333                    return ::std::result::Result::Err(
334                        Box::new(::aws_smithy_http::endpoint::ResolveEndpointError::message("No endpoint rule matched"))
335                            as ::aws_smithy_runtime_api::box_error::BoxError,
336                    )
337                }
338                ref_val => {
339                    let is_complement = ref_val < 0;
340                    let node = &NODES[(ref_val.unsigned_abs() as usize) - 1];
341                    let condition_result = match node.condition_index {
342                        0 => endpoint.is_some(),
343                        1 => region.is_some(),
344                        2 => (|_diagnostic_collector: &mut crate::endpoint_lib::diagnostic::DiagnosticCollector| -> bool {
345                            let partition_result = &mut context.partition_result;
346                            let partition_resolver = &self.partition_resolver;
347                            {
348                                *partition_result = partition_resolver
349                                    .resolve_partition(if let Some(param) = region { param } else { return false }, _diagnostic_collector)
350                                    .map(|inner| inner.into());
351                                partition_result.is_some()
352                            }
353                        })(&mut _diagnostic_collector),
354                        3 => (use_fips) == (&true),
355                        _ => unreachable!("Invalid condition index"),
356                    };
357                    current_ref = if is_complement ^ condition_result { node.high_ref } else { node.low_ref };
358                }
359            }
360        }
361    }
362}
363
364impl crate::config::endpoint::ResolveEndpoint for DefaultResolver {
365    fn resolve_endpoint<'a>(&'a self, params: &'a crate::config::endpoint::Params) -> ::aws_smithy_runtime_api::client::endpoint::EndpointFuture<'a> {
366        // Check single-entry cache (lock-free read via ArcSwap)
367        let cached = self.endpoint_cache.load();
368        if let Some((cached_params, cached_endpoint)) = cached.as_ref() {
369            if cached_params == params {
370                return ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(::std::result::Result::Ok(cached_endpoint.clone()));
371            }
372        }
373        drop(cached);
374        let result = self.resolve_endpoint(params);
375        if let ::std::result::Result::Ok(ref endpoint) = result {
376            self.endpoint_cache.store(::std::sync::Arc::new(Some((params.clone(), endpoint.clone()))));
377        }
378        ::aws_smithy_runtime_api::client::endpoint::EndpointFuture::ready(result)
379    }
380}
381const NODES: [crate::endpoint_lib::bdd_interpreter::BddNode; 6] = [
382    crate::endpoint_lib::bdd_interpreter::BddNode {
383        condition_index: -1,
384        high_ref: 1,
385        low_ref: -1,
386    },
387    crate::endpoint_lib::bdd_interpreter::BddNode {
388        condition_index: 0,
389        high_ref: 6,
390        low_ref: 3,
391    },
392    crate::endpoint_lib::bdd_interpreter::BddNode {
393        condition_index: 1,
394        high_ref: 4,
395        low_ref: 100000005,
396    },
397    crate::endpoint_lib::bdd_interpreter::BddNode {
398        condition_index: 2,
399        high_ref: 5,
400        low_ref: 100000005,
401    },
402    crate::endpoint_lib::bdd_interpreter::BddNode {
403        condition_index: 3,
404        high_ref: 100000003,
405        low_ref: 100000004,
406    },
407    crate::endpoint_lib::bdd_interpreter::BddNode {
408        condition_index: 3,
409        high_ref: 100000001,
410        low_ref: 100000002,
411    },
412];
413// These are all optional since they are set by conditions and will
414// all be unset when we start evaluation
415#[derive(Default)]
416#[allow(unused_lifetimes)]
417pub(crate) struct ConditionContext<'a> {
418    pub(crate) partition_result: Option<crate::endpoint_lib::partition::Partition<'a>>,
419    // Sometimes none of the members reference the lifetime, this makes it still valid
420    phantom: std::marker::PhantomData<&'a ()>,
421}
422
423#[non_exhaustive]
424#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)]
425/// Configuration parameters for resolving the correct endpoint
426pub struct Params {
427    /// When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.
428    pub(crate) use_fips: bool,
429    /// Override the endpoint used to send this request
430    pub(crate) endpoint: ::std::option::Option<::std::string::String>,
431    /// The AWS region used to dispatch the request.
432    pub(crate) region: ::std::option::Option<::std::string::String>,
433}
434impl Params {
435    /// Create a builder for [`Params`]
436    pub fn builder() -> crate::config::endpoint::ParamsBuilder {
437        crate::config::endpoint::ParamsBuilder::default()
438    }
439    /// When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.
440    pub fn use_fips(&self) -> ::std::option::Option<bool> {
441        Some(self.use_fips)
442    }
443    /// Override the endpoint used to send this request
444    pub fn endpoint(&self) -> ::std::option::Option<&str> {
445        self.endpoint.as_deref()
446    }
447    /// The AWS region used to dispatch the request.
448    pub fn region(&self) -> ::std::option::Option<&str> {
449        self.region.as_deref()
450    }
451}
452
453/// Builder for [`Params`]
454#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug)]
455pub struct ParamsBuilder {
456    use_fips: ::std::option::Option<bool>,
457    endpoint: ::std::option::Option<::std::string::String>,
458    region: ::std::option::Option<::std::string::String>,
459}
460impl ParamsBuilder {
461    /// Consume this builder, creating [`Params`].
462    pub fn build(self) -> ::std::result::Result<crate::config::endpoint::Params, crate::config::endpoint::InvalidParams> {
463        if let Some(region) = &self.region {
464            if !crate::endpoint_lib::host::is_valid_host_label(
465                region.as_ref() as &str,
466                true,
467                &mut crate::endpoint_lib::diagnostic::DiagnosticCollector::new(),
468            ) {
469                return Err(crate::config::endpoint::InvalidParams::invalid_value(
470                    "region",
471                    "must be a valid host label",
472                ));
473            }
474        };
475        self.build_without_validators()
476    }
477    /// Consume this builder, creating [`Params`] without the validators run by `build()`.
478    ///
479    /// Endpoint rule-set tests use this so they test the rules as the model defines them.
480    fn build_without_validators(self) -> ::std::result::Result<crate::config::endpoint::Params, crate::config::endpoint::InvalidParams> {
481        Ok(
482            #[allow(clippy::unnecessary_lazy_evaluations)]
483            crate::config::endpoint::Params {
484                use_fips: self
485                    .use_fips
486                    .or_else(|| Some(false))
487                    .ok_or_else(|| crate::config::endpoint::InvalidParams::missing("use_fips"))?,
488                endpoint: self.endpoint,
489                region: self.region,
490            },
491        )
492    }
493    /// Sets the value for use_fips
494    ///
495    /// When unset, this parameter has a default value of `false`.
496    /// When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.
497    pub fn use_fips(mut self, value: impl Into<bool>) -> Self {
498        self.use_fips = Some(value.into());
499        self
500    }
501
502    /// Sets the value for use_fips
503    ///
504    /// When unset, this parameter has a default value of `false`.
505    /// When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.
506    pub fn set_use_fips(mut self, param: Option<bool>) -> Self {
507        self.use_fips = param;
508        self
509    }
510    /// Sets the value for endpoint
511    ///
512    /// Override the endpoint used to send this request
513    pub fn endpoint(mut self, value: impl Into<::std::string::String>) -> Self {
514        self.endpoint = Some(value.into());
515        self
516    }
517
518    /// Sets the value for endpoint
519    ///
520    /// Override the endpoint used to send this request
521    pub fn set_endpoint(mut self, param: Option<::std::string::String>) -> Self {
522        self.endpoint = param;
523        self
524    }
525    /// Sets the value for region
526    ///
527    /// The AWS region used to dispatch the request.
528    pub fn region(mut self, value: impl Into<::std::string::String>) -> Self {
529        self.region = Some(value.into());
530        self
531    }
532
533    /// Sets the value for region
534    ///
535    /// The AWS region used to dispatch the request.
536    pub fn set_region(mut self, param: Option<::std::string::String>) -> Self {
537        self.region = param;
538        self
539    }
540}
541
542/// An error that occurred during endpoint resolution
543#[derive(Debug)]
544pub struct InvalidParams {
545    field: std::borrow::Cow<'static, str>,
546    kind: InvalidParamsErrorKind,
547}
548
549/// The kind of invalid parameter error
550#[derive(Debug)]
551enum InvalidParamsErrorKind {
552    MissingField,
553    InvalidValue { message: &'static str },
554}
555
556impl InvalidParams {
557    #[allow(dead_code)]
558    fn missing(field: &'static str) -> Self {
559        Self {
560            field: field.into(),
561            kind: InvalidParamsErrorKind::MissingField,
562        }
563    }
564
565    #[allow(dead_code)]
566    fn invalid_value(field: &'static str, message: &'static str) -> Self {
567        Self {
568            field: field.into(),
569            kind: InvalidParamsErrorKind::InvalidValue { message },
570        }
571    }
572}
573
574impl std::fmt::Display for InvalidParams {
575    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
576        match self.kind {
577            InvalidParamsErrorKind::MissingField => write!(f, "a required field was missing: `{}`", self.field),
578            InvalidParamsErrorKind::InvalidValue { message } => write!(f, "invalid value for field: `{}` - {}", self.field, message),
579        }
580    }
581}
582
583impl std::error::Error for InvalidParams {}