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

Enforce constraints for unnamed enums #3884

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

drganjoo
Copy link
Contributor

@drganjoo drganjoo commented Oct 17, 2024

Enforces Constraints for Unnamed Enums

This PR addresses the issue where, on the server side, unnamed enums were incorrectly treated as infallible during deserialization, allowing any string value to be converted without validation. The solution introduces a ConstraintViolation and TryFrom implementation for unnamed enums, ensuring that deserialized values conform to the enum variants defined in the Smithy model.

The following is an example of an unnamed enum:

@enum([
    { value: "MONDAY" },
    { value: "TUESDAY" }
])
string UnnamedDayOfWeek

On the server side the following type is generated for the Smithy shape:

pub struct UnnamedDayOfWeek(String);

impl ::std::convert::TryFrom<::std::string::String> for UnnamedDayOfWeek {
    type Error = crate::model::unnamed_day_of_week::ConstraintViolation;

    fn try_from(
        s: ::std::string::String,
    ) -> ::std::result::Result<Self, <Self as ::std::convert::TryFrom<::std::string::String>>::Error>
    {
        match s.as_str() {
            "MONDAY" | "TUESDAY" => Ok(Self(s)),
            _ => Err(crate::model::unnamed_day_of_week::ConstraintViolation(s)),
        }
    }
}

This change prevents invalid values from being deserialized into unnamed enums and raises appropriate constraint violations when necessary.

There is one difference between the Rust code generated for TryFrom<String> for named enums versus unnamed enums. The implementation for unnamed enums passes the ownership of the String parameter to the generated structure, and the implementation for TryFrom<&str> delegates to TryFrom<String>.

impl ::std::convert::TryFrom<::std::string::String> for UnnamedDayOfWeek {
    type Error = crate::model::unnamed_day_of_week::ConstraintViolation;
    fn try_from(
        s: ::std::string::String,
    ) -> ::std::result::Result<Self, <Self as ::std::convert::TryFrom<::std::string::String>>::Error>
    {
        match s.as_str() {
            "MONDAY" | "TUESDAY" => Ok(Self(s)),
            _ => Err(crate::model::unnamed_day_of_week::ConstraintViolation(s)),
        }
    }
}

impl ::std::convert::TryFrom<&str> for UnnamedDayOfWeek {
    type Error = crate::model::unnamed_day_of_week::ConstraintViolation;
    fn try_from(
        s: &str,
    ) -> ::std::result::Result<Self, <Self as ::std::convert::TryFrom<&str>>::Error> {
        s.to_owned().try_into()
    }
}

On the client side, the behaviour is unchanged, and the client does not validate for backward compatibility reasons. An existing test has been modified to ensure this.

#[test]
fn generate_unnamed_enums() {
    let result = "t2.nano"
        .parse::<crate::types::UnnamedEnum>()
        .expect("static value validated to member");
    assert_eq!(result, UnnamedEnum("t2.nano".to_owned()));
    let result = "not-a-valid-variant"
        .parse::<crate::types::UnnamedEnum>()
        .expect("static value validated to member");
    assert_eq!(result, UnnamedEnum("not-a-valid-variant".to_owned()));
}

Fixes issue #3880

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

@drganjoo drganjoo force-pushed the fahadzub/unnamed-enum-constrained branch from f2aa580 to 651538a Compare October 17, 2024 23:43
Copy link

A new generated diff is ready to view.

  • AWS SDK (ignoring whitespace)
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Copy link

A new generated diff is ready to view.

  • AWS SDK (ignoring whitespace)
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

@drganjoo drganjoo force-pushed the fahadzub/unnamed-enum-constrained branch from 17ca030 to bfdf606 Compare October 29, 2024 08:29
@drganjoo drganjoo marked this pull request as ready for review October 29, 2024 08:42
@drganjoo drganjoo requested review from a team as code owners October 29, 2024 08:42
Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

@@ -10,6 +10,7 @@ import software.amazon.smithy.rust.codegen.core.rustlang.rust
import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.core.rustlang.writable
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.preludeScope
import software.amazon.smithy.rust.codegen.core.util.dq

object TestEnumType : EnumType() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, I wonder why we have this class at all i.e. why we don't test directly against InfallibleEnumType. It feels wrong to copy over the implementations from the "real" classes to this class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with you on this. I'll see if it can be easily fixed in this PR, otherwise will raise another one for this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

InfallibleEnumType allows UnknownVariants, whereas TestEnumType panics when an unknown variant is encountered. I tried composing TestEnumType to use InfallibleEnumType internally, but InfallibleEnumType is defined in codegen-client, while TestEnumType is in codegen-core.

impl #{TryFrom}<&str> for ${context.enumName} {
type Error = #{ConstraintViolation};
fn try_from(s: &str) -> #{Result}<Self, <Self as #{TryFrom}<&str>>::Error> {
s.to_owned().try_into()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is first converting to a heap-allocated String and only then matching on the enum values. So invalid enum values would unnecessarily be heap-allocated. We should make TryFrom<String> and TryFrom<&str> instead delegate to FromStr, which should only heap-allocate when the enum value is valid.

Copy link
Contributor Author

@drganjoo drganjoo Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike named enums, which can use &str for comparison and directly return an enum variant, unnamed enums need to store an owned, heap-allocated String. The TryFrom<String> implementation already receives an owned String as a parameter, so delegating to FromStr would result in an unnecessary heap allocation. Additionally, ConstraintViolation takes ownership of a heap-allocated String. Therefore, both code paths (valid and invalid enum values) require a heap-allocated String. Calling to_owned within TryFrom<&str> only shifts the allocation slightly earlier without adding any additional allocation.

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

@drganjoo drganjoo force-pushed the fahadzub/unnamed-enum-constrained branch from fbcefa0 to 042fe5c Compare October 30, 2024 11:51
Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

.changelog/4329788.md Show resolved Hide resolved
Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Copy link

A new generated diff is ready to view.

  • No codegen difference in the AWS SDK
  • No codegen difference in the Client Test
  • No codegen difference in the Server Test
  • No codegen difference in the Server Test Python
  • No codegen difference in the Server Test Typescript

A new doc preview is ready to view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants