-
Notifications
You must be signed in to change notification settings - Fork 931
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
Merged
RanVaknin
merged 14 commits into
master
from
rvaknin/ddb-enhanced-client-versioned-record-custom-startAt
Jul 22, 2025
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
31c550b
Adding annotation support
RanVaknin 9d21fa8
Making annotation values nullable to know if initial value is explici…
RanVaknin 83a5ff8
Added changelog with attribution
RanVaknin 0220253
Fix checkstyle
RanVaknin eb820c4
Adding japicmp excludes block
RanVaknin 22d23d0
Adding additional test coverage to account for all isInitialVersion c…
RanVaknin 637df9d
Removing logger config file
RanVaknin 192a858
porting version from Integer to Long, removing refactoring
RanVaknin 1a6e558
refactoring and adding test coverage
RanVaknin 27a0fbe
adding annotation test
RanVaknin 244aa9a
adding localstack test, removing optional from function signature
RanVaknin f745d70
fix checkstyle
RanVaknin b8e0ad9
Adding overflow protection
RanVaknin 18bb268
Fixed edge case in isInitialVersion, fixed javadoc and typos
RanVaknin 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
6 changes: 6 additions & 0 deletions
6
.changes/next-release/feature-DynamoDBEnhancedClient-2a501d8.json
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,6 @@ | ||
{ | ||
"type": "feature", | ||
"category": "DynamoDB Enhanced Client", | ||
"contributor": "akiesler", | ||
"description": "Support for Version Starting at 0 with Configurable Increment" | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
|
@@ -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"); | ||
RanVaknin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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() { | ||
|
@@ -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"); | ||
RanVaknin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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); | ||
} | ||
} | ||
|
@@ -106,31 +146,53 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex | |
String attributeKeyRef = keyRef(versionAttributeKey.get()); | ||
AttributeValue newVersionValue; | ||
Expression condition; | ||
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(); | ||
AttributeValue existingVersionValue = itemToTransform.get(versionAttributeKey.get()); | ||
Long versionStartAtFromAnnotation = context.tableMetadata() | ||
.customMetadataObject(VersionAttribute.START_AT_METADATA_KEY, Long.class) | ||
.orElse(this.startAt); | ||
Long versionIncrementByFromAnnotation = context.tableMetadata() | ||
.customMetadataObject(VersionAttribute.INCREMENT_BY_METADATA_KEY, Long.class) | ||
.orElse(this.incrementBy); | ||
|
||
|
||
if (isInitialVersion(existingVersionValue, versionStartAtFromAnnotation)) { | ||
newVersionValue = AttributeValue.builder() | ||
.n(Long.toString(versionStartAtFromAnnotation + versionIncrementByFromAnnotation)) | ||
.build(); | ||
condition = Expression.builder() | ||
.expression(String.format("attribute_not_exists(%s)", attributeKeyRef)) | ||
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get())) | ||
.build(); | ||
} else { | ||
// Existing record, increment version | ||
if (existingVersionValue.get().n() == null) { | ||
if (existingVersionValue.n() == null) { | ||
// In this case a non-null version attribute is present, but it's not an N | ||
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.n()); | ||
String existingVersionValueKey = VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER.apply(versionAttributeKey.get()); | ||
newVersionValue = AttributeValue.builder().n(Integer.toString(existingVersion + 1)).build(); | ||
|
||
long increment = versionIncrementByFromAnnotation; | ||
|
||
/* | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: the convention for inline comment is |
||
Since the new incrementBy and StartAt functionality can now accept any positive number, though unlikely | ||
to happen in a real life scenario, we should add overflow protection. | ||
*/ | ||
if (existingVersion > Long.MAX_VALUE - increment) { | ||
throw new IllegalStateException( | ||
String.format("Version overflow detected. Current version %d + increment %d would exceed Long.MAX_VALUE", | ||
existingVersion, increment)); | ||
} | ||
|
||
newVersionValue = AttributeValue.builder().n(Long.toString(existingVersion + increment)).build(); | ||
RanVaknin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
condition = Expression.builder() | ||
.expression(String.format("%s = %s", attributeKeyRef, existingVersionValueKey)) | ||
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get())) | ||
.expressionValues(Collections.singletonMap(existingVersionValueKey, | ||
existingVersionValue.get())) | ||
existingVersionValue)) | ||
.build(); | ||
} | ||
|
||
|
@@ -142,13 +204,55 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex | |
.build(); | ||
} | ||
|
||
private boolean isInitialVersion(AttributeValue existingVersionValue, Long versionStartAtFromAnnotation) { | ||
if (existingVersionValue == null || isNullAttributeValue(existingVersionValue)) { | ||
return true; | ||
} | ||
|
||
if (existingVersionValue.n() != null) { | ||
long currentVersion = Long.parseLong(existingVersionValue.n()); | ||
// If annotation value is present, use it, otherwise fall back to the extension's value | ||
Long effectiveStartAt = versionStartAtFromAnnotation != null ? versionStartAtFromAnnotation : this.startAt; | ||
return currentVersion == effectiveStartAt; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
@NotThreadSafe | ||
public static final class Builder { | ||
private Long startAt; | ||
private Long incrementBy; | ||
|
||
private Builder() { | ||
} | ||
|
||
/** | ||
* Sets the startAt used to compare if a record is the initial version of a record. | ||
* Default value - {@code 0}. | ||
* | ||
* @param startAt the starting value for version comparison, must not be negative | ||
* @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 the amount to increment the version by, must be greater than 0 | ||
* @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); | ||
} | ||
} | ||
} |
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
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.
Uh oh!
There was an error while loading. Please reload this page.