Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(dynamodb): keep expired items visible until TTL deletion (#5555)

Aniket Shuklae919560e3c1c
diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md
index 14bd279811..1531c71ee0 100644
--- a/docs/services/dynamodb.md
+++ b/docs/services/dynamodb.md
@@ -88,8 +88,9 @@ the reset.
With TTL enabled, a sweep runs every 60 seconds and deletes the items whose TTL attribute holds an
epoch time in the past. Each deletion writes a `REMOVE` record to the table's stream and is
-forwarded to an active Kinesis streaming destination. Between sweeps, reads already leave expired
-items out.
+forwarded to an active Kinesis streaming destination. Between sweeps, expired items remain visible
+to reads until they are physically deleted, as on AWS. Use a filter expression on the TTL attribute
+to exclude expired items from a Query or Scan result.
As in AWS, the records of a TTL deletion carry the DynamoDB service identity, which a `DeleteItem`
removal does not. The member names depend on where the record is read. The DynamoDB Streams API
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
index 5d4e9e7323..4149153b96 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
@@ -740,7 +740,7 @@ public class DynamoDbService {
}
/**
- * Every live item of the table, expired ones dropped. SearchVectors reads the whole table:
+ * Every stored item of the table, including expired items pending TTL deletion. SearchVectors reads the whole table:
* it has no page boundary and no cursor, so it cannot go through {@link #scan}, which stops
* at the 1 MB response cap.
*/
@@ -750,9 +750,7 @@ public class DynamoDbService {
if (items == null) {
return List.of();
}
- return items.values().stream()
- .filter(item -> !isExpired(item, table))
- .toList();
+ return List.copyOf(items.values());
}
/**
@@ -997,10 +995,6 @@ public class DynamoDbService {
return null;
}
JsonNode item = items.get(itemKey);
- if (item != null && isExpired(item, table)) {
- LOG.tracev("Got item from {0}: key={1} item=<expired>", canonicalTableName, itemKey);
- return null;
- }
LOG.tracev("Got item from {0}: key={1} item={2}", canonicalTableName, itemKey, item);
return item;
}
@@ -1385,9 +1379,6 @@ public class DynamoDbService {
.toList();
}
- // Filter out TTL-expired items
- results = results.stream().filter(item -> !isExpired(item, table)).toList();
-
// Sort by the full (possibly composite) sort key, comparing each attribute in key-schema
// order. Using only the first sort-key attribute would ignore the remaining components
// (e.g. a "requestStateQuery RANGE, createdAt RANGE" index would never order by createdAt),
@@ -1572,11 +1563,11 @@ public class DynamoDbService {
totalScanned++;
scannedItems.add(item);
lastScanned = item;
- if (!isExpired(item, table)) {
- boolean matched = (filterExpression == null
- || matchesFilterExpression(item, filterExpression, expressionAttrNames, expressionAttrValues))
- && (scanFilter == null || matchesScanFilter(item, scanFilter));
- if (matched) results.add(item);
+ boolean matched = (filterExpression == null
+ || matchesFilterExpression(item, filterExpression, expressionAttrNames, expressionAttrValues))
+ && (scanFilter == null || matchesScanFilter(item, scanFilter));
+ if (matched) {
+ results.add(item);
}
// Limit caps SCANNED items (those read), not matched items. DynamoDB does
// not look ahead when it stops at the Limit boundary: it always surfaces a
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java
index e4aae67e4a..e1fd3fac51 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java
@@ -1209,7 +1209,7 @@ public class NativeDynamoDbJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
if ("COUNT".equals(select)) {
- response.put("Count", result.items().size());
+ response.put("Count", queryItems.size());
response.put("ScannedCount", result.scannedCount());
} else {
ArrayNode itemsArray = objectMapper.createArrayNode();
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlForwardingTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlForwardingTest.java
index 500b125f4c..d6fe442076 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlForwardingTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlForwardingTest.java
@@ -195,10 +195,8 @@ class DynamoDbTtlForwardingTest {
}
// Direct proof of persistence: the sweep must have written the trimmed map back to the
- // underlying item store. Inspecting the stored map (rather than getItem) is what makes this
- // fail if persistItemsForAccount is dropped: getItem would still return null for expired
- // rows via isExpired even though the stale rows remained physically persisted. putItem
- // during seeding persisted 'expired' rows here, so the store must now hold none of them.
+ // underlying item store, independently of the live cache. putItem during seeding
+ // persisted expired rows here, so the store must now hold none of them.
Map<String, JsonNode> persisted = itemStore.get("us-east-1::TtlTable").orElseGet(Map::of);
assertTrue(persisted.isEmpty(),
() -> "TTL removals must be persisted to the item store; stale rows still present: "
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlVisibilityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlVisibilityIntegrationTest.java
new file mode 100644
index 0000000000..37b9adda64
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTtlVisibilityIntegrationTest.java
@@ -0,0 +1,165 @@
+package io.github.hectorvent.floci.services.dynamodb;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+@QuarkusTest
+class DynamoDbTtlVisibilityIntegrationTest {
+
+ private static final String REGION = "us-east-1";
+
+ @Inject
+ DynamoDbService service;
+
+ @Inject
+ DynamoDbTtlService ttlService;
+
+ private String tableName;
+ private long now;
+
+ @BeforeAll
+ static void configureContentTypes() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @BeforeEach
+ void createTtlTable() {
+ ttlService.pause();
+ tableName = "TtlVisibility" + UUID.randomUUID().toString().replace("-", "");
+ now = Instant.now().getEpochSecond();
+ call("CreateTable", """
+ {"TableName":"%s","KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}],
+ "AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"}],
+ "BillingMode":"PAY_PER_REQUEST"}
+ """.formatted(tableName)).statusCode(200);
+ call("UpdateTimeToLive", """
+ {"TableName":"%s","TimeToLiveSpecification":{"Enabled":true,"AttributeName":"ttl"}}
+ """.formatted(tableName)).statusCode(200);
+ putItem("expired", now - 3600);
+ putItem("future", now + 3600);
+ }
+
+ @AfterEach
+ void cleanUp() {
+ try {
+ service.deleteTable(tableName, REGION);
+ } finally {
+ ttlService.resume();
+ }
+ }
+
+ @Test
+ void getItemReturnsExpiredItemsUntilTheSweepDeletesThem() {
+ getExpired().statusCode(200).body("Item.pk.S", equalTo("expired"));
+
+ service.deleteExpiredItems();
+
+ getExpired().statusCode(200).body("Item", nullValue());
+ call("Scan", "{\"TableName\":\"%s\"}".formatted(tableName))
+ .statusCode(200).body("Count", equalTo(1)).body("Items[0].pk.S", equalTo("future"));
+ }
+
+ @Test
+ void queryReturnsExpiredItemsUnlessTheCallerFiltersThem() {
+ call("Query", """
+ {"TableName":"%s","KeyConditionExpression":"pk = :pk",
+ "ExpressionAttributeValues":{":pk":{"S":"expired"}}}
+ """.formatted(tableName))
+ .statusCode(200).body("Count", equalTo(1)).body("Items[0].pk.S", equalTo("expired"));
+ call("Query", """
+ {"TableName":"%s","KeyConditionExpression":"pk = :pk","FilterExpression":"#ttl > :now",
+ "ExpressionAttributeNames":{"#ttl":"ttl"},
+ "ExpressionAttributeValues":{":pk":{"S":"expired"},":now":{"N":"%d"}}}
+ """.formatted(tableName, now))
+ .statusCode(200).body("Count", equalTo(0)).body("ScannedCount", equalTo(1));
+ }
+
+ @Test
+ void legacyTtlQueryFilterUsesTheFilteredCount() {
+ String request = """
+ {"TableName":"%s","KeyConditions":{"pk":{"ComparisonOperator":"EQ",
+ "AttributeValueList":[{"S":"expired"}]}},
+ "QueryFilter":{"ttl":{"ComparisonOperator":"GT","AttributeValueList":[{"N":"%d"}]}},
+ "Select":"COUNT"}
+ """.formatted(tableName, now);
+ call("Query", request).statusCode(200)
+ .body("Count", equalTo(0)).body("ScannedCount", equalTo(1)).body("Items", nullValue());
+ }
+
+ @Test
+ void scanReturnsExpiredItemsAndPreservesExplicitFiltersAndPagination() {
+ call("Scan", "{\"TableName\":\"%s\"}".formatted(tableName))
+ .statusCode(200).body("Count", equalTo(2)).body("ScannedCount", equalTo(2));
+ call("Scan", """
+ {"TableName":"%s","FilterExpression":"#ttl > :now",
+ "ExpressionAttributeNames":{"#ttl":"ttl"},"ExpressionAttributeValues":{":now":{"N":"%d"}}}
+ """.formatted(tableName, now))
+ .statusCode(200).body("Count", equalTo(1)).body("ScannedCount", equalTo(2))
+ .body("Items[0].pk.S", equalTo("future"));
+ call("Scan", "{\"TableName\":\"%s\",\"Limit\":1}".formatted(tableName))
+ .statusCode(200).body("Count", equalTo(1)).body("Items[0].pk.S", equalTo("expired"))
+ .body("LastEvaluatedKey.pk.S", equalTo("expired"));
+ call("Scan", """
+ {"TableName":"%s","ExclusiveStartKey":{"pk":{"S":"expired"}}}
+ """.formatted(tableName))
+ .statusCode(200).body("Count", equalTo(1)).body("Items[0].pk.S", equalTo("future"));
+ }
+
+ @Test
+ void batchTransactionalAndPartiQlReadsReturnPendingTtlItems() {
+ call("BatchGetItem", """
+ {"RequestItems":{"%s":{"Keys":[{"pk":{"S":"expired"}}]}}}
+ """.formatted(tableName))
+ .statusCode(200).body("Responses." + tableName + "[0].pk.S", equalTo("expired"));
+ call("TransactGetItems", """
+ {"TransactItems":[{"Get":{"TableName":"%s","Key":{"pk":{"S":"expired"}}}}]}
+ """.formatted(tableName))
+ .statusCode(200).body("Responses[0].Item.pk.S", equalTo("expired"));
+ call("ExecuteStatement", """
+ {"Statement":"SELECT * FROM \\\"%s\\\" WHERE pk = 'expired'"}
+ """.formatted(tableName))
+ .statusCode(200).body("Items[0].pk.S", equalTo("expired"));
+ }
+
+ @Test
+ void wholeTableReadsIncludePendingTtlItems() {
+ Set<String> keys = service.liveItems(service.settledTable(tableName, REGION), REGION).stream()
+ .map(item -> item.path("pk").path("S").asText())
+ .collect(Collectors.toSet());
+ assertEquals(Set.of("expired", "future"), keys);
+ }
+
+ private ValidatableResponse getExpired() {
+ return call("GetItem", """
+ {"TableName":"%s","Key":{"pk":{"S":"expired"}},"ConsistentRead":true}
+ """.formatted(tableName));
+ }
+
+ private void putItem(String key, long ttl) {
+ call("PutItem", """
+ {"TableName":"%s","Item":{"pk":{"S":"%s"},"ttl":{"N":"%d"}}}
+ """.formatted(tableName, key, ttl)).statusCode(200);
+ }
+
+ private ValidatableResponse call(String action, String body) {
+ return given().header("X-Amz-Target", "DynamoDB_20120810." + action)
+ .contentType("application/x-amz-json-1.0").body(body)
+ .when().post("/").then();
+ }
+}