-
Notifications
You must be signed in to change notification settings - Fork 29
Add protocol support for AWS JSON-RPC #645
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
base: develop
Are you sure you want to change the base?
Changes from 6 commits
5c1d94b
d6704da
2eb2023
ad43c77
0243826
5a4659c
7d332fb
3d2f6c5
e051943
3512866
76ac447
05c957e
4b07405
306961c
7614b45
679c259
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /* | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| package software.amazon.smithy.python.aws.codegen; | ||
|
|
||
| import java.util.Set; | ||
| import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait; | ||
| import software.amazon.smithy.model.node.ArrayNode; | ||
| import software.amazon.smithy.model.node.ObjectNode; | ||
| import software.amazon.smithy.model.shapes.ShapeId; | ||
| import software.amazon.smithy.python.codegen.ApplicationProtocol; | ||
| import software.amazon.smithy.python.codegen.GenerationContext; | ||
| import software.amazon.smithy.python.codegen.HttpProtocolTestGenerator; | ||
| import software.amazon.smithy.python.codegen.SymbolProperties; | ||
| import software.amazon.smithy.python.codegen.generators.ProtocolGenerator; | ||
| import software.amazon.smithy.python.codegen.writer.PythonWriter; | ||
| import software.amazon.smithy.utils.SmithyInternalApi; | ||
|
|
||
| @SmithyInternalApi | ||
| public final class AwsJson10ProtocolGenerator implements ProtocolGenerator { | ||
| private static final Set<String> TESTS_TO_SKIP = Set.of( | ||
| // TODO: support the request compression trait | ||
| // https://smithy.io/2.0/spec/behavior-traits.html#smithy-api-requestcompression-trait | ||
| "SDKAppliedContentEncoding_awsJson1_0", | ||
| "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_awsJson1_0", | ||
|
|
||
| // TODO: Fix for both REST-JSON and JSON-RPC | ||
| "AwsJson10ClientPopulatesDefaultValuesInInput", | ||
| "AwsJson10ClientSkipsTopLevelDefaultValuesInInput", | ||
| "AwsJson10ClientUsesExplicitlyProvidedMemberValuesOverDefaults", | ||
| "AwsJson10ClientPopulatesDefaultsValuesWhenMissingInResponse", | ||
| "AwsJson10ClientIgnoresNonTopLevelDefaultsOnMembersWithClientOptional", | ||
| "AwsJson10ClientIgnoresDefaultValuesIfMemberValuesArePresentInResponse", | ||
|
|
||
| // TODO: support client error-correction behavior when the server | ||
| // omits required values in modeled error responses. | ||
| "AwsJson10ClientErrorCorrectsWhenServerFailsToSerializeRequiredValues", | ||
| "AwsJson10ClientErrorCorrectsWithDefaultValuesWhenServerFailsToSerializeRequiredValues"); | ||
|
|
||
| @Override | ||
| public ShapeId getProtocol() { | ||
| return AwsJson1_0Trait.ID; | ||
| } | ||
|
|
||
| @Override | ||
| public ApplicationProtocol getApplicationProtocol(GenerationContext context) { | ||
| var service = context.settings().service(context.model()); | ||
| var trait = service.expectTrait(AwsJson1_0Trait.class); | ||
| var config = ObjectNode.builder() | ||
| .withMember("http", ArrayNode.fromStrings(trait.getHttp())) | ||
| .withMember("eventStreamHttp", ArrayNode.fromStrings(trait.getEventStreamHttp())) | ||
| .build(); | ||
| return ApplicationProtocol.createDefaultHttpApplicationProtocol(config); | ||
| } | ||
|
|
||
| @Override | ||
| public void initializeProtocol(GenerationContext context, PythonWriter writer) { | ||
| writer.addDependency(AwsPythonDependency.SMITHY_AWS_CORE.withOptionalDependencies("json")); | ||
| writer.addImport("smithy_aws_core.aio.protocols", "AwsJson10ClientProtocol"); | ||
| var serviceSymbol = context.symbolProvider().toSymbol(context.settings().service(context.model())); | ||
| var serviceSchema = serviceSymbol.expectProperty(SymbolProperties.SCHEMA); | ||
| writer.write("AwsJson10ClientProtocol($T)", serviceSchema); | ||
| } | ||
|
|
||
| @Override | ||
| public void generateProtocolTests(GenerationContext context) { | ||
| context.writerDelegator().useFileWriter("./tests/test_protocol.py", "tests.test_protocol", writer -> { | ||
|
jonathan343 marked this conversation as resolved.
Outdated
|
||
| new HttpProtocolTestGenerator( | ||
| context, | ||
| getProtocol(), | ||
| writer, | ||
| (shape, testCase) -> TESTS_TO_SKIP.contains(testCase.getId())).run(); | ||
| }); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| /* | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| package software.amazon.smithy.python.aws.codegen; | ||
|
|
||
| import java.util.Set; | ||
| import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait; | ||
| import software.amazon.smithy.model.node.ArrayNode; | ||
| import software.amazon.smithy.model.node.ObjectNode; | ||
| import software.amazon.smithy.model.shapes.ShapeId; | ||
| import software.amazon.smithy.python.codegen.ApplicationProtocol; | ||
| import software.amazon.smithy.python.codegen.GenerationContext; | ||
| import software.amazon.smithy.python.codegen.HttpProtocolTestGenerator; | ||
| import software.amazon.smithy.python.codegen.SymbolProperties; | ||
| import software.amazon.smithy.python.codegen.generators.ProtocolGenerator; | ||
| import software.amazon.smithy.python.codegen.writer.PythonWriter; | ||
| import software.amazon.smithy.utils.SmithyInternalApi; | ||
|
|
||
| @SmithyInternalApi | ||
| public final class AwsJson11ProtocolGenerator implements ProtocolGenerator { | ||
| private static final Set<String> TESTS_TO_SKIP = Set.of( | ||
| // TODO: support the request compression trait | ||
| // https://smithy.io/2.0/spec/behavior-traits.html#smithy-api-requestcompression-trait | ||
| "SDKAppliedContentEncoding_awsJson1_1", | ||
| "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_awsJson1_1"); | ||
|
|
||
| @Override | ||
| public ShapeId getProtocol() { | ||
| return AwsJson1_1Trait.ID; | ||
| } | ||
|
|
||
| @Override | ||
| public ApplicationProtocol getApplicationProtocol(GenerationContext context) { | ||
| var service = context.settings().service(context.model()); | ||
| var trait = service.expectTrait(AwsJson1_1Trait.class); | ||
| var config = ObjectNode.builder() | ||
| .withMember("http", ArrayNode.fromStrings(trait.getHttp())) | ||
| .withMember("eventStreamHttp", ArrayNode.fromStrings(trait.getEventStreamHttp())) | ||
| .build(); | ||
| return ApplicationProtocol.createDefaultHttpApplicationProtocol(config); | ||
| } | ||
|
|
||
| @Override | ||
| public void initializeProtocol(GenerationContext context, PythonWriter writer) { | ||
| writer.addDependency(AwsPythonDependency.SMITHY_AWS_CORE.withOptionalDependencies("json")); | ||
| writer.addImport("smithy_aws_core.aio.protocols", "AwsJson11ClientProtocol"); | ||
| var serviceSymbol = context.symbolProvider().toSymbol(context.settings().service(context.model())); | ||
| var serviceSchema = serviceSymbol.expectProperty(SymbolProperties.SCHEMA); | ||
| writer.write("AwsJson11ClientProtocol($T)", serviceSchema); | ||
| } | ||
|
|
||
| @Override | ||
| public void generateProtocolTests(GenerationContext context) { | ||
| context.writerDelegator().useFileWriter("./tests/test_protocol.py", "tests.test_protocol", writer -> { | ||
|
jonathan343 marked this conversation as resolved.
Outdated
|
||
| new HttpProtocolTestGenerator( | ||
| context, | ||
| getProtocol(), | ||
| writer, | ||
| (shape, testCase) -> TESTS_TO_SKIP.contains(testCase.getId())).run(); | ||
| }); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,6 +16,7 @@ | |
| import java.util.logging.Logger; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
| import software.amazon.smithy.aws.traits.auth.SigV4Trait; | ||
| import software.amazon.smithy.codegen.core.CodegenException; | ||
| import software.amazon.smithy.codegen.core.Symbol; | ||
| import software.amazon.smithy.model.Model; | ||
|
|
@@ -188,12 +189,14 @@ private void generateRequestTest(OperationShape operation, HttpRequestTestCase t | |
| endpoint_uri="https://$L/$L", | ||
| transport = $T(), | ||
| retry_strategy=SimpleRetryStrategy(max_attempts=1), | ||
| ${C|} | ||
| ) | ||
| """, | ||
| CodegenUtils.getConfigSymbol(context.settings()), | ||
| host, | ||
| path, | ||
| REQUEST_TEST_ASYNC_HTTP_CLIENT_SYMBOL); | ||
| REQUEST_TEST_ASYNC_HTTP_CLIENT_SYMBOL, | ||
| (Runnable) this::writeSigV4TestConfig); | ||
| })); | ||
|
|
||
| // Generate the input using the expected shape and params | ||
|
|
@@ -437,13 +440,15 @@ private void generateResponseTest(OperationShape operation, HttpResponseTestCase | |
| headers=$J, | ||
| body=b$S, | ||
| ), | ||
| ${C|} | ||
| ) | ||
| """, | ||
| CodegenUtils.getConfigSymbol(context.settings()), | ||
| RESPONSE_TEST_ASYNC_HTTP_CLIENT_SYMBOL, | ||
| testCase.getCode(), | ||
| CodegenUtils.toTuples(testCase.getHeaders()), | ||
| testCase.getBody().filter(body -> !body.isEmpty()).orElse("")); | ||
| testCase.getBody().filter(body -> !body.isEmpty()).orElse(""), | ||
| (Runnable) this::writeSigV4TestConfig); | ||
| })); | ||
| // Create an empty input object to pass | ||
| var inputShape = model.expectShape(operation.getInputShape(), StructureShape.class); | ||
|
|
@@ -490,13 +495,15 @@ private void generateErrorResponseTest( | |
| headers=$J, | ||
| body=b$S, | ||
| ), | ||
| ${C|} | ||
| ) | ||
| """, | ||
| CodegenUtils.getConfigSymbol(context.settings()), | ||
| RESPONSE_TEST_ASYNC_HTTP_CLIENT_SYMBOL, | ||
| testCase.getCode(), | ||
| CodegenUtils.toTuples(testCase.getHeaders()), | ||
| testCase.getBody().orElse("")); | ||
| testCase.getBody().orElse(""), | ||
| (Runnable) this::writeSigV4TestConfig); | ||
| })); | ||
| // Create an empty input object to pass | ||
| var inputShape = model.expectShape(operation.getInputShape(), StructureShape.class); | ||
|
|
@@ -531,7 +538,7 @@ private void assertResponseEqual(HttpMessageTestCase testCase, Shape operationOr | |
| .findAny(); | ||
|
|
||
| if (streamBinding.isEmpty()) { | ||
| writer.write("assert actual == expected\n"); | ||
| writer.write("_assert_modeled_value(actual, expected)\n"); | ||
| return; | ||
| } | ||
|
|
||
|
|
@@ -556,7 +563,7 @@ assert isinstance(actual.$1L, AsyncByteStream) | |
| compareMediaBlob(testCase, writer); | ||
| continue; | ||
| } | ||
| writer.write("assert actual.$1L == expected.$1L\n", memberName); | ||
| writer.write("_assert_modeled_value(actual.$1L, expected.$1L)\n", memberName); | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -607,10 +614,26 @@ private void writeClientBlock( | |
| }); | ||
| } | ||
|
|
||
| private void writeSigV4TestConfig() { | ||
| if (!service.hasTrait(SigV4Trait.class)) { | ||
| return; | ||
| } | ||
| writer.addImport("smithy_aws_core.identity", "StaticCredentialsResolver"); | ||
| writer.write(""" | ||
| region="us-east-1", | ||
| aws_access_key_id="test-access-key-id", | ||
| aws_secret_access_key="test-secret-access-key", | ||
| aws_credentials_identity_resolver=StaticCredentialsResolver(), | ||
| """); | ||
| } | ||
|
|
||
| private void writeUtilStubs(Symbol serviceSymbol) { | ||
| LOGGER.fine(String.format("Writing utility stubs for %s : %s", serviceSymbol.getName(), protocol.getName())); | ||
| writer.addDependency(SmithyPythonDependency.SMITHY_CORE); | ||
| writer.addDependency(SmithyPythonDependency.SMITHY_HTTP); | ||
| writer.addStdlibImport("dataclasses", "fields"); | ||
| writer.addStdlibImport("dataclasses", "is_dataclass"); | ||
| writer.addStdlibImport("math", "isnan"); | ||
| writer.addImports("smithy_http.interfaces", | ||
| Set.of( | ||
| "HTTPRequestConfiguration", | ||
|
|
@@ -621,6 +644,24 @@ private void writeUtilStubs(Symbol serviceSymbol) { | |
| writer.addImport("smithy_core.aio.utils", "async_list"); | ||
|
|
||
| writer.write(""" | ||
| def _assert_modeled_value(actual: object, expected: object) -> None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not a fan of this. When you do a plain assert with two dataclasses, pytest will give you a nice result showing you the diff if they're not equal. This will fail at the first non-equal value. Also, since it only recurses on dataclasses it'll never find nan in a list or map. In the spirit of moving things out of Java, it might be best to have a test-utils package that implements an assert that builds up an error. It could go in test dependencies so normal installs don't catch it.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yea, this is more complicated that I thought. I'm gonna back track from this here so the scope is on JSON-RPC and I don't add complexity to this PR. I played around with this approach for replacing NaN's with a custom object that won't fail on the class _ModeledNaN:
def __repr__(self) -> str:
return "float('nan')"
class _NormalizedDocument:
def __init__(self, value: object) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
return isinstance(other, _NormalizedDocument) and self.value == other.value
def __repr__(self) -> str:
return f"Document(value={self.value!r})"
_MODELED_NAN = _ModeledNaN()
def _normalize_modeled_value(value: Any) -> Any:
if isinstance(value, float) and isnan(value):
return _MODELED_NAN
if isinstance(value, Document):
return _NormalizedDocument(_normalize_modeled_value(value.as_value()))
if is_dataclass(value) and not isinstance(value, type):
return cast(Any, type(value))(
**{
field.name: _normalize_modeled_value(getattr(value, field.name))
for field in fields(value)
if field.init
},
)
if isinstance(value, list):
return [_normalize_modeled_value(member) for member in cast(list[Any], value)]
if isinstance(value, tuple):
return tuple(
_normalize_modeled_value(member) for member in cast(tuple[Any, ...], value)
)
if isinstance(value, dict):
return {
key: _normalize_modeled_value(member)
for key, member in cast(dict[Any, Any], value).items()
}
return value
def _assert_modeled_value(actual: Any, expected: Any) -> None:
assert _normalize_modeled_value(actual) == _normalize_modeled_value(expected)I'm gonna revert these changes and ignore the nan tests again. I'll create an issue for us to track the work for getting a proper solution.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah it's a bit complex. What if you just to a recursive equalty check if it's a known nan test? I'm okay with the rest result being less good for those tests specifically. I think it should be pretty easy to traverse the document during codegen to see if there's a nan value. |
||
| if isinstance(expected, float) and isnan(expected): | ||
| assert isinstance(actual, float) | ||
| assert isnan(actual) | ||
| return | ||
|
|
||
| if is_dataclass(expected): | ||
| assert is_dataclass(actual) | ||
| for field in fields(expected): | ||
| _assert_modeled_value( | ||
| getattr(actual, field.name), | ||
| getattr(expected, field.name), | ||
| ) | ||
| return | ||
|
|
||
| assert actual == expected | ||
|
|
||
|
|
||
| class $1L($2T): | ||
| ""\"A test error that subclasses the service-error for protocol tests.""\" | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Didn't you say you fixed this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, maybe you're thinking of the error namespace mismatch fallback behavior I added?