Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Endpoint panic-safety and ergonomics #1984

Merged
merged 5 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.next.toml
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,21 @@ Server SDKs now correctly reject operation inputs that don't set values for `req
references = ["smithy-rs#1714", "smithy-rs#1342", "smithy-rs#1860"]
meta = { "breaking" = true, "tada" = false, "bug" = true, "target" = "server" }
author = "david-perez"

[[aws-sdk-rust]]
message = "Functions on `aws_smithy_http::endpoint::Endpoint` now return a `Result` instead of panicking."
references = ["smithy-rs#1984", "smithy-rs#1496"]
meta = { "breaking" = true, "tada" = false, "bug" = false }
jdisanti marked this conversation as resolved.
Show resolved Hide resolved
author = "jdisanti"

[[aws-sdk-rust]]
message = "`Endpoint::mutable` now takes `impl AsRef<str>` instead of `Uri`. For the old functionality, use `Endpoint::mutable_uri`."
references = ["smithy-rs#1984", "smithy-rs#1496"]
meta = { "breaking" = true, "tada" = false, "bug" = false }
author = "jdisanti"

[[aws-sdk-rust]]
message = "`Endpoint::immutable` now takes `impl AsRef<str>` instead of `Uri`. For the old functionality, use `Endpoint::immutable_uri`."
references = ["smithy-rs#1984", "smithy-rs#1496"]
meta = { "breaking" = true, "tada" = false, "bug" = false }
author = "jdisanti"
7 changes: 5 additions & 2 deletions aws/rust-runtime/aws-config/src/ecs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,11 @@ impl Provider {
});
}
};
let endpoint = Endpoint::immutable(Uri::from_static(BASE_HOST));
endpoint.set_endpoint(&mut relative_uri, None);
let endpoint =
Endpoint::immutable_uri(Uri::from_static(BASE_HOST)).expect("BASE_HOST is valid");
endpoint
.set_endpoint(&mut relative_uri, None)
.expect("appending relative URLs to the ECS endpoint should always succeed");
Ok(relative_uri)
}
}
Expand Down
12 changes: 7 additions & 5 deletions aws/rust-runtime/aws-config/src/imds/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,10 @@ impl Client {
let mut base_uri: Uri = path.parse().map_err(|_| {
ImdsError::unexpected("IMDS path was not a valid URI. Hint: does it begin with `/`?")
})?;
self.inner.endpoint.set_endpoint(&mut base_uri, None);
self.inner
.endpoint
.set_endpoint(&mut base_uri, None)
.map_err(ImdsError::unexpected)?;
let request = http::Request::builder()
.uri(base_uri)
.body(SdkBody::empty())
Expand Down Expand Up @@ -433,7 +436,7 @@ impl Builder {
.endpoint
.unwrap_or_else(|| EndpointSource::Env(config.env(), config.fs()));
let endpoint = endpoint_source.endpoint(self.mode_override).await?;
let endpoint = Endpoint::immutable(endpoint);
let endpoint = Endpoint::immutable_uri(endpoint)?;
let retry_config = retry::Config::default()
.with_max_attempts(self.max_attempts.unwrap_or(DEFAULT_ATTEMPTS));
let token_loader = token::TokenMiddleware::new(
Expand Down Expand Up @@ -503,9 +506,8 @@ impl EndpointSource {
profile.get(profile_keys::ENDPOINT).map(Cow::Borrowed)
};
if let Some(uri) = uri_override {
return Ok(
Uri::try_from(uri.as_ref()).map_err(BuildErrorKind::InvalidEndpointUri)?
);
return Ok(Uri::try_from(uri.as_ref())
.map_err(|err| BuildErrorKind::InvalidEndpointUri(err.into()))?);
jdisanti marked this conversation as resolved.
Show resolved Hide resolved
}

// if not, load a endpoint mode from the environment
Expand Down
14 changes: 11 additions & 3 deletions aws/rust-runtime/aws-config/src/imds/client/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use crate::profile::credentials::ProfileFileError;
use aws_smithy_client::SdkError;
use aws_smithy_http::body::SdkBody;
use http::uri::InvalidUri;
use aws_smithy_http::endpoint::error::InvalidEndpointError;
use std::error::Error;
use std::fmt;

Expand Down Expand Up @@ -182,7 +182,7 @@ pub(super) enum BuildErrorKind {
InvalidProfile(ProfileFileError),

/// The specified endpoint was not a valid URI
InvalidEndpointUri(InvalidUri),
InvalidEndpointUri(Box<dyn Error + Send + Sync + 'static>),
}

/// Error constructing IMDSv2 Client
Expand All @@ -209,7 +209,7 @@ impl Error for BuildError {
match &self.kind {
InvalidEndpointMode(e) => Some(e),
InvalidProfile(e) => Some(e),
InvalidEndpointUri(e) => Some(e),
InvalidEndpointUri(e) => Some(e.as_ref()),
}
}
}
Expand All @@ -220,6 +220,14 @@ impl From<BuildErrorKind> for BuildError {
}
}

impl From<InvalidEndpointError> for BuildError {
fn from(err: InvalidEndpointError) -> Self {
Self {
kind: BuildErrorKind::InvalidEndpointUri(err.into()),
}
}
}

#[derive(Debug)]
pub(super) enum TokenErrorKind {
/// The token was invalid
Expand Down
4 changes: 3 additions & 1 deletion aws/rust-runtime/aws-config/src/imds/client/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,9 @@ impl TokenMiddleware {

async fn get_token(&self) -> Result<(Token, SystemTime), ImdsError> {
let mut uri = Uri::from_static("/latest/api/token");
self.endpoint.set_endpoint(&mut uri, None);
self.endpoint
.set_endpoint(&mut uri, None)
.map_err(ImdsError::unexpected)?;
let request = http::Request::builder()
.header(
X_AWS_EC2_METADATA_TOKEN_TTL_SECONDS,
Expand Down
5 changes: 3 additions & 2 deletions aws/rust-runtime/aws-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,14 @@ mod loader {
///
/// Use a static endpoint for all services
/// ```no_run
/// # async fn create_config() {
/// # async fn create_config() -> Result<(), aws_smithy_http::endpoint::error::InvalidEndpointError> {
/// use aws_config::endpoint::Endpoint;
///
/// let sdk_config = aws_config::from_env()
/// .endpoint_resolver(Endpoint::immutable("http://localhost:1234".parse().expect("valid URI")))
/// .endpoint_resolver(Endpoint::immutable("http://localhost:1234")?)
/// .load()
/// .await;
/// # Ok(())
/// # }
pub fn endpoint_resolver(
mut self,
Expand Down
2 changes: 1 addition & 1 deletion aws/rust-runtime/aws-endpoint/src/partition/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl ResolveAwsEndpoint for Metadata {
fn resolve_endpoint(&self, region: &Region) -> Result<AwsEndpoint, BoxError> {
let uri = self.uri_template.replace("{region}", region.as_ref());
let uri = format!("{}://{}", self.protocol.as_str(), uri);
let endpoint = Endpoint::mutable(uri.parse()?);
let endpoint = Endpoint::mutable(uri)?;
let mut credential_scope = CredentialScope::builder().region(
self.credential_scope
.region()
Expand Down
2 changes: 1 addition & 1 deletion aws/rust-runtime/aws-endpoint/src/partition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ mod test {
.resolve_endpoint(&Region::new(test_case.region))
.expect("valid region");
let mut test_uri = Uri::from_static("/");
endpoint.set_endpoint(&mut test_uri, None);
endpoint.set_endpoint(&mut test_uri, None).unwrap();
assert_eq!(test_uri, Uri::from_static(test_case.uri));
assert_eq!(
endpoint.credential_scope().region(),
Expand Down
17 changes: 11 additions & 6 deletions aws/rust-runtime/aws-types/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

use crate::region::{Region, SigningRegion};
use crate::SigningService;
use aws_smithy_http::endpoint::error::InvalidEndpointError;
use aws_smithy_http::endpoint::{Endpoint, EndpointPrefix};
use std::error::Error;
use std::fmt::Debug;
Expand Down Expand Up @@ -43,8 +44,12 @@ impl AwsEndpoint {
}

/// Sets the endpoint on a given `uri` based on this endpoint
pub fn set_endpoint(&self, uri: &mut http::Uri, endpoint_prefix: Option<&EndpointPrefix>) {
self.endpoint.set_endpoint(uri, endpoint_prefix);
pub fn set_endpoint(
&self,
uri: &mut http::Uri,
endpoint_prefix: Option<&EndpointPrefix>,
) -> Result<(), InvalidEndpointError> {
self.endpoint.set_endpoint(uri, endpoint_prefix)
}
}

Expand All @@ -71,12 +76,12 @@ pub type BoxError = Box<dyn Error + Send + Sync + 'static>;
/// # }
/// # }
/// # }
/// # fn wrapper() -> Result<(), aws_smithy_http::endpoint::error::InvalidEndpointError> {
/// use aws_smithy_http::endpoint::Endpoint;
/// use http::Uri;
/// let config = dynamodb::Config::builder()
/// .endpoint(
/// Endpoint::immutable(Uri::from_static("http://localhost:8080"))
/// );
/// .endpoint(Endpoint::immutable("http://localhost:8080")?);
/// # Ok(())
/// # }
/// ```
/// Each AWS service generates their own implementation of `ResolveAwsEndpoint`.
pub trait ResolveAwsEndpoint: Send + Sync + Debug {
Expand Down
6 changes: 4 additions & 2 deletions aws/rust-runtime/aws-types/src/sdk_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,15 @@ impl Builder {
///
/// # Examples
/// ```
/// # fn wrapper() -> Result<(), aws_smithy_http::endpoint::error::InvalidEndpointError> {
/// use std::sync::Arc;
/// use aws_types::SdkConfig;
/// use aws_smithy_http::endpoint::Endpoint;
/// use http::Uri;
/// let config = SdkConfig::builder().endpoint_resolver(
/// Endpoint::immutable(Uri::from_static("http://localhost:8080"))
/// Endpoint::immutable("http://localhost:8080")?
/// ).build();
/// # Ok(())
/// # }
/// ```
pub fn endpoint_resolver(
mut self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,16 @@ class EndpointConfigCustomization(
///
/// ## Examples
/// ```no_run
/// ## fn wrapper() -> Result<(), aws_smithy_http::endpoint::error::InvalidEndpointError> {
/// use #{aws_types}::region::Region;
/// use $moduleUseName::config::{Builder, Config};
/// use $moduleUseName::Endpoint;
///
/// let config = $moduleUseName::Config::builder()
/// .endpoint_resolver(
/// Endpoint::immutable("http://localhost:8080".parse().expect("valid URI"))
/// ).build();
/// .endpoint_resolver(Endpoint::immutable("http://localhost:8080")?)
/// .build();
/// ## Ok(())
/// ## }
/// ```
pub fn endpoint_resolver(mut self, endpoint_resolver: impl #{ResolveAwsEndpoint} + 'static) -> Self {
self.endpoint_resolver = Some(std::sync::Arc::new(#{EndpointShim}::from_resolver(endpoint_resolver)) as _);
Expand Down
8 changes: 2 additions & 6 deletions aws/sdk/integration-tests/dynamodb/tests/endpoints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ async fn endpoints_can_be_overridden_globally() {
let shared_config = aws_types::SdkConfig::builder()
.region(Region::new("us-east-4"))
.http_connector(conn)
.endpoint_resolver(Endpoint::immutable(
"http://localhost:8000".parse().unwrap(),
))
.endpoint_resolver(Endpoint::immutable("http://localhost:8000").expect("valid endpoint"))
.build();
let conf = aws_sdk_dynamodb::config::Builder::from(&shared_config)
.credentials_provider(Credentials::new("asdf", "asdf", None, None, "test"))
Expand All @@ -38,9 +36,7 @@ async fn endpoints_can_be_overridden_locally() {
.build();
let conf = aws_sdk_dynamodb::config::Builder::from(&shared_config)
.credentials_provider(Credentials::new("asdf", "asdf", None, None, "test"))
.endpoint_resolver(Endpoint::immutable(
"http://localhost:8000".parse().unwrap(),
))
.endpoint_resolver(Endpoint::immutable("http://localhost:8000").expect("valid endpoint"))
.build();
let svc = aws_sdk_dynamodb::Client::from_conf(conf);
let _ = svc.list_tables().send().await;
Expand Down
6 changes: 3 additions & 3 deletions aws/sdk/integration-tests/s3/tests/streaming-response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ async fn test_streaming_response_fails_when_eof_comes_before_content_length_reac
"test",
)))
.region(Region::new("us-east-1"))
.endpoint_resolver(Endpoint::immutable(
format!("http://{server_addr}").parse().expect("valid URI"),
))
.endpoint_resolver(
Endpoint::immutable(format!("http://{server_addr}")).expect("valid endpoint"),
)
.build();

let client = Client::new(&sdk_config);
Expand Down
17 changes: 10 additions & 7 deletions aws/sdk/integration-tests/s3/tests/timeouts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ async fn test_read_timeout() {
.read_timeout(Duration::from_millis(300))
.build(),
)
.endpoint_resolver(Endpoint::immutable(
format!("http://{server_addr}").parse().expect("valid URI"),
))
.endpoint_resolver(
Endpoint::immutable(format!("http://{server_addr}")).expect("valid endpoint"),
)
.region(Some(Region::from_static("us-east-1")))
.credentials_provider(SharedCredentialsProvider::new(Credentials::new(
"test", "test", None, None, "test",
Expand Down Expand Up @@ -148,10 +148,13 @@ async fn test_connect_timeout() {
.connect_timeout(Duration::from_millis(300))
.build(),
)
.endpoint_resolver(Endpoint::immutable(
// Emulate a connect timeout error by hitting an unroutable IP
"http://172.255.255.0:18104".parse().unwrap(),
))
.endpoint_resolver(
Endpoint::immutable(
// Emulate a connect timeout error by hitting an unroutable IP
"http://172.255.255.0:18104",
)
.expect("valid endpoint"),
)
.region(Some(Region::from_static("us-east-1")))
.credentials_provider(SharedCredentialsProvider::new(Credentials::new(
"test", "test", None, None, "test",
Expand Down
Loading