aws_smithy_runtime/client/
endpoint.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Code for applying endpoints to a request.
7
8use aws_smithy_runtime_api::client::endpoint::{error::InvalidEndpointError, EndpointPrefix};
9use std::borrow::Cow;
10use std::result::Result as StdResult;
11use std::str::FromStr;
12
13/// Apply `endpoint` to `uri`
14///
15/// This method mutates `uri` by setting the `endpoint` on it
16pub fn apply_endpoint(
17    uri: &mut http_02x::Uri,
18    endpoint: &http_02x::Uri,
19    prefix: Option<&EndpointPrefix>,
20) -> StdResult<(), InvalidEndpointError> {
21    let prefix = prefix.map(EndpointPrefix::as_str).unwrap_or("");
22    let authority = endpoint
23        .authority()
24        .as_ref()
25        .map(|auth| auth.as_str())
26        .unwrap_or("");
27    let authority = if !prefix.is_empty() {
28        Cow::Owned(format!("{}{}", prefix, authority))
29    } else {
30        Cow::Borrowed(authority)
31    };
32    let authority = http_02x::uri::Authority::from_str(&authority).map_err(|err| {
33        InvalidEndpointError::failed_to_construct_authority(authority.into_owned(), err)
34    })?;
35    let scheme = *endpoint
36        .scheme()
37        .as_ref()
38        .ok_or_else(InvalidEndpointError::endpoint_must_have_scheme)?;
39    let new_uri = http_02x::Uri::builder()
40        .authority(authority)
41        .scheme(scheme.clone())
42        .path_and_query(merge_paths(endpoint, uri).as_ref())
43        .build()
44        .map_err(InvalidEndpointError::failed_to_construct_uri)?;
45    *uri = new_uri;
46    Ok(())
47}
48
49fn merge_paths<'a>(endpoint: &'a http_02x::Uri, uri: &'a http_02x::Uri) -> Cow<'a, str> {
50    if let Some(query) = endpoint.path_and_query().and_then(|pq| pq.query()) {
51        tracing::warn!(query = %query, "query specified in endpoint will be ignored during endpoint resolution");
52    }
53    let endpoint_path = endpoint.path();
54    let uri_path_and_query = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("");
55    if endpoint_path.is_empty() {
56        Cow::Borrowed(uri_path_and_query)
57    } else {
58        let ep_no_slash = endpoint_path.strip_suffix('/').unwrap_or(endpoint_path);
59        let uri_path_no_slash = uri_path_and_query
60            .strip_prefix('/')
61            .unwrap_or(uri_path_and_query);
62        Cow::Owned(format!("{}/{}", ep_no_slash, uri_path_no_slash))
63    }
64}