Skip to content

DDB Enhanced: Allow custom versioning #6019

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
wants to merge 8 commits into
base: master
Choose a base branch
from
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
@@ -0,0 +1,6 @@
{
"type": "feature",
"category": "DynamoDB Enhanced Client",
"contributor": "akiesler",
"description": "DynamoDB Enhanced Client: Support for Version Starting at 0 with Configurable Increment"
}
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,8 @@
<includeModule>polly</includeModule>
</includeModules>
<excludes>
<exclude>software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute#incrementBy()</exclude>
<exclude>software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute#startAt()</exclude>
<exclude>*.internal.*</exclude>
<exclude>software.amazon.awssdk.thirdparty.*</exclude>
<exclude>software.amazon.awssdk.regions.*</exclude>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,15 @@ public int hashCode() {
return result;
}

@Override
public String toString() {
return "Expression{" +
"expression='" + expression + '\'' +
", expressionValues=" + expressionValues +
", expressionNames=" + expressionNames +
'}';
}

/**
* A builder for {@link Expression}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;

/**
* This extension implements optimistic locking on record writes by means of a 'record version number' that is used
Expand Down Expand Up @@ -61,7 +62,18 @@ public final class VersionedRecordExtension implements DynamoDbEnhancedClientExt
private static final String CUSTOM_METADATA_KEY = "VersionedRecordExtension:VersionAttribute";
private static final VersionAttribute VERSION_ATTRIBUTE = new VersionAttribute();

private VersionedRecordExtension() {
private final long startAt;
private final long incrementBy;

private VersionedRecordExtension(Long startAt, Long incrementBy) {
Validate.isNotNegativeOrNull(startAt, "startAt");

if (incrementBy != null && incrementBy < 1) {
throw new IllegalArgumentException("IncrementBy must be greater than 0.");
}

this.startAt = startAt != null ? startAt : 0L;
this.incrementBy = incrementBy != null ? incrementBy : 1L;
}

public static Builder builder() {
Expand All @@ -75,19 +87,47 @@ private AttributeTags() {
public static StaticAttributeTag versionAttribute() {
return VERSION_ATTRIBUTE;
}

public static StaticAttributeTag versionAttribute(Long startAt, Long incrementBy) {
return new VersionAttribute(startAt, incrementBy);
}
}

private static class VersionAttribute implements StaticAttributeTag {
private static final class VersionAttribute implements StaticAttributeTag {
private static final String START_AT_METADATA_KEY = "VersionedRecordExtension:StartAt";
private static final String INCREMENT_BY_METADATA_KEY = "VersionedRecordExtension:IncrementBy";

private final Long startAt;
private final Long incrementBy;

private VersionAttribute() {
this.startAt = null;
this.incrementBy = null;
}

private VersionAttribute(Long startAt, Long incrementBy) {
this.startAt = startAt;
this.incrementBy = incrementBy;
}

@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType) {
if (attributeValueType != AttributeValueType.N) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' of type %s is not a suitable type to be used as a version attribute. Only type 'N' " +
"is supported.", attributeName, attributeValueType.name()));
"is supported.", attributeName, attributeValueType.name()));
}

Validate.isNotNegativeOrNull(startAt, "startAt");

if (incrementBy != null && incrementBy < 1) {
throw new IllegalArgumentException("IncrementBy must be greater than 0.");
}

return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, attributeName)
.addCustomMetadataObject(START_AT_METADATA_KEY, startAt)
.addCustomMetadataObject(INCREMENT_BY_METADATA_KEY, incrementBy)
.markAttributeAsKey(attributeName, attributeValueType);
}
}
Expand All @@ -109,9 +149,24 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex
Optional<AttributeValue> existingVersionValue =
Optional.ofNullable(itemToTransform.get(versionAttributeKey.get()));

if (!existingVersionValue.isPresent() || isNullAttributeValue(existingVersionValue.get())) {
// First version of the record
newVersionValue = AttributeValue.builder().n("1").build();
Optional<Long> versionStartAtFromAnnotation = context.tableMetadata()
.customMetadataObject(VersionAttribute.START_AT_METADATA_KEY,
Long.class);

Optional<Long> versionIncrementByFromAnnotation = context.tableMetadata()
.customMetadataObject(VersionAttribute.INCREMENT_BY_METADATA_KEY,
Long.class);

if (!existingVersionValue.isPresent() || isNullAttributeValue(existingVersionValue.get()) ||
(existingVersionValue.get().n() != null &&
((versionStartAtFromAnnotation.isPresent() &&
Long.parseLong(existingVersionValue.get().n()) == versionStartAtFromAnnotation.get()) ||
Long.parseLong(existingVersionValue.get().n()) == this.startAt))) {

long startValue = versionStartAtFromAnnotation.orElse(this.startAt);
long increment = versionIncrementByFromAnnotation.orElse(this.incrementBy);

newVersionValue = AttributeValue.builder().n(Long.toString(startValue + increment)).build();
condition = Expression.builder()
.expression(String.format("attribute_not_exists(%s)", attributeKeyRef))
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get()))
Expand All @@ -123,9 +178,12 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex
throw new IllegalArgumentException("Version attribute appears to be the wrong type. N is required.");
}

int existingVersion = Integer.parseInt(existingVersionValue.get().n());
long existingVersion = Long.parseLong(existingVersionValue.get().n());
String existingVersionValueKey = VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER.apply(versionAttributeKey.get());
newVersionValue = AttributeValue.builder().n(Integer.toString(existingVersion + 1)).build();

long increment = versionIncrementByFromAnnotation.orElse(this.incrementBy);
newVersionValue = AttributeValue.builder().n(Long.toString(existingVersion + increment)).build();

condition = Expression.builder()
.expression(String.format("%s = %s", attributeKeyRef, existingVersionValueKey))
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get()))
Expand All @@ -144,11 +202,38 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex

@NotThreadSafe
public static final class Builder {
private Long startAt = 0L;
private Long incrementBy = 1L;

private Builder() {
}

/**
* Sets the startAt used to compare if a record is the initial version of a record.
* Default value - {@code 0}.
*
* @param startAt
* @return the builder instance
*/
public Builder startAt(Long startAt) {
this.startAt = startAt;
return this;
}

/**
* Sets the amount to increment the version by with each subsequent update.
* Default value - {@code 1}.
*
* @param incrementBy
* @return the builder instance
*/
public Builder incrementBy(Long incrementBy) {
this.incrementBy = incrementBy;
return this;
}

public VersionedRecordExtension build() {
return new VersionedRecordExtension();
return new VersionedRecordExtension(this.startAt, this.incrementBy);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,20 @@
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(VersionRecordAttributeTags.class)
public @interface DynamoDbVersionAttribute {
/**
* The starting value for the version attribute.
* Default value - {@code 0}.
*
* @return the starting value
*/
long startAt() default 0;

/**
* The amount to increment the version by with each update.
* Default value - {@code 1}.
*
* @return the increment value
*/
long incrementBy() default 1;

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ private VersionRecordAttributeTags() {
}

public static StaticAttributeTag attributeTagFor(DynamoDbVersionAttribute annotation) {
return VersionedRecordExtension.AttributeTags.versionAttribute();
return VersionedRecordExtension.AttributeTags.versionAttribute(annotation.startAt(), annotation.incrementBy());
}
}
Loading
Loading