Skip to content

Commit

Permalink
feat(type-safe-api): faster code generation for java infrastructure a…
Browse files Browse the repository at this point in the history
…nd handlers (#852)

* feat(type-safe-api): faster code generation for java lambda handlers projects

Move to new codegen for java lambda handlers

* feat(type-safe-api): faster code generation for java infrastructure projects

Move java infrastructure projects to new codegen
  • Loading branch information
cogwirrel authored Oct 9, 2024
1 parent be29501 commit 39b2b71
Show file tree
Hide file tree
Showing 41 changed files with 662 additions and 1,353 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
package {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-infrastructure-package}}{{/apis.0}}{{/apiInfo}};
###TSAPI_WRITE_FILE###
{
"id": "api",
"dir": "<%= metadata.srcDir || 'src' %>",
"name": "Api",
"ext": ".java",
"overwrite": true
}
###/TSAPI_WRITE_FILE###package <%- metadata.packageName %>;

import com.fasterxml.jackson.databind.ObjectMapper;
import software.aws.pdk.type_safe_api.OperationDetails;
import software.aws.pdk.type_safe_api.TypeSafeRestApi;
import software.aws.pdk.type_safe_api.TypeSafeRestApiProps;
import software.constructs.Construct;
import {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-runtime-package}}{{/apis.0}}{{/apiInfo}}.api.operation_config.OperationLookup;
import <%- metadata.runtimePackageName %>.api.operation_config.OperationLookup;

import java.io.IOException;
import java.net.URL;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
package {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-infrastructure-package}}{{/apis.0}}{{/apiInfo}};
###TSAPI_WRITE_FILE###
{
"id": "api-props",
"dir": "<%= metadata.srcDir || 'src' %>",
"name": "ApiProps",
"ext": ".java",
"overwrite": true
}
###/TSAPI_WRITE_FILE###package <%- metadata.packageName %>;

import software.amazon.awscdk.services.apigateway.CorsOptions;
import software.amazon.awscdk.services.apigateway.StageOptions;
Expand All @@ -11,7 +19,7 @@ import software.aws.pdk.type_safe_api.Authorizer;
import software.aws.pdk.type_safe_api.TypeSafeApiIntegration;
import software.aws.pdk.type_safe_api.TypeSafeApiWebAclOptions;

import {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-runtime-package}}{{/apis.0}}{{/apiInfo}}.api.operation_config.OperationConfig;
import <%- metadata.runtimePackageName %>.api.operation_config.OperationConfig;

import java.util.List;
import java.util.Map;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
###TSAPI_SPLIT_FILE###
{{#apiInfo ~}}
{{#apis ~}}
{{#operations ~}}
{{#operation ~}}
{{#if vendorExtensions.x-handler}}
<%_ allOperations.forEach((operation) => { _%>
<%_ if (operation.vendorExtensions && operation.vendorExtensions['x-handler']) { _%>
<%_ const language = operation.vendorExtensions['x-handler'].language; _%>
<%_ const isTypeScript = language === 'typescript'; _%>
<%_ const isJava = language === 'java'; _%>
<%_ const isPython = language === 'python'; _%>
###TSAPI_WRITE_FILE###
{
"dir": "functions",
"name": "{{operationIdCamelCase}}Function",
"dir": "<%= metadata.srcDir || 'src' %>/functions",
"name": "<%- operation.operationIdPascalCase %>Function",
"ext": ".java",
"overwrite": true
}
###/TSAPI_WRITE_FILE###package {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-infrastructure-package}}{{/apis.0}}{{/apiInfo}}.functions;
###/TSAPI_WRITE_FILE###package <%- metadata.packageName %>.functions;
import org.jetbrains.annotations.NotNull;
import software.amazon.awscdk.services.lambda.Function;
import software.aws.pdk.type_safe_api.SnapStartFunction;
import software.constructs.Construct;
/**
* Lambda function construct which points to the {{vendorExtensions.x-handler.language}} implementation of {{operationIdCamelCase}}
* Lambda function construct which points to the <%- language %> implementation of <%- operation.operationIdPascalCase %>
*/
public class {{operationIdCamelCase}}Function extends {{#startsWith vendorExtensions.x-handler.language 'java' ~}}SnapStart{{~/startsWith}}Function {
public {{operationIdCamelCase}}Function(@NotNull Construct scope, @NotNull String id, @NotNull {{operationIdCamelCase}}FunctionProps props) {
public class <%- operation.operationIdPascalCase %>Function extends <% if (isJava) { %>SnapStart<% } %>Function {
public <%- operation.operationIdPascalCase %>Function(@NotNull Construct scope, @NotNull String id, @NotNull <%- operation.operationIdPascalCase %>FunctionProps props) {
super(scope, id, props);
}
public {{operationIdCamelCase}}Function(@NotNull Construct scope, @NotNull String id) {
this(scope, id, {{operationIdCamelCase}}FunctionProps.builder().build());
public <%- operation.operationIdPascalCase %>Function(@NotNull Construct scope, @NotNull String id) {
this(scope, id, <%- operation.operationIdPascalCase %>FunctionProps.builder().build());
}
}
###TSAPI_WRITE_FILE###
{
"dir": "functions",
"name": "{{operationIdCamelCase}}FunctionProps",
"dir": "<%= metadata.srcDir || 'src' %>/functions",
"name": "<%- operation.operationIdPascalCase %>FunctionProps",
"ext": ".java",
"overwrite": true
}
###/TSAPI_WRITE_FILE###package {{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-infrastructure-package}}{{/apis.0}}{{/apiInfo}}.functions;
###/TSAPI_WRITE_FILE###package <%- metadata.packageName %>.functions;
import org.jetbrains.annotations.NotNull;
import software.amazon.awscdk.Duration;
Expand Down Expand Up @@ -79,12 +79,12 @@ import java.util.List;
import java.util.Map;
@lombok.Builder @lombok.Getter
public class {{operationIdCamelCase}}FunctionProps implements {{#startsWith vendorExtensions.x-handler.language 'java' ~}}SnapStart{{~/startsWith}}FunctionProps {
public class <%- operation.operationIdPascalCase %>FunctionProps implements <% if (isJava) { %>SnapStart<% } %>FunctionProps {
private static String infraProjectAbsolutePath;
static {
try {
try (InputStream stream = {{operationIdCamelCase}}FunctionProps.class.getClassLoader()
try (InputStream stream = <%- operation.operationIdPascalCase %>FunctionProps.class.getClassLoader()
.getResourceAsStream("project-absolute-path.txt")) {
try (InputStreamReader inputStreamReader = new InputStreamReader(stream)) {
infraProjectAbsolutePath = new BufferedReader(inputStreamReader).lines().findFirst()
Expand All @@ -98,28 +98,28 @@ public class {{operationIdCamelCase}}FunctionProps implements {{#startsWith vend
// Fixed props
private final Code code = Code.fromAsset(Paths.get(infraProjectAbsolutePath).resolve(
{{#startsWith vendorExtensions.x-handler.language 'typescript' ~}}
"{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-typescript-asset-path}}{{/apis.0}}{{/apiInfo}}/###TSAPI_FN###{ "function": "kebabCase", "args": ["{{operationIdCamelCase}}"] }###/TSAPI_FN###"
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'python' ~}}
"{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-python-asset-path}}{{/apis.0}}{{/apiInfo}}"
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'java' ~}}
"{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-java-asset-path}}{{/apis.0}}{{/apiInfo}}"
{{~/startsWith}}
<%_ if (isTypeScript) { _%>
"<%- metadata['x-handlers-typescript-asset-path'] %>/<%- operation.operationIdKebabCase %>"
<%_ } else if (isPython) { _%>
"<%- metadata['x-handlers-python-asset-path'] %>"
<%_ } else if (isJava) { _%>
"<%- metadata['x-handlers-java-asset-path'] %>"
<%_ } _%>
).toAbsolutePath().toString());
{{#startsWith vendorExtensions.x-handler.language 'typescript' ~}}
<%_ if (isTypeScript) { _%>
private final String handler = "index.handler";
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'python' ~}}
private final String handler = "{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-python-module}}{{/apis.0}}{{/apiInfo}}.{{operationIdSnakeCase}}.handler";
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'java' ~}}
private final String handler = "{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-java-package}}{{/apis.0}}{{/apiInfo}}.{{operationIdCamelCase}}Handler";
{{~/startsWith}}
{{#startsWith vendorExtensions.x-handler.language 'typescript' ~}}
private final Runtime runtime = Runtime.{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-node-lambda-runtime-version}}{{/apis.0}}{{/apiInfo}};
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'python' ~}}
private final Runtime runtime = Runtime.{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-python-lambda-runtime-version}}{{/apis.0}}{{/apiInfo}};
{{~/startsWith}}{{#startsWith vendorExtensions.x-handler.language 'java' ~}}
private final Runtime runtime = Runtime.{{#apiInfo}}{{#apis.0}}{{vendorExtensions.x-handlers-java-lambda-runtime-version}}{{/apis.0}}{{/apiInfo}};
{{~/startsWith}}
<%_ } else if (isPython) { _%>
private final String handler = "<%- metadata['x-handlers-python-module'] %>.<%- operation.operationIdSnakeCase %>.handler";
<%_ } else if (isJava) { _%>
private final String handler = "<%- metadata['x-handlers-java-package'] %>.<%- operation.operationIdPascalCase %>Handler";
<%_ } _%>
<%_ if (isTypeScript) { _%>
private final Runtime runtime = Runtime.<%- metadata['x-handlers-node-lambda-runtime-version'] %>;
<%_ } else if (isPython) { _%>
private final Runtime runtime = Runtime.<%- metadata['x-handlers-python-lambda-runtime-version'] %>;
<%_ } else if (isJava) { _%>
private final Runtime runtime = Runtime.<%- metadata['x-handlers-java-lambda-runtime-version'] %>;
<%_ } _%>
// Props with defaults
@lombok.Builder.Default
Expand Down Expand Up @@ -165,8 +165,5 @@ public class {{operationIdCamelCase}}FunctionProps implements {{#startsWith vend
IDestination onSuccess;
Number retryAttempts;
}
{{/if}}
{{~/operation}}
{{~/operations}}
{{~/apis}}
{{~/apiInfo}}
<%_ } _%>
<%_ }); _%>
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
###TSAPI_WRITE_FILE###
{
"id": "mock-integrations",
"dir": "<%= metadata.srcDir || 'src' %>",
"name": "MockIntegrations",
"ext": ".java",
"overwrite": true
}
###/TSAPI_WRITE_FILE###package <%- metadata.packageName %>;

import <%- metadata.runtimePackageName %>.JSON;
import <%- metadata.runtimePackageName %>.api.operation_config.OperationConfig;
import <%- metadata.runtimePackageName %>.model.*;
import software.aws.pdk.type_safe_api.Integrations;
import software.aws.pdk.type_safe_api.MockIntegration;
import software.aws.pdk.type_safe_api.MockIntegrationResponse;
import software.aws.pdk.type_safe_api.TypeSafeApiIntegration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.stream.Collectors;


/**
* Type-safe mock integrations for API operations
*/
public class MockIntegrations {
static {
// Instantiate json instance so that any .toJson() methods can be used
new JSON();
}

/**
* Read a mock data file for the given operation
*/
private static String readMockDataFile(final String method, final String path, final int statusCode) {
try {
try (InputStream stream = MockIntegrations.class.getClassLoader()
.getResourceAsStream(Paths.get("mocks", method + path.replaceAll("/", "-") + String.format("-%d.json", statusCode)).toString())) {
try (InputStreamReader inputStreamReader = new InputStreamReader(stream)) {
return new BufferedReader(inputStreamReader).lines().collect(Collectors.joining(System.lineSeparator()));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

<%_ if (metadata.enableMockIntegrations) { _%>
<%_ allOperations.forEach((operation) => { _%>
<%_ operation.responses.forEach((response) => { _%>
/**
* Mock integration to return a <%- response.code %> response from the <%- operation.name %> operation
*/
public static MockIntegration <%- operation.name %><%- response.code %>(<% if (response.type !== 'void') { %>final <% if (response.isPrimitive) { %>String<% } else { %><%- response.javaType %><% } %> body<% } %>) {
return Integrations.mock(MockIntegrationResponse.builder()
.statusCode(<%- response.code %>)
<%_ if (response.type !== 'void') { _%>
<%_ if (response.isPrimitive) { _%>
.body(body)
<%_ } else { _%>
.body(body.toJson())
<%_ } _%>
<%_ } _%>
.build());
}
<%_ if (response.type !== 'void') { _%>
<%_ if (!response.isPrimitive) { _%>
/**
* Mock integration to return a <%- response.code %> response from the <%- operation.name %> operation, with generated mock data
*/
public static MockIntegration <%- operation.name %><%- response.code %>() {
return Integrations.mock(MockIntegrationResponse.builder()
.statusCode(<%- response.code %>)
.body(MockIntegrations.readMockDataFile("<%- operation.method.toLowerCase() %>", "<%- operation.path %>", <%- response.code %>))
.build());
}
<%_ } _%>
<%_ } _%>
<%_ }); _%>
<%_ }); _%>
/**
* Mock all operations for which generated JSON data can be returned.
* The first available response is used for each operation. In most cases this is the successful 200 response.
* @return a builder which you can use to override integrations for operations before calling .build()
*/
public static OperationConfig.OperationConfigBuilder<TypeSafeApiIntegration> mockAll() {
return OperationConfig.<TypeSafeApiIntegration>builder()
<%_ allOperations.forEach((operation) => { _%>
<%_ const firstResponse = operation.results[0] || operation.responses[0]; _%>
<%_ if (firstResponse && !firstResponse.isPrimitive) { _%>
.<%- operation.name %>(TypeSafeApiIntegration.builder()
.integration(MockIntegrations.<%- operation.name %><%- firstResponse.code %>())
.build())
<%_ } _%>
<%_ }); _%>
;
}
<%_ } else { _%>
// No mock integrations have been generated, since mock data generation is disabled.
<%_ } _%>
}
Loading

0 comments on commit 39b2b71

Please sign in to comment.