-
Notifications
You must be signed in to change notification settings - Fork 1.2k
create smithy plugin to generate BDD ruleset #3880
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
Open
sbiscigl
wants to merge
1
commit into
main
Choose a base branch
from
generate-bdd-rulesset
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
...va/com/amazonaws/util/awsclientsmithygenerator/generators/endpointrules/BddBytecoder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| /** | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0. | ||
| */ | ||
| package com.amazonaws.util.awsclientsmithygenerator.generators.endpointrules; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| /** | ||
| * Shells out to the in-tree {@code bdd-bytecoder.py} compiler to turn the JSON form of a | ||
| * {@code smithy.rules#endpointBdd} trait into the binary BDD bytecode blob consumed by the | ||
| * CRT {@code BddEngine}. The bytecoder path and python executable are supplied by the caller | ||
| * (threaded in from {@code smithy_cpp_gen.py} as gradle properties) because the gradle working | ||
| * directory cannot reach the compiler under {@code crt/} on its own. | ||
| */ | ||
| public final class BddBytecoder { | ||
|
|
||
| private BddBytecoder() {} | ||
|
|
||
| /** | ||
| * @param pythonExecutable python interpreter to run (e.g. "python3"). | ||
| * @param bytecoderPath absolute path to bdd-bytecoder.py. | ||
| * @param traitJson the endpointBdd trait serialized as JSON (the compiler's input). | ||
| * @param serviceLabel used only to label temp files / error messages. | ||
| * @return the compiled binary bytecode. | ||
| */ | ||
| public static byte[] compile(String pythonExecutable, String bytecoderPath, String traitJson, String serviceLabel) { | ||
| String tempPrefix = "bdd-" + serviceLabel.replaceAll("[^a-zA-Z0-9._-]", "_") + "-"; | ||
| try (TempFile input = new TempFile(tempPrefix, ".json"); | ||
| TempFile output = new TempFile(tempPrefix, ".bin")) { | ||
| Files.writeString(input.path, traitJson, StandardCharsets.UTF_8); | ||
|
|
||
| Process process = new ProcessBuilder( | ||
| pythonExecutable, bytecoderPath, input.path.toString(), output.path.toString()) | ||
| .redirectErrorStream(true) | ||
| .start(); | ||
| String consoleOutput = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); | ||
| int exitCode = process.waitFor(); | ||
| if (exitCode != 0) { | ||
| throw new RuntimeException("bdd-bytecoder.py failed for '" + serviceLabel | ||
| + "' (exit " + exitCode + "):\n" + consoleOutput); | ||
| } | ||
| byte[] bytecode = Files.readAllBytes(output.path); | ||
| if (bytecode.length == 0) { | ||
| throw new RuntimeException("bdd-bytecoder.py produced an empty blob for '" + serviceLabel + "'"); | ||
| } | ||
| return bytecode; | ||
| } catch (IOException | InterruptedException e) { | ||
| throw new RuntimeException("Failed to run bdd-bytecoder.py for '" + serviceLabel + "'", e); | ||
| } | ||
| } | ||
|
|
||
| /** A temp file that deletes itself on close, so {@link #compile} can lean on try-with-resources. */ | ||
| private static final class TempFile implements AutoCloseable { | ||
| private final Path path; | ||
|
|
||
| TempFile(String prefix, String suffix) throws IOException { | ||
| this.path = Files.createTempFile(prefix, suffix); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() throws IOException { | ||
| Files.deleteIfExists(path); | ||
| } | ||
| } | ||
| } |
125 changes: 125 additions & 0 deletions
125
...ws/util/awsclientsmithygenerator/generators/endpointrules/EndpointRulesCodegenPlugin.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| /** | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0. | ||
| */ | ||
| package com.amazonaws.util.awsclientsmithygenerator.generators.endpointrules; | ||
|
|
||
| import com.amazonaws.util.awsclientsmithygenerator.generators.CppWriterDelegator; | ||
| import com.amazonaws.util.awsclientsmithygenerator.generators.ServiceNameUtil; | ||
| import software.amazon.smithy.build.PluginContext; | ||
| import software.amazon.smithy.build.SmithyBuildPlugin; | ||
| import software.amazon.smithy.model.Model; | ||
| import software.amazon.smithy.model.node.Node; | ||
| import software.amazon.smithy.model.node.ObjectNode; | ||
| import software.amazon.smithy.model.node.StringNode; | ||
| import software.amazon.smithy.model.shapes.ServiceShape; | ||
| import software.amazon.smithy.model.shapes.ShapeId; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| /** | ||
| * Generates the {@code <Prefix>EndpointRules.{h,cpp}} pair carrying the compiled BDD bytecode blob. | ||
| * | ||
| * <p>This is the smithy-side counterpart to the C2J {@code --skip-endpoint-rules-blob} flag: when that | ||
| * flag is set the legacy generator deliberately emits nothing for these two files, leaving this plugin | ||
| * to write them whole. The emitted ABI is identical to the JSON path (see {@link EndpointRulesRenderer}); | ||
| * only the blob contents change from ruleset JSON to binary BDD bytecode. | ||
| * | ||
| * <p>The BDD is read from the {@code smithy.rules#endpointBdd} trait on the service shape and compiled by | ||
| * shelling out to the in-tree {@code bdd-bytecoder.py}. The interpreter and compiler paths are supplied via | ||
| * the {@code pythonExecutable} and {@code bddBytecoderPath} plugin settings (threaded in from | ||
| * {@code smithy_cpp_gen.py}) because gradle's working directory cannot reach the compiler under {@code crt/}. | ||
| */ | ||
| public class EndpointRulesCodegenPlugin implements SmithyBuildPlugin { | ||
|
|
||
| private static final ShapeId ENDPOINT_BDD_TRAIT = ShapeId.from("smithy.rules#endpointBdd"); | ||
| private static final String DEFAULT_PYTHON = "python3"; | ||
|
|
||
| @Override | ||
| public String getName() { | ||
| return "smithy-cpp-codegen-endpoint-rules"; | ||
| } | ||
|
|
||
| @Override | ||
| public void execute(PluginContext context) { | ||
| Model model = context.getModel(); | ||
|
|
||
| // Mock projections stand in for legacy services with no Smithy model, hence no BDD to compile. | ||
| if (context.getProjectionName().endsWith(".mock")) { | ||
| return; | ||
| } | ||
|
|
||
| ObjectNode settings = context.getSettings(); | ||
| Map<String, String> serviceMap = parseMapSetting(settings, "c2jMap"); | ||
| Map<String, String> namespaceMap = parseNamespaceMap(settings); | ||
| String pythonExecutable = settings.getStringMemberOrDefault("pythonExecutable", DEFAULT_PYTHON); | ||
| String bddBytecoderPath = settings.getStringMember("bddBytecoderPath") | ||
| .map(n -> n.getValue()) | ||
| .orElseThrow(() -> new IllegalStateException( | ||
| "endpoint-rules plugin requires the 'bddBytecoderPath' setting (path to bdd-bytecoder.py)")); | ||
|
|
||
| CppWriterDelegator writerDelegator = new CppWriterDelegator(context.getFileManifest()); | ||
|
|
||
| // Services without an endpointBdd trait keep resolving via the JSON path, so skip them here. | ||
| model.getServiceShapes().stream() | ||
| .map(service -> ServiceNameUtil.processS3CrtProjection(service, context.getProjectionName())) | ||
| .filter(service -> service.hasTrait(ENDPOINT_BDD_TRAIT)) | ||
| .forEach(service -> generateEndpointRules( | ||
| service, serviceMap, namespaceMap, pythonExecutable, bddBytecoderPath, writerDelegator)); | ||
|
|
||
| writerDelegator.flushWriters(); | ||
| } | ||
|
|
||
| private void generateEndpointRules(ServiceShape service, Map<String, String> serviceMap, | ||
| Map<String, String> namespaceMap, String pythonExecutable, | ||
| String bddBytecoderPath, CppWriterDelegator writerDelegator) { | ||
| String smithyServiceName = ServiceNameUtil.getSmithyServiceName(service, serviceMap); | ||
| String exportMacro = ServiceNameUtil.getExportMacro(service, serviceMap); | ||
| String namespace = namespaceMap.getOrDefault(smithyServiceName, ServiceNameUtil.getServiceName(service)); | ||
| String classPrefix = Optional.ofNullable(namespaceMap.get(smithyServiceName)) | ||
| .map(ServiceNameUtil::capitalize) | ||
| .orElse(ServiceNameUtil.getServiceNameUpperCamel(service)); | ||
|
|
||
| String traitJson = Node.printJson(service.findTrait(ENDPOINT_BDD_TRAIT).orElseThrow().toNode()); | ||
| byte[] bytecode = BddBytecoder.compile(pythonExecutable, bddBytecoderPath, traitJson, smithyServiceName); | ||
|
|
||
| writerDelegator.useFileWriter( | ||
| "include/aws/" + smithyServiceName + "/internal/" + classPrefix + "EndpointRules.h", | ||
| writer -> EndpointRulesRenderer.renderHeader(writer, namespace, classPrefix, smithyServiceName, exportMacro)); | ||
| writerDelegator.useFileWriter( | ||
| "source/" + classPrefix + "EndpointRules.cpp", | ||
| writer -> EndpointRulesRenderer.renderSource(writer, namespace, classPrefix, smithyServiceName, bytecode)); | ||
| } | ||
|
|
||
| private Map<String, String> parseMapSetting(ObjectNode settings, String key) { | ||
| return settings.getMember(key) | ||
| .filter(Node::isStringNode) | ||
| .map(Node::expectStringNode) | ||
| .map(StringNode::getValue) | ||
| .map(Node::parseJsonWithComments) | ||
| .map(Node::expectObjectNode) | ||
| .map(mapNode -> mapNode.getMembers().entrySet().stream() | ||
| .collect(Collectors.toMap( | ||
| entry -> entry.getKey().getValue(), | ||
| entry -> entry.getValue().expectStringNode().getValue()))) | ||
| .orElse(Map.of()); | ||
| } | ||
|
|
||
| private Map<String, String> parseNamespaceMap(ObjectNode settings) { | ||
| return settings.getMember("namespaceMappings") | ||
| .map(node -> node.expectStringNode().getValue()) | ||
| .map(jsonStr -> Node.parseJsonWithComments(jsonStr).expectObjectNode()) | ||
| .map(node -> node.getMembers().entrySet().stream() | ||
| .collect(Collectors.toMap( | ||
| entry -> entry.getKey().getValue(), | ||
| entry -> sanitize(entry.getValue().expectStringNode().getValue())))) | ||
| .orElse(Map.of()); | ||
| } | ||
|
|
||
| private static String sanitize(String s) { | ||
| return s.replace(" ", "").replace("-", "").replace("_", "") | ||
| .replace("Amazon", "").replace("AWS", "").replace("/", ""); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
We're duplicating functionality here. ServiceNameUtilJava.sanitizeServiceAbbreviation does this already