Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,16 @@ public class CustomizationConfig {
*/
private List<String> generateDirectUnionConstructors = Collections.emptyList();

/**
* Map of union shape names to collection members for which to generate trusted, no-copy direct factories.
*/
private Map<String, List<String>> generateTrustedUnionCollectionConstructors = Collections.emptyMap();

/**
* Map of structure shape names to collection members for which to generate trusted builder factories.
*/
private Map<String, List<String>> generateTrustedStructureCollectionBuilders = Collections.emptyMap();

/**
* A boolean flag to indicate if the code-generated endpoint providers class should cache the calls to URI constructors.
*/
Expand Down Expand Up @@ -1003,4 +1013,22 @@ public List<String> getGenerateDirectUnionConstructors() {
public void setGenerateDirectUnionConstructors(List<String> generateDirectUnionConstructors) {
this.generateDirectUnionConstructors = generateDirectUnionConstructors;
}

public Map<String, List<String>> getGenerateTrustedUnionCollectionConstructors() {
return generateTrustedUnionCollectionConstructors;
}

public void setGenerateTrustedUnionCollectionConstructors(
Map<String, List<String>> generateTrustedUnionCollectionConstructors) {
this.generateTrustedUnionCollectionConstructors = generateTrustedUnionCollectionConstructors;
}

public Map<String, List<String>> getGenerateTrustedStructureCollectionBuilders() {
return generateTrustedStructureCollectionBuilders;
}

public void setGenerateTrustedStructureCollectionBuilders(
Map<String, List<String>> generateTrustedStructureCollectionBuilders) {
this.generateTrustedStructureCollectionBuilders = generateTrustedStructureCollectionBuilders;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.element.Modifier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.codegen.docs.DocumentationBuilder;
import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel;
Expand Down Expand Up @@ -469,6 +470,7 @@ private List<MethodSpec> modelClassMethods() {
methodSpecs.add(addModifier(modelMethodOverrides.toStringMethod(shapeModel), FINAL));
methodSpecs.add(getValueForField());
methodSpecs.addAll(unionMembers());
methodSpecs.addAll(trustedStructureCollectionBuilders());
break;
}

Expand Down Expand Up @@ -511,6 +513,65 @@ private FieldSpec unionTypeField() {
return FieldSpec.builder(unionTypeClassName(), "type", PRIVATE, FINAL).build();
}

private Collection<MethodSpec> trustedStructureCollectionBuilders() {
Map<String, List<String>> trustedMembersByShape =
intermediateModel.getCustomizationConfig().getGenerateTrustedStructureCollectionBuilders();
trustedMembersByShape.forEach((shapeName, trustedMembers) ->
Validate.isTrue(intermediateModel.getShapes().containsKey(shapeName),
"generateTrustedStructureCollectionBuilders references shape '%s' which does not exist "
+ "in the model.", shapeName));

List<String> trustedMembers = trustedMembersByShape.getOrDefault(shapeModel.getShapeName(), emptyList());
if (trustedMembers.isEmpty()) {
return emptyList();
}

List<MemberModel> members = shapeModel.getMembers();
List<MethodSpec> methods = new ArrayList<>();
for (String trustedMember : trustedMembers) {
Optional<MemberModel> member = members.stream()
.filter(m -> m.getC2jName().equals(trustedMember))
.findFirst();
Validate.isTrue(member.isPresent(),
"Trusted structure collection builder references missing member '%s' on shape '%s'.",
trustedMember, shapeModel.getShapeName());
Validate.isTrue(member.get().isList() || member.get().isMap(),
"Trusted structure collection builder references non-collection member '%s' on shape '%s'.",
trustedMember, shapeModel.getShapeName());
methods.add(trustedStructureCollectionBuilder(member.get()));
}
return methods;
}

private MethodSpec trustedStructureCollectionBuilder(MemberModel member) {
String memberName = member.getVariable().getVariableName();
String factoryName = "builderWith" + capitalize(member.getFluentSetterMethodName()) + "Trusted";
TypeName paramType = typeProvider.typeName(member, new TypeNameOptions().useEnumTypes(false));
ClassName autoConstruct = member.isMap()
? ClassName.get("software.amazon.awssdk.core.util", "SdkAutoConstructMap")
: ClassName.get("software.amazon.awssdk.core.util", "SdkAutoConstructList");
String unmodifiableMethod = member.isMap() ? "unmodifiableMap" : "unmodifiableList";

MethodSpec.Builder factory = MethodSpec.methodBuilder(factoryName)
.addJavadoc("Creates a builder with $N set without defensively copying "
+ "the collection. The caller must provide an immutable or "
+ "exclusively owned collection.\n", member.getC2jName())
.addAnnotation(SdkInternalApi.class)
.addModifiers(PUBLIC, STATIC)
.returns(modelBuilderSpecs.builderInterfaceName())
.addParameter(paramType, memberName)
.addStatement("$T builder = new $T()",
modelBuilderSpecs.builderImplName(),
modelBuilderSpecs.builderImplName());
factory.beginControlFlow("if ($N == null || $N instanceof $T)", memberName, memberName, autoConstruct);
factory.addStatement("return builder");
factory.endControlFlow();
factory.addStatement("builder.$N = $T.$N($N)",
memberName, Collections.class, unmodifiableMethod, memberName);
factory.addStatement("return builder");
return factory.build();
}

private Collection<MethodSpec> unionMembers() {
if (!shapeModel.isUnion()) {
return emptyList();
Expand Down Expand Up @@ -540,6 +601,23 @@ private Collection<MethodSpec> directUnionConstructors() {
"Direct union constructors are only supported on Model shapes, not %s (%s)",
shapeModel.getShapeType(), shapeModel.getShapeName());
List<MemberModel> members = shapeModel.getMembers();
Map<String, List<String>> trustedMembersByShape =
intermediateModel.getCustomizationConfig().getGenerateTrustedUnionCollectionConstructors();
trustedMembersByShape.forEach((shapeName, trustedMembers) -> {
Validate.isTrue(intermediateModel.getShapes().containsKey(shapeName),
"generateTrustedUnionCollectionConstructors references shape '%s' which does not exist "
+ "in the model.", shapeName);
Validate.isTrue(intermediateModel.getCustomizationConfig().getGenerateDirectUnionConstructors()
.contains(shapeName),
"Trusted union collection constructors require direct union constructors for shape '%s'.",
shapeName);
});
List<String> trustedMembers = trustedMembersByShape.getOrDefault(shapeModel.getShapeName(), emptyList());
trustedMembers.forEach(trustedMember ->
Validate.isTrue(members.stream().anyMatch(member -> member.getC2jName().equals(trustedMember)
&& (member.isList() || member.isMap())),
"Trusted union collection constructor references non-collection member '%s' on shape '%s'.",
trustedMember, shapeModel.getShapeName()));
List<MethodSpec> methods = new ArrayList<>();

MethodSpec.Builder ctor = MethodSpec.constructorBuilder()
Expand Down Expand Up @@ -592,10 +670,40 @@ private Collection<MethodSpec> directUnionConstructors() {
factory.addStatement("$L", directCtorCall(members, member, slotValue));

methods.add(factory.build());
if (trustedMembers.contains(member.getC2jName())) {
methods.add(trustedDirectUnionCollectionConstructor(members, member, paramType));
}
}
return methods;
}

private MethodSpec trustedDirectUnionCollectionConstructor(List<MemberModel> members,
MemberModel member,
TypeName paramType) {
String memberName = member.getVariable().getVariableName();
String factoryName = "create" + capitalize(member.getFluentSetterMethodName()) + "Trusted";
ClassName autoConstruct = member.isMap()
? ClassName.get("software.amazon.awssdk.core.util", "SdkAutoConstructMap")
: ClassName.get("software.amazon.awssdk.core.util", "SdkAutoConstructList");
String unmodifiableMethod = member.isMap() ? "unmodifiableMap" : "unmodifiableList";

MethodSpec.Builder factory = MethodSpec.methodBuilder(factoryName)
.addJavadoc("Creates the $N union member without defensively copying the "
+ "collection. The caller must provide an exclusively owned "
+ "collection and relinquish all mutable references to it.\n",
member.getC2jName())
.addAnnotation(SdkInternalApi.class)
.addModifiers(PUBLIC, STATIC)
.returns(className())
.addParameter(paramType, memberName);
factory.beginControlFlow("if ($N == null || $N instanceof $T)", memberName, memberName, autoConstruct);
factory.addStatement("return UNSET_INSTANCE");
factory.endControlFlow();
factory.addStatement("$T trusted = $T.$N($N)", paramType, Collections.class, unmodifiableMethod, memberName);
factory.addStatement("$L", directCtorCall(members, member, "trusted"));
return factory.build();
}

private FieldSpec directUnionUnsetConstant() {
List<MemberModel> members = shapeModel.getMembers();
CodeBlock.Builder init = CodeBlock.builder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@
package software.amazon.awssdk.codegen.poet.model;


import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.codegen.C2jModels;
Expand Down Expand Up @@ -65,4 +70,54 @@ public void setAndInjectCustomShapes_areAddedAsMembersToBaseTypeShape() {
}
assertThat(memberNames).contains("CustomShape1","CustomShape2");
}

@Test
public void trustedStructureConfiguration_rejectsUnknownShape() throws IOException {
IntermediateModel model = model(Collections.emptyMap(),
singletonMap("MissingShape", singletonList("SimpleList")));

assertThatThrownBy(() -> source(model, "AllTypesRequest"))
.isInstanceOf(IllegalArgumentException.class);
}

@Test
public void trustedStructureConfiguration_rejectsNonCollectionMember() throws IOException {
IntermediateModel model = model(Collections.emptyMap(),
singletonMap("AllTypesRequest", singletonList("StringMember")));

assertThatThrownBy(() -> source(model, "AllTypesRequest"))
.isInstanceOf(IllegalArgumentException.class);
}

@Test
public void trustedUnionConfiguration_requiresDirectUnionConstructor() throws IOException {
IntermediateModel model = model(singletonMap("AllTypesRequest", singletonList("SimpleList")),
Collections.emptyMap());

assertThatThrownBy(() -> source(model, "AllTypesUnionStructure"))
.isInstanceOf(IllegalArgumentException.class);
}

private static IntermediateModel model(Map<String, List<String>> trustedUnions,
Map<String, List<String>> trustedStructures) throws IOException {
File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile());
File customizationConfigFile = new File(AwsModelSpecTest.class
.getResource("customization.config")
.getFile());
ServiceModel serviceModel = ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile);
CustomizationConfig config = ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile);
config.setGenerateTrustedUnionCollectionConstructors(trustedUnions);
config.setGenerateTrustedStructureCollectionBuilders(trustedStructures);

return new IntermediateModelBuilder(
C2jModels.builder()
.serviceModel(serviceModel)
.customizationConfig(config)
.build())
.build();
}

private static String source(IntermediateModel model, String shapeName) {
return new AwsServiceModel(model, model.getShapes().get(shapeName)).poetSpec().toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
Expand Down Expand Up @@ -1604,6 +1605,34 @@ public final <T> Optional<T> getValueForField(String fieldName, Class<T> clazz)
}
}

/**
* Creates a builder with SimpleList set without defensively copying the collection. The caller must provide an
* immutable or exclusively owned collection.
*/
@SdkInternalApi
public static Builder builderWithSimpleListTrusted(List<String> simpleList) {
BuilderImpl builder = new BuilderImpl();
if (simpleList == null || simpleList instanceof SdkAutoConstructList) {
return builder;
}
builder.simpleList = Collections.unmodifiableList(simpleList);
return builder;
}

/**
* Creates a builder with MapOfStringToString set without defensively copying the collection. The caller must
* provide an immutable or exclusively owned collection.
*/
@SdkInternalApi
public static Builder builderWithMapOfStringToStringTrusted(Map<String, String> mapOfStringToString) {
BuilderImpl builder = new BuilderImpl();
if (mapOfStringToString == null || mapOfStringToString instanceof SdkAutoConstructMap) {
return builder;
}
builder.mapOfStringToString = Collections.unmodifiableMap(mapOfStringToString);
return builder;
}

@Override
public final List<SdkField<?>> sdkFields() {
return SDK_FIELDS;
Expand Down
Loading
Loading