From 26c8966d619fbfe86e8569d45658643bd445a82f Mon Sep 17 00:00:00 2001 From: RanVaknin <50976344+RanVaknin@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:07:53 -0800 Subject: [PATCH 1/2] Add trusted collection factories --- .../customization/CustomizationConfig.java | 28 +++++ .../codegen/poet/model/AwsServiceModel.java | 108 ++++++++++++++++++ .../model/CustomSdkShapesCodegenTest.java | 55 +++++++++ .../codegen/poet/model/alltypesrequest.java | 29 +++++ .../poet/model/alltypesunionstructure.java | 26 +++++ .../codegen/poet/model/customization.config | 6 + .../dynamodb/customization.config | 7 ++ .../dynamodbstreams/customization.config | 1 + .../AttributeValueCreateConstructorTest.java | 107 +++++++++++++++++ 9 files changed, 367 insertions(+) diff --git a/codegen/src/main/java/software/amazon/awssdk/codegen/model/config/customization/CustomizationConfig.java b/codegen/src/main/java/software/amazon/awssdk/codegen/model/config/customization/CustomizationConfig.java index 069f738c64f6..29d53590a97e 100644 --- a/codegen/src/main/java/software/amazon/awssdk/codegen/model/config/customization/CustomizationConfig.java +++ b/codegen/src/main/java/software/amazon/awssdk/codegen/model/config/customization/CustomizationConfig.java @@ -373,6 +373,16 @@ public class CustomizationConfig { */ private List generateDirectUnionConstructors = Collections.emptyList(); + /** + * Map of union shape names to collection members for which to generate trusted, no-copy direct factories. + */ + private Map> generateTrustedUnionCollectionConstructors = Collections.emptyMap(); + + /** + * Map of structure shape names to collection members for which to generate trusted builder factories. + */ + private Map> generateTrustedStructureCollectionBuilders = Collections.emptyMap(); + /** * A boolean flag to indicate if the code-generated endpoint providers class should cache the calls to URI constructors. */ @@ -1003,4 +1013,22 @@ public List getGenerateDirectUnionConstructors() { public void setGenerateDirectUnionConstructors(List generateDirectUnionConstructors) { this.generateDirectUnionConstructors = generateDirectUnionConstructors; } + + public Map> getGenerateTrustedUnionCollectionConstructors() { + return generateTrustedUnionCollectionConstructors; + } + + public void setGenerateTrustedUnionCollectionConstructors( + Map> generateTrustedUnionCollectionConstructors) { + this.generateTrustedUnionCollectionConstructors = generateTrustedUnionCollectionConstructors; + } + + public Map> getGenerateTrustedStructureCollectionBuilders() { + return generateTrustedStructureCollectionBuilders; + } + + public void setGenerateTrustedStructureCollectionBuilders( + Map> generateTrustedStructureCollectionBuilders) { + this.generateTrustedStructureCollectionBuilders = generateTrustedStructureCollectionBuilders; + } } diff --git a/codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AwsServiceModel.java b/codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AwsServiceModel.java index 55923a847a48..d278a00165c9 100644 --- a/codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AwsServiceModel.java +++ b/codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AwsServiceModel.java @@ -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; @@ -469,6 +470,7 @@ private List modelClassMethods() { methodSpecs.add(addModifier(modelMethodOverrides.toStringMethod(shapeModel), FINAL)); methodSpecs.add(getValueForField()); methodSpecs.addAll(unionMembers()); + methodSpecs.addAll(trustedStructureCollectionBuilders()); break; } @@ -511,6 +513,65 @@ private FieldSpec unionTypeField() { return FieldSpec.builder(unionTypeClassName(), "type", PRIVATE, FINAL).build(); } + private Collection trustedStructureCollectionBuilders() { + Map> 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 trustedMembers = trustedMembersByShape.getOrDefault(shapeModel.getShapeName(), emptyList()); + if (trustedMembers.isEmpty()) { + return emptyList(); + } + + List members = shapeModel.getMembers(); + List methods = new ArrayList<>(); + for (String trustedMember : trustedMembers) { + Optional 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 unionMembers() { if (!shapeModel.isUnion()) { return emptyList(); @@ -540,6 +601,23 @@ private Collection directUnionConstructors() { "Direct union constructors are only supported on Model shapes, not %s (%s)", shapeModel.getShapeType(), shapeModel.getShapeName()); List members = shapeModel.getMembers(); + Map> 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 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 methods = new ArrayList<>(); MethodSpec.Builder ctor = MethodSpec.constructorBuilder() @@ -592,10 +670,40 @@ private Collection 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 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 members = shapeModel.getMembers(); CodeBlock.Builder init = CodeBlock.builder(); diff --git a/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/CustomSdkShapesCodegenTest.java b/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/CustomSdkShapesCodegenTest.java index 19c95061ae36..2d53a97bb4c3 100644 --- a/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/CustomSdkShapesCodegenTest.java +++ b/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/CustomSdkShapesCodegenTest.java @@ -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; @@ -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> trustedUnions, + Map> 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(); + } } diff --git a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesrequest.java b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesrequest.java index 5e3b7f4b4a8c..212a4cba97fc 100644 --- a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesrequest.java +++ b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesrequest.java @@ -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; @@ -1604,6 +1605,34 @@ public final Optional getValueForField(String fieldName, Class 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 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 mapOfStringToString) { + BuilderImpl builder = new BuilderImpl(); + if (mapOfStringToString == null || mapOfStringToString instanceof SdkAutoConstructMap) { + return builder; + } + builder.mapOfStringToString = Collections.unmodifiableMap(mapOfStringToString); + return builder; + } + @Override public final List> sdkFields() { return SDK_FIELDS; diff --git a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesunionstructure.java b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesunionstructure.java index ef20e834f7d6..60568bdd3c86 100644 --- a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesunionstructure.java +++ b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/alltypesunionstructure.java @@ -21,6 +21,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.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; @@ -2149,6 +2150,18 @@ public static AllTypesUnionStructure createSimpleList(List simpleList) { return new AllTypesUnionStructure(Type.SIMPLE_LIST, null, null, null, null, null, null, null, copied, DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), null, null, null, null, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructList.getInstance(), null, null, null, null, null, null, null); } + /** + * Creates the SimpleList union member without defensively copying the collection. The caller must provide an exclusively owned collection and relinquish all mutable references to it. + */ + @SdkInternalApi + public static AllTypesUnionStructure createSimpleListTrusted(List simpleList) { + if (simpleList == null || simpleList instanceof SdkAutoConstructList) { + return UNSET_INSTANCE; + } + List trusted = Collections.unmodifiableList(simpleList); + return new AllTypesUnionStructure(Type.SIMPLE_LIST, null, null, null, null, null, null, null, trusted, DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), null, null, null, null, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructList.getInstance(), null, null, null, null, null, null, null); + } + /** * Equivalent to {@code builder().listOfEnumsWithStrings(listOfEnums).build()} but with a single allocation. */ @@ -2251,6 +2264,19 @@ public static AllTypesUnionStructure createMapOfStringToString( return new AllTypesUnionStructure(Type.MAP_OF_STRING_TO_STRING, null, null, null, null, null, null, null, DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructMap.getInstance(), copied, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), null, null, null, null, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructList.getInstance(), null, null, null, null, null, null, null); } + /** + * Creates the MapOfStringToString union member without defensively copying the collection. The caller must provide an exclusively owned collection and relinquish all mutable references to it. + */ + @SdkInternalApi + public static AllTypesUnionStructure createMapOfStringToStringTrusted( + Map mapOfStringToString) { + if (mapOfStringToString == null || mapOfStringToString instanceof SdkAutoConstructMap) { + return UNSET_INSTANCE; + } + Map trusted = Collections.unmodifiableMap(mapOfStringToString); + return new AllTypesUnionStructure(Type.MAP_OF_STRING_TO_STRING, null, null, null, null, null, null, null, DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructList.getInstance(), DefaultSdkAutoConstructMap.getInstance(), trusted, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructMap.getInstance(), null, null, null, null, DefaultSdkAutoConstructMap.getInstance(), DefaultSdkAutoConstructList.getInstance(), null, null, null, null, null, null, null); + } + /** * Equivalent to {@code builder().mapOfStringToSimpleStruct(mapOfStringToSimpleStruct).build()} but with a single allocation. */ diff --git a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/customization.config b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/customization.config index c9f5746b2996..fffbedef9eb9 100644 --- a/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/customization.config +++ b/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/model/customization.config @@ -70,6 +70,12 @@ } }, "generateDirectUnionConstructors": ["AllTypesUnionStructure", "UnionWithTypeMember"], + "generateTrustedUnionCollectionConstructors": { + "AllTypesUnionStructure": ["SimpleList", "MapOfStringToString"] + }, + "generateTrustedStructureCollectionBuilders": { + "AllTypesRequest": ["SimpleList", "MapOfStringToString"] + }, "underscoresInNameBehavior": "ALLOW", "requiredTraitValidationEnabled": true } diff --git a/services/dynamodb/src/main/resources/codegen-resources/dynamodb/customization.config b/services/dynamodb/src/main/resources/codegen-resources/dynamodb/customization.config index 01363ce0186e..c09f6e80dacb 100644 --- a/services/dynamodb/src/main/resources/codegen-resources/dynamodb/customization.config +++ b/services/dynamodb/src/main/resources/codegen-resources/dynamodb/customization.config @@ -1,6 +1,13 @@ { "calculateCrc32FromCompressedData": true, "generateDirectUnionConstructors": ["AttributeValue"], + "generateTrustedUnionCollectionConstructors": {"AttributeValue": ["M", "L"]}, + "generateTrustedStructureCollectionBuilders": { + "GetItemRequest": ["Key"], + "PutItemRequest": ["Item"], + "PutRequest": ["Item"], + "Put": ["Item"] + }, "shapeModifiers": { "AttributeValue": { "modify": [ diff --git a/services/dynamodb/src/main/resources/codegen-resources/dynamodbstreams/customization.config b/services/dynamodb/src/main/resources/codegen-resources/dynamodbstreams/customization.config index 41101d3f9ff3..5209ab8c886d 100644 --- a/services/dynamodb/src/main/resources/codegen-resources/dynamodbstreams/customization.config +++ b/services/dynamodb/src/main/resources/codegen-resources/dynamodbstreams/customization.config @@ -1,6 +1,7 @@ { "calculateCrc32FromCompressedData": true, "generateDirectUnionConstructors": ["AttributeValue"], + "generateTrustedUnionCollectionConstructors": {"AttributeValue": ["M", "L"]}, "shapeModifiers": { "AttributeValue": { "modify": [ diff --git a/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/AttributeValueCreateConstructorTest.java b/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/AttributeValueCreateConstructorTest.java index 93f7ea1adc9a..a72dd7ec90e9 100644 --- a/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/AttributeValueCreateConstructorTest.java +++ b/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/AttributeValueCreateConstructorTest.java @@ -31,6 +31,10 @@ import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.model.Put; +import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; +import software.amazon.awssdk.services.dynamodb.model.PutRequest; /** * Verifies that the generated {@code createX} factories on {@link AttributeValue} (emitted under the @@ -129,6 +133,105 @@ void fastMap_defensivelyCopiesAndStoresUnmodifiable() { .isInstanceOf(UnsupportedOperationException.class); } + @Test + void trustedList_usesExclusivelyOwnedInputWithoutCopyingAndExposesItUnmodifiable() { + List values = new ArrayList<>(); + values.add(AttributeValue.fromS("first")); + + AttributeValue attributeValue = AttributeValue.createLTrusted(values); + values.add(AttributeValue.fromS("second")); + + assertThat(attributeValue.type()).isEqualTo(AttributeValue.Type.L); + assertThat(attributeValue.l()).containsExactlyElementsOf(values); + assertThatThrownBy(() -> attributeValue.l().add(AttributeValue.fromS("third"))) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void trustedMap_usesExclusivelyOwnedInputWithoutCopyingAndExposesItUnmodifiable() { + Map values = new HashMap<>(); + values.put("first", AttributeValue.fromS("one")); + + AttributeValue attributeValue = AttributeValue.createMTrusted(values); + values.put("second", AttributeValue.fromS("two")); + + assertThat(attributeValue.type()).isEqualTo(AttributeValue.Type.M); + assertThat(attributeValue.m()).containsAllEntriesOf(values); + assertThatThrownBy(() -> attributeValue.m().put("third", AttributeValue.fromS("three"))) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void trustedEmptyCollections_arePresentUnionMembers() { + assertThat(AttributeValue.createLTrusted(new ArrayList<>()).type()).isEqualTo(AttributeValue.Type.L); + assertThat(AttributeValue.createMTrusted(new HashMap<>()).type()).isEqualTo(AttributeValue.Type.M); + } + + @Test + void trustedNullAndAutoConstructCollections_areUnsetUnionMembers() { + AttributeValue unset = AttributeValue.builder().build(); + + assertThat(AttributeValue.createLTrusted(null)).isEqualTo(unset); + assertThat(AttributeValue.createMTrusted(null)).isEqualTo(unset); + assertThat(AttributeValue.createLTrusted(unset.l())).isEqualTo(unset); + assertThat(AttributeValue.createMTrusted(unset.m())).isEqualTo(unset); + } + + @Test + void trustedRequestBuilders_useExclusivelyOwnedMapsWithoutCopying() { + Map key = trustedMap("key"); + GetItemRequest get = GetItemRequest.builderWithKeyTrusted(key).build(); + key.put("later", AttributeValue.fromS("mutation")); + assertThat(get.key()).containsKey("later"); + assertThatThrownBy(() -> get.key().put("getter", AttributeValue.fromS("mutation"))) + .isInstanceOf(UnsupportedOperationException.class); + + Map putItem = trustedMap("item"); + PutItemRequest putItemRequest = PutItemRequest.builderWithItemTrusted(putItem).build(); + putItem.put("later", AttributeValue.fromS("mutation")); + assertThat(putItemRequest.item()).containsKey("later"); + assertThatThrownBy(() -> putItemRequest.item().put("getter", AttributeValue.fromS("mutation"))) + .isInstanceOf(UnsupportedOperationException.class); + + Map batchItem = trustedMap("batch"); + PutRequest putRequest = PutRequest.builderWithItemTrusted(batchItem).build(); + batchItem.put("later", AttributeValue.fromS("mutation")); + assertThat(putRequest.item()).containsKey("later"); + assertThatThrownBy(() -> putRequest.item().put("getter", AttributeValue.fromS("mutation"))) + .isInstanceOf(UnsupportedOperationException.class); + + Map transactionItem = trustedMap("transaction"); + Put put = Put.builderWithItemTrusted(transactionItem).build(); + transactionItem.put("later", AttributeValue.fromS("mutation")); + assertThat(put.item()).containsKey("later"); + assertThatThrownBy(() -> put.item().put("getter", AttributeValue.fromS("mutation"))) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void existingRequestBuilder_stillDefensivelyCopies() { + Map item = trustedMap("item"); + PutItemRequest request = PutItemRequest.builder().item(item).build(); + + item.put("later", AttributeValue.fromS("mutation")); + + assertThat(request.item()).doesNotContainKey("later"); + } + + @Test + void trustedRequestBuilders_nullAndAutoConstructMapsRemainUnset() { + Map autoConstruct = PutItemRequest.builder().build().item(); + + assertThat(GetItemRequest.builderWithKeyTrusted(null).build().hasKey()).isFalse(); + assertThat(GetItemRequest.builderWithKeyTrusted(autoConstruct).build().hasKey()).isFalse(); + assertThat(PutItemRequest.builderWithItemTrusted(null).build().hasItem()).isFalse(); + assertThat(PutItemRequest.builderWithItemTrusted(autoConstruct).build().hasItem()).isFalse(); + assertThat(PutRequest.builderWithItemTrusted(null).build().hasItem()).isFalse(); + assertThat(PutRequest.builderWithItemTrusted(autoConstruct).build().hasItem()).isFalse(); + assertThat(Put.builderWithItemTrusted(null).build().hasItem()).isFalse(); + assertThat(Put.builderWithItemTrusted(autoConstruct).build().hasItem()).isFalse(); + } + @Test void fastStringSet_defensivelyCopiesAndStoresUnmodifiable() { List input = new ArrayList<>(Arrays.asList("a")); @@ -202,6 +305,10 @@ private static Map singletonMap(String k, AttributeValue return m; } + private static Map trustedMap(String value) { + return singletonMap("id", AttributeValue.fromS(value)); + } + private static Arguments arg(String name, Supplier fast, Supplier builder) { return Arguments.of(name, fast, builder); } From 4570e08da649fdb69d2755a834342edc5345f1c4 Mon Sep 17 00:00:00 2001 From: RanVaknin <50976344+RanVaknin@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:08:01 -0800 Subject: [PATCH 2/2] Use trusted collection factories --- .../mapper/dynamodb/DynamoDBMapper.java | 132 ++++++++++++++---- .../dynamodb/StandardModelFactories.java | 8 +- .../CollectionToListMarshaller.java | 2 +- .../marshallers/MapToMapMarshaller.java | 2 +- .../marshallers/ObjectToMapMarshaller.java | 2 +- .../dynamodb/DynamoDBMapperBuilderTest.java | 80 +++++++++++ .../StandardModelFactoriesV2Test.java | 43 ++++++ 7 files changed, 233 insertions(+), 36 deletions(-) diff --git a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapper.java b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapper.java index 59d6ba72d0b9..831e0f3c2aea 100644 --- a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapper.java +++ b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapper.java @@ -367,9 +367,14 @@ public T load(T keyObject, DynamoDBMapperConfig config) { String tableName = getTableName(clazz, keyObject, config); Map key = model.convertKey(keyObject); + return load(model, key, tableName, config); + } - GetItemRequest rq = applyUserAgent(GetItemRequest.builder()) - .key(key) + private T load(DynamoDBMapperTableModel model, + Map key, + String tableName, + DynamoDBMapperConfig config) { + GetItemRequest rq = applyUserAgent(GetItemRequest.builderWithKeyTrusted(key)) .tableName(tableName) .consistentRead(config.getConsistentReads() == ConsistentReads.CONSISTENT) .build(); @@ -380,10 +385,8 @@ public T load(T keyObject, DynamoDBMapperConfig config) { return null; } - T object = privateMarshallIntoObject( - toParameters(itemAttributes, clazz, tableName, config)); - - return object; + return privateMarshallIntoObject( + toParameters(itemAttributes, model, model.targetType(), tableName, config)); } @Override @@ -391,7 +394,9 @@ public T load(Class clazz, Object hashKey, Object rangeKey config = mergeConfig(config); DynamoDBMapperTableModel model = getTableModel(clazz, config); T keyObject = model.createKey(hashKey, rangeKey); - return load(keyObject, config); + Map key = model.convertKey(keyObject); + String tableName = getTableName(clazz, keyObject, config); + return load(model, key, tableName, config); } @Override @@ -407,13 +412,13 @@ public T marshallIntoObject(Class clazz, Map item /** * The one true implementation of marshallIntoObject. */ + @SuppressWarnings("unchecked") private T privateMarshallIntoObject( AttributeTransformer.Parameters parameters) { - Class clazz = parameters.getModelClass(); Map values = untransformAttributes(parameters); - DynamoDBMapperTableModel model = getTableModel(clazz, parameters.getMapperConfig()); + DynamoDBMapperTableModel model = ((TransformerParameters) parameters).model; return model.unconvert(values); } @@ -473,18 +478,28 @@ public void save(T object, if (usePut) { saveObjectHandler = this.new SaveObjectHandler(clazz, object, - tableName, finalConfig, saveExpression) { + model, tableName, finalConfig, saveExpression) { + + private final Map attributeValues = + new HashMap(); @Override protected void onPrimaryKeyAttributeValue(String attributeName, AttributeValue keyAttributeValue) { - /* Treat key values as common attribute value updates. */ - getAttributeValueUpdates().put(attributeName, - AttributeValueUpdate.builder().value(keyAttributeValue) - .action("PUT").build()); + attributeValues.put(attributeName, keyAttributeValue); } - /* Use default implementation of onNonKeyAttribute(...) */ + @Override + protected void onNonKeyAttribute(String attributeName, + AttributeValue currentValue) { + attributeValues.put(attributeName, currentValue); + } + + @Override + void onAutoGeneratedAttribute(String attributeName, + AttributeValue generatedValue) { + attributeValues.put(attributeName, generatedValue); + } @Override protected void onNullNonKeyAttribute(String attributeName) { @@ -495,12 +510,12 @@ protected void onNullNonKeyAttribute(String attributeName) { @Override protected void executeLowLevelRequest() { /* Send a putItem request */ - doPutItem(); + doPutItem(attributeValues); } }; } else { saveObjectHandler = this.new SaveObjectHandler(clazz, object, - tableName, finalConfig, saveExpression) { + model, tableName, finalConfig, saveExpression) { @Override protected void onPrimaryKeyAttributeValue(String attributeName, @@ -595,6 +610,8 @@ protected abstract class SaveObjectHandler { protected final Object object; protected final Class clazz; + private final Class modelClass; + private DynamoDBMapperTableModel model; private final String tableName; private final DynamoDBMapperConfig saveConfig; @@ -629,6 +646,7 @@ protected abstract class SaveObjectHandler { * @param saveConfig The mapper configuration used for this save. * @param saveExpression The save expression, including the user-provided conditions and an optional logic operator. */ + @SuppressWarnings("unchecked") public SaveObjectHandler( Class clazz, Object object, @@ -637,6 +655,7 @@ public SaveObjectHandler( DynamoDBSaveExpression saveExpression) { this.clazz = clazz; + this.modelClass = (Class) (Class) clazz; this.object = object; this.tableName = tableName; this.saveConfig = saveConfig; @@ -657,11 +676,26 @@ public SaveObjectHandler( primaryKeys = new HashMap(); } + @SuppressWarnings("unchecked") + SaveObjectHandler( + Class clazz, + T object, + DynamoDBMapperTableModel model, + String tableName, + DynamoDBMapperConfig saveConfig, + DynamoDBSaveExpression saveExpression) { + + this(clazz, object, tableName, saveConfig, saveExpression); + this.model = (DynamoDBMapperTableModel) (DynamoDBMapperTableModel) model; + } + /** * The general workflow of a save operation. */ public void execute() { - DynamoDBMapperTableModel model = getTableModel((Class)clazz, saveConfig); + if (model == null) { + model = getTableModel(modelClass, saveConfig); + } for ( DynamoDBMapperFieldModel field : model.fields() ) { if ( canGenerate(model, object, getLocalSaveBehavior(), field) ) { if ( field.keyType() != null || field.indexed() ) { @@ -732,6 +766,12 @@ protected void onNonKeyAttribute(String attributeName, AttributeValue currentVal .value(currentValue).action("PUT").build()); } + /** Store an auto-generated attribute value for the low-level request. */ + void onAutoGeneratedAttribute(String attributeName, AttributeValue generatedValue) { + updateValues.put(attributeName, AttributeValueUpdate.builder() + .value(generatedValue).action("PUT").build()); + } + /** * Implement this method for necessary operations when a non-key * attribute is set null in the object. @@ -803,7 +843,8 @@ protected UpdateItemResponse doUpdateItem() { .key(getPrimaryKeyAttributeValues()) .attributeUpdates( transformAttributeUpdates( - this.clazz, + model, + modelClass, getTableName(), getPrimaryKeyAttributeValues(), getAttributeValueUpdates(), @@ -829,15 +870,18 @@ protected UpdateItemResponse doUpdateItem() { */ protected PutItemResponse doPutItem() { Map attributeValues = convertToItem(getAttributeValueUpdates()); + return doPutItem(attributeValues); + } + PutItemResponse doPutItem(Map attributeValues) { attributeValues = transformAttributes( toParameters(attributeValues, - this.clazz, + model, + modelClass, getTableName(), saveConfig)); - PutItemRequest req = applyUserAgent(PutItemRequest.builder()) + PutItemRequest req = applyUserAgent(PutItemRequest.builderWithItemTrusted(attributeValues)) .tableName(getTableName()) - .item(attributeValues) .expected(mergeExpectedAttributeValueConditions()) .conditionalOperator(userProvidedConditionOperator) .build(); @@ -851,7 +895,7 @@ protected PutItemResponse doPutItem() { */ private void onAutoGenerate(DynamoDBMapperFieldModel field) { AttributeValue value = field.convert(field.generate(field.get(object))); - updateValues.put(field.name(), AttributeValueUpdate.builder().action("PUT").value(value).build()); + onAutoGeneratedAttribute(field.name(), value); inMemoryUpdates.add(new ValueUpdate(field, value, object)); } @@ -921,7 +965,8 @@ private Map convertToItem(Map transformAttributeUpdates( - final Class clazz, + final DynamoDBMapperTableModel model, + final Class clazz, final String tableName, final Map keys, final Map updateValues, @@ -942,7 +987,7 @@ private Map transformAttributeUpdates( } AttributeTransformer.Parameters parameters = - toParameters(item, true, clazz, tableName, config); + toParameters(item, model, true, clazz, tableName, config); String hashKey = parameters.getHashKeyName(); @@ -1175,7 +1220,7 @@ public List batchWrite(Iterable objectsToWrite, toParameters(attributeValues, clazz, tableName, config); requestItems.add(tableName, WriteRequest.builder() - .putRequest(PutRequest.builder().item(transformAttributes(parameters)).build()) + .putRequest(PutRequest.builderWithItemTrusted(transformAttributes(parameters)).build()) .build()); } @@ -2023,6 +2068,33 @@ private static void processKeyConditions( queryRequest.keyConditions(keyConditions); } + private AttributeTransformer.Parameters toParameters( + final Map attributeValues, + final DynamoDBMapperTableModel model, + final Class modelClass, + final String tableName, + final DynamoDBMapperConfig mapperConfig) { + + return toParameters(attributeValues, model, false, modelClass, tableName, mapperConfig); + } + + private AttributeTransformer.Parameters toParameters( + final Map attributeValues, + final DynamoDBMapperTableModel model, + final boolean partialUpdate, + final Class modelClass, + final String tableName, + final DynamoDBMapperConfig mapperConfig) { + + return new TransformerParameters( + model, + attributeValues, + partialUpdate, + modelClass, + mapperConfig, + tableName); + } + private AttributeTransformer.Parameters toParameters( final Map attributeValues, final Class modelClass, @@ -2147,7 +2219,10 @@ private Map transformAttributes( final AttributeTransformer.Parameters parameters) { if (transformer != null) { - return transformer.transform(parameters); + Map transformed = transformer.transform(parameters); + return transformed == null + ? null + : Collections.unmodifiableMap(new HashMap<>(transformed)); } else { return parameters.getAttributeValues(); } @@ -2448,8 +2523,7 @@ private Put generatePut(String tableName, Map attributeValueMap, ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure, DynamoDBTransactionWriteExpression writeExpression) { - Put.Builder put = Put.builder(); - put.item(attributeValueMap); + Put.Builder put = Put.builderWithItemTrusted(attributeValueMap); put.tableName(tableName); if (returnValuesOnConditionCheckFailure != null) { put.returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure); diff --git a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactories.java b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactories.java index 42f6b9abea4f..d6eac78eee44 100644 --- a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactories.java +++ b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactories.java @@ -618,7 +618,7 @@ public List get(AttributeValue value) { } @Override public AttributeValue build(List o) { - return AttributeValue.createL(o); + return AttributeValue.createLTrusted(o); } } @@ -663,7 +663,7 @@ public List get(AttributeValue value) { } @Override public AttributeValue build(List o) { - return AttributeValue.createL(o); + return AttributeValue.createLTrusted(o); } } @@ -691,7 +691,7 @@ public Map get(AttributeValue value) { } @Override public AttributeValue build(Map o) { - return AttributeValue.createM(o); + return AttributeValue.createMTrusted(o); } } @@ -727,7 +727,7 @@ public Map get(AttributeValue value) { } @Override public AttributeValue build(Map o) { - return AttributeValue.createM(o); + return AttributeValue.createMTrusted(o); } } diff --git a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/CollectionToListMarshaller.java b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/CollectionToListMarshaller.java index dfa3addd94c0..8b756caeb685 100644 --- a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/CollectionToListMarshaller.java +++ b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/CollectionToListMarshaller.java @@ -67,7 +67,7 @@ public AttributeValue marshall(Object obj) { values.add(value); } - return AttributeValue.builder().l(values).build(); + return AttributeValue.createLTrusted(values); } public ArgumentMarshaller getMemberMarshaller() { diff --git a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/MapToMapMarshaller.java b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/MapToMapMarshaller.java index 2dc995b7de45..c9da48ab1002 100644 --- a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/MapToMapMarshaller.java +++ b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/MapToMapMarshaller.java @@ -70,7 +70,7 @@ public AttributeValue marshall(Object obj) { values.put(entry.getKey(), value); } - return AttributeValue.builder().m(values).build(); + return AttributeValue.createMTrusted(values); } public ArgumentMarshaller getMemberMarshaller() { diff --git a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/ObjectToMapMarshaller.java b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/ObjectToMapMarshaller.java index 8a524b47ec26..55cc14dbade4 100644 --- a/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/ObjectToMapMarshaller.java +++ b/services-custom/dynamodb-mapper/src/main/java/software/amazon/awssdk/mapper/dynamodb/internal/marshallers/ObjectToMapMarshaller.java @@ -48,6 +48,6 @@ public ObjectToMapMarshaller(ItemConverter converter) { @Override public AttributeValue marshall(Object obj) { Map values = converter.convert(obj); - return AttributeValue.builder().m(values).build(); + return AttributeValue.createMTrusted(values); } } diff --git a/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapperBuilderTest.java b/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapperBuilderTest.java index 3ae4bb4b5ae6..73fe19182e32 100644 --- a/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapperBuilderTest.java +++ b/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/DynamoDBMapperBuilderTest.java @@ -24,6 +24,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import org.junit.Before; @@ -32,6 +33,7 @@ import software.amazon.awssdk.mapper.dynamodb.DynamoDBMapperConfig.ConsistentReads; import software.amazon.awssdk.mapper.dynamodb.DynamoDBMapperConfig.SaveBehavior; import software.amazon.awssdk.mapper.dynamodb.DynamoDBMapperConfig.TableNameOverride; +import software.amazon.awssdk.mapper.dynamodb.internal.DynamoDBMapperModelFactory; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; @@ -144,6 +146,46 @@ public void build_withAttributeTransformer_transformsOnWrite() { assertEquals("transformed", captor.getValue().item().get("value").s()); } + @Test + public void build_withAttributeTransformer_requestDoesNotAliasTransformerResult() { + RetainingTransformer transformer = new RetainingTransformer(); + DynamoDBMapper mapper = DynamoDBMapper.builder() + .dynamoDbClient(ddb) + .mapperConfig(SaveBehavior.CLOBBER.config()) + .attributeTransformer(transformer) + .build(); + + mapper.save(item("new")); + + ArgumentCaptor captor = ArgumentCaptor.forClass(PutItemRequest.class); + verify(ddb).putItem(captor.capture()); + transformer.returned.put("mutated", AttributeValue.builder().s("later").build()); + assertFalse(captor.getValue().item().containsKey("mutated")); + } + + @Test + public void build_load_resolvesTableModelOncePerOperation() throws Exception { + DynamoDBMapper mapper = DynamoDBMapper.builder().dynamoDbClient(ddb).build(); + CountingModelFactory models = installCountingModelFactory(mapper); + + mapper.load(StringItem.class, HASH_KEY); + + assertEquals(1, models.lookups); + } + + @Test + public void build_clobberSave_resolvesTableModelOncePerOperation() throws Exception { + DynamoDBMapper mapper = DynamoDBMapper.builder() + .dynamoDbClient(ddb) + .mapperConfig(SaveBehavior.CLOBBER.config()) + .build(); + CountingModelFactory models = installCountingModelFactory(mapper); + + mapper.save(item("new")); + + assertEquals(1, models.lookups); + } + @Test public void build_withLaterSetterCall_lastValueWins() { DynamoDBMapper mapper = DynamoDBMapper.builder() @@ -187,6 +229,14 @@ private static Map storedItem() { return item; } + private static CountingModelFactory installCountingModelFactory(DynamoDBMapper mapper) throws Exception { + CountingModelFactory counting = new CountingModelFactory(StandardModelFactories.of()); + Field models = DynamoDBMapper.class.getDeclaredField("models"); + models.setAccessible(true); + models.set(mapper, counting); + return counting; + } + @DynamoDBTable(tableName = "M_String") public static class StringItem { private String id; @@ -229,4 +279,34 @@ private static Map withValue(Map return copy; } } + + private static final class RetainingTransformer implements AttributeTransformer { + private Map returned; + + @Override + public Map transform(Parameters parameters) { + returned = new HashMap<>(parameters.getAttributeValues()); + return returned; + } + + @Override + public Map untransform(Parameters parameters) { + return parameters.getAttributeValues(); + } + } + + private static final class CountingModelFactory implements DynamoDBMapperModelFactory { + private final DynamoDBMapperModelFactory delegate; + private int lookups; + + private CountingModelFactory(DynamoDBMapperModelFactory delegate) { + this.delegate = delegate; + } + + @Override + public TableFactory getTableFactory(DynamoDBMapperConfig config) { + lookups++; + return delegate.getTableFactory(config); + } + } } diff --git a/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactoriesV2Test.java b/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactoriesV2Test.java index c4aee1b667fa..3be4cf3120aa 100644 --- a/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactoriesV2Test.java +++ b/services-custom/dynamodb-mapper/src/test/java/software/amazon/awssdk/mapper/dynamodb/StandardModelFactoriesV2Test.java @@ -17,6 +17,7 @@ import software.amazon.awssdk.mapper.dynamodb.internal.DynamoDBMapperModelFactory; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.math.BigDecimal; @@ -31,6 +32,7 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; @@ -332,6 +334,24 @@ public void testMap() { convert("getMap", Collections.singletonMap("a", null)).m()); } + @Test + public void emptyListAndMap_areExplicitValuesAndRoundTrip() { + DynamoDBMapperTableModel model = models.getTable(EmptyCollections.class); + DynamoDBMapperFieldModel> listField = model.field("list"); + DynamoDBMapperFieldModel> mapField = model.field("map"); + + AttributeValue listValue = listField.convert(Collections.emptyList()); + AttributeValue mapValue = mapField.convert(Collections.emptyMap()); + + assertTrue(listValue.hasL()); + assertTrue(listValue.l().isEmpty()); + assertEquals(Collections.emptyList(), listField.unconvert(listValue)); + + assertTrue(mapValue.hasM()); + assertTrue(mapValue.m().isEmpty()); + assertEquals(Collections.emptyMap(), mapField.unconvert(mapValue)); + } + @Test public void testSetMap() { assertEquals(new HashMap() {{ @@ -383,4 +403,27 @@ protected AttributeValue convert(String getter, Object value) { } } + public static final class EmptyCollections { + private List list; + private Map map; + + @DynamoDBAttribute(attributeName = "list") + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + @DynamoDBAttribute(attributeName = "map") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + } + }