feat(dynamodb): emulate Contributor Insights on tables and global secondary indexes (#7326)

This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-02 11:30:29 -04:00
1 parent bbe23ed550
commit bb5e692b87
8 files changed
+707

No files matched your search

+18
View File
@@ -30,6 +30,9 @@
| `ListTagsOfResource` | List tags |
| `DescribeContinuousBackups` | Get the point-in-time recovery status and restore window |
| `UpdateContinuousBackups` | Enable or disable point-in-time recovery |
| `UpdateContributorInsights` | Enable or disable CloudWatch Contributor Insights on a table or global secondary index |
| `DescribeContributorInsights` | Get the Contributor Insights status, mode and rule names of a table or global secondary index |
| `ListContributorInsights` | List the tables and global secondary indexes with Contributor Insights enabled |
| `RestoreTableToPointInTime` | Create a new table from a table as it was at a point in time |
| `CreateBackup` | Take an on-demand backup of a table |
| `DescribeBackup` | Get a backup and the table it was taken from |
@@ -540,6 +543,21 @@ Deleting a table with point-in-time recovery enabled leaves a `SYSTEM` backup na
Deviations from AWS: enabling point-in-time recovery right after `CreateTable` is accepted at once. AWS sometimes refuses it for a few seconds with `ContinuousBackupsUnavailableException`. `EarliestRestorableDateTime` is rounded down to the second, as on AWS. A restore or an export at that time on AWS leaves out the writes made earlier in that second, before point-in-time recovery was enabled. Floci keeps changes only from the moment it is enabled, so it includes those writes.
## Contributor Insights
`UpdateContributorInsights` turns CloudWatch Contributor Insights on or off for a table or one of its global secondary indexes. `ContributorInsightsMode` is `ACCESSED_AND_THROTTLED_KEYS` (the default) or `THROTTLED_KEYS`. The setting is kept with the table, so it is gone when the table or the index is deleted, and a restored table starts without it.
```bash
aws dynamodb update-contributor-insights --table-name Users \
--contributor-insights-action ENABLE --endpoint-url $AWS_ENDPOINT_URL
aws dynamodb describe-contributor-insights --table-name Users --endpoint-url $AWS_ENDPOINT_URL
```
`DescribeContributorInsights` lists the rule names AWS would create, in the form `DynamoDBContributorInsights-<kind>-<resource>-<creation time in ms>`, where the resource is the table name, or `<table>-<index>` for an index. The kinds are `PKC` and `PKT`, plus `SKC` and `SKT` when the table or index has a sort key. `THROTTLED_KEYS` mode has only the throttled-key rules (`PKT`, `SKT`). A table or index that never had Contributor Insights enabled reads `DISABLED`. `ListContributorInsights` returns the enabled tables and indexes, at most 100 per page.
Deviations from AWS: `UpdateContributorInsights` answers `ENABLING` or `DISABLING` as on AWS, but the change applies at once, so the next `DescribeContributorInsights` reads `ENABLED` or `DISABLED`. Floci creates no CloudWatch rules and collects no key statistics, and the status is never `FAILED`.
## Kinesis change data capture (CDC)
When a table has an **ACTIVE** Kinesis streaming destination (see
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.ContributorInsights;
import io.github.hectorvent.floci.services.dynamodb.model.ExportDescription;
import io.github.hectorvent.floci.services.dynamodb.model.ExportSummary;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
@@ -2935,6 +2936,122 @@ public class DynamoDbService {
LOG.infov("Updated TTL for table {0}: enabled={1}, attr={2}", canonicalTableName, enabled, ttlAttributeName);
}
// --- Contributor Insights ---
private static final String DEFAULT_CONTRIBUTOR_INSIGHTS_MODE = "ACCESSED_AND_THROTTLED_KEYS";
private static final int MAX_CONTRIBUTOR_INSIGHTS_PAGE_SIZE = 100;
/**
* A table or global secondary index as the Contributor Insights operations see it. {@code arn}
* orders and pages ListContributorInsights; {@code insights} is null until the first update.
*/
public record ContributorInsightsTarget(String tableName, String indexName, String arn, boolean hasSortKey,
ContributorInsights insights) {
public boolean enabled() {
return insights != null && insights.isEnabled();
}
}
public record ContributorInsightsPage(List<ContributorInsightsTarget> summaries, String nextToken) {}
public ContributorInsightsTarget describeContributorInsights(String tableName, String indexName, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
TableDefinition table = tableStore.get(regionKey(region, canonicalTableName))
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
return contributorInsightsTarget(table, indexName);
}
/**
* Enabling a disabled table or index creates its rules again. Enabling an enabled one keeps its
* rules and switches the mode only when the request names one.
*/
public ContributorInsightsTarget updateContributorInsights(String tableName, String indexName, boolean enable,
String mode, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
ContributorInsightsTarget target = contributorInsightsTarget(table, indexName);
ContributorInsights insights = target.insights();
if (insights == null) {
insights = new ContributorInsights();
if (indexName == null) {
table.setContributorInsights(insights);
} else {
table.findGsi(indexName).orElseThrow().setContributorInsights(insights);
}
}
Instant now = clock.instant();
if (enable && !insights.isEnabled()) {
insights.setRulesCreatedAt(now);
insights.setMode(mode != null ? mode : DEFAULT_CONTRIBUTOR_INSIGHTS_MODE);
} else if (enable && mode != null) {
insights.setMode(mode);
}
insights.setEnabled(enable);
insights.setLastUpdateDateTime(now);
tableStore.put(storageKey, table);
LOG.infov("Updated Contributor Insights for table {0} index {1}: enabled={2}, mode={3}",
canonicalTableName, indexName, enable, insights.getMode());
return new ContributorInsightsTarget(target.tableName(), target.indexName(), target.arn(),
target.hasSortKey(), insights);
}
/** The tables and global secondary indexes with Contributor Insights enabled, in ARN order. */
public ContributorInsightsPage listContributorInsights(String tableName, Integer maxResults, String nextToken,
String region) {
if (maxResults != null && MAX_CONTRIBUTOR_INSIGHTS_PAGE_SIZE < maxResults) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.valueTooLarge(
"maxResults", String.valueOf(maxResults), MAX_CONTRIBUTOR_INSIGHTS_PAGE_SIZE));
}
// A token is the ARN of the last table or index of the previous page.
if (nextToken != null && !AwsArnUtils.isArnFor(nextToken, "dynamodb")) {
throw new AwsException("ValidationException", "The provided next token is invalid", 400);
}
List<TableDefinition> tables;
if (tableName != null) {
String canonicalTableName = canonicalTableName(region, tableName);
tables = List.of(tableStore.get(regionKey(region, canonicalTableName))
.orElseThrow(() -> resourceNotFoundException(canonicalTableName)));
} else {
tables = tableStore.scan(k -> k.startsWith(region + "::"));
}
List<ContributorInsightsTarget> enabled = new ArrayList<>();
for (TableDefinition table : tables) {
enabled.add(contributorInsightsTarget(table, null));
for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {
enabled.add(contributorInsightsTarget(table, gsi.getIndexName()));
}
}
enabled.removeIf(target -> !target.enabled());
enabled.sort(Comparator.comparing(ContributorInsightsTarget::arn));
int start = 0;
if (nextToken != null) {
while (start < enabled.size() && enabled.get(start).arn().compareTo(nextToken) <= 0) {
start++;
}
}
int limit = maxResults != null && maxResults > 0 ? maxResults : MAX_CONTRIBUTOR_INSIGHTS_PAGE_SIZE;
int end = Math.min(start + limit, enabled.size());
List<ContributorInsightsTarget> page = List.copyOf(enabled.subList(start, end));
return new ContributorInsightsPage(page, end < enabled.size() ? page.getLast().arn() : null);
}
/** Contributor Insights covers a table and its global secondary indexes, never a local one. */
private static ContributorInsightsTarget contributorInsightsTarget(TableDefinition table, String indexName) {
if (indexName == null) {
return new ContributorInsightsTarget(table.getTableName(), null, table.getTableArn(),
table.getSortKeyName() != null, table.getContributorInsights());
}
GlobalSecondaryIndex gsi = table.findGsi(indexName)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Requested resource not found: Index: " + indexName + " not found for table: "
+ table.getTableName(), 400));
return new ContributorInsightsTarget(table.getTableName(), indexName, gsi.getIndexArn(),
gsi.getSortKeyName() != null, gsi.getContributorInsights());
}
/** The restore window is null while point-in-time recovery is disabled. */
public record ContinuousBackups(TableDefinition table, DynamoDbPointInTimeRecovery.RestoreWindow window) {}
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.T
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.UpdateTableRequest;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.ContributorInsights;
import io.github.hectorvent.floci.services.dynamodb.model.ExportDescription;
import io.github.hectorvent.floci.services.dynamodb.model.ExportSummary;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
@@ -69,6 +70,9 @@ public class NativeDynamoDbJsonHandler {
private static final int MAX_BACKUP_ARN_LENGTH = 1024;
private static final Instant MAX_TIME_RANGE_BOUND = Instant.ofEpochMilli(99_999_999_999_999L);
private static final int MAX_RECOVERY_PERIOD_DAYS = 35;
private static final List<String> CONTRIBUTOR_INSIGHTS_ACTIONS = List.of("ENABLE", "DISABLE");
// The order AWS prints the enum constraint in.
private static final List<String> CONTRIBUTOR_INSIGHTS_MODES = List.of("THROTTLED_KEYS", "ACCESSED_AND_THROTTLED_KEYS");
// The warm throughput a new on-demand table or index starts with.
private static final long ON_DEMAND_WARM_READ_UNITS = 12000;
private static final long ON_DEMAND_WARM_WRITE_UNITS = 4000;
@@ -115,6 +119,9 @@ public class NativeDynamoDbJsonHandler {
case "UpdateTimeToLive" -> handleUpdateTimeToLive(request, region);
case "DescribeContinuousBackups" -> handleDescribeContinuousBackups(request, region);
case "UpdateContinuousBackups" -> handleUpdateContinuousBackups(request, region);
case "UpdateContributorInsights" -> handleUpdateContributorInsights(request, region);
case "DescribeContributorInsights" -> handleDescribeContributorInsights(request, region);
case "ListContributorInsights" -> handleListContributorInsights(request, region);
case "CreateBackup" -> handleCreateBackup(request, region);
case "DescribeBackup" -> handleDescribeBackup(request, region);
case "ListBackups" -> handleListBackups(request, region);
@@ -2001,6 +2008,136 @@ public class NativeDynamoDbJsonHandler {
return Response.ok(response).build();
}
/** AWS answers ENABLING or DISABLING here; Floci settles at once, so a describe reads ENABLED or DISABLED. */
private Response handleUpdateContributorInsights(JsonNode request, String region) {
String tableName = requireTableNameParameter(request, "TableName");
DynamoDbTableNames.resolveWithRegion(tableName, region);
List<String> violations = new ArrayList<>();
String indexName = contributorInsightsIndexName(request, violations);
JsonNode action = request.path("ContributorInsightsAction");
if (action.isMissingNode() || action.isNull()) {
violations.add(SmithyValidationErrors.notNull("contributorInsightsAction"));
} else if (!CONTRIBUTOR_INSIGHTS_ACTIONS.contains(action.asText())) {
violations.add(SmithyValidationErrors.notInEnum(action.asText(), "contributorInsightsAction",
CONTRIBUTOR_INSIGHTS_ACTIONS));
}
String mode = request.hasNonNull("ContributorInsightsMode")
? request.get("ContributorInsightsMode").asText() : null;
if (mode != null && !CONTRIBUTOR_INSIGHTS_MODES.contains(mode)) {
violations.add(SmithyValidationErrors.notInEnum(mode, "contributorInsightsMode",
CONTRIBUTOR_INSIGHTS_MODES));
}
throwValidationErrors(violations);
boolean enable = "ENABLE".equals(action.asText());
DynamoDbService.ContributorInsightsTarget target =
dynamoDbService.updateContributorInsights(tableName, indexName, enable, mode, region);
ObjectNode response = contributorInsightsNode(target);
response.put("ContributorInsightsStatus", enable ? "ENABLING" : "DISABLING");
if (enable) {
response.put("ContributorInsightsMode", target.insights().getMode());
}
return Response.ok(response).build();
}
private Response handleDescribeContributorInsights(JsonNode request, String region) {
String tableName = requireTableNameParameter(request, "TableName");
DynamoDbTableNames.resolveWithRegion(tableName, region);
List<String> violations = new ArrayList<>();
String indexName = contributorInsightsIndexName(request, violations);
throwValidationErrors(violations);
DynamoDbService.ContributorInsightsTarget target =
dynamoDbService.describeContributorInsights(tableName, indexName, region);
ObjectNode response = contributorInsightsNode(target);
ContributorInsights insights = target.insights();
if (target.enabled()) {
ArrayNode rules = response.putArray("ContributorInsightsRuleList");
contributorInsightsRuleNames(target).forEach(rules::add);
response.put("ContributorInsightsStatus", "ENABLED");
response.put("ContributorInsightsMode", insights.getMode());
} else {
response.put("ContributorInsightsStatus", "DISABLED");
}
if (insights != null) {
response.put("LastUpdateDateTime", epochSeconds(insights.getLastUpdateDateTime()));
}
return Response.ok(response).build();
}
private Response handleListContributorInsights(JsonNode request, String region) {
String tableName = request.hasNonNull("TableName") ? request.get("TableName").asText() : null;
if (tableName != null) {
DynamoDbTableNames.resolveWithRegion(tableName, region);
}
Integer maxResults = request.hasNonNull("MaxResults") ? request.get("MaxResults").asInt() : null;
String nextToken = request.hasNonNull("NextToken") ? request.get("NextToken").asText() : null;
DynamoDbService.ContributorInsightsPage page =
dynamoDbService.listContributorInsights(tableName, maxResults, nextToken, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode summaries = response.putArray("ContributorInsightsSummaries");
for (DynamoDbService.ContributorInsightsTarget target : page.summaries()) {
ObjectNode summary = contributorInsightsNode(target);
summary.put("ContributorInsightsStatus", "ENABLED");
summary.put("ContributorInsightsMode", target.insights().getMode());
summaries.add(summary);
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
private static String contributorInsightsIndexName(JsonNode request, List<String> violations) {
if (!request.hasNonNull("IndexName")) {
return null;
}
String indexName = request.get("IndexName").asText();
violations.addAll(nameViolations(indexName, "indexName"));
return indexName;
}
private ObjectNode contributorInsightsNode(DynamoDbService.ContributorInsightsTarget target) {
ObjectNode node = objectMapper.createObjectNode();
node.put("TableName", target.tableName());
if (target.indexName() != null) {
node.put("IndexName", target.indexName());
}
return node;
}
/**
* The rules AWS creates, named {@code DynamoDBContributorInsights-<kind>-<resource>-<creation millis>}
* where the resource is the table name, or {@code <table>-<index>} for an index: the accessed-key
* rules (PKC, SKC) only in ACCESSED_AND_THROTTLED_KEYS mode, the sort-key rules (SKC, SKT) only
* when the table or index has a sort key.
*/
private static List<String> contributorInsightsRuleNames(DynamoDbService.ContributorInsightsTarget target) {
List<String> kinds = new ArrayList<>();
if ("ACCESSED_AND_THROTTLED_KEYS".equals(target.insights().getMode())) {
kinds.add("PKC");
if (target.hasSortKey()) {
kinds.add("SKC");
}
}
kinds.add("PKT");
if (target.hasSortKey()) {
kinds.add("SKT");
}
String resource = target.indexName() != null
? target.tableName() + "-" + target.indexName() : target.tableName();
String suffix = "-" + resource + "-" + target.insights().getRulesCreatedAt().toEpochMilli();
List<String> names = new ArrayList<>();
for (String kind : kinds) {
names.add("DynamoDBContributorInsights-" + kind + suffix);
}
return names;
}
private Response handleCreateBackup(JsonNode request, String region) {
String tableName = requireTableNameParameter(request, "TableName");
DynamoDbTableNames.resolveWithRegion(tableName, region);
@@ -0,0 +1,36 @@
package io.github.hectorvent.floci.services.dynamodb.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* The CloudWatch Contributor Insights setting of a table or a global secondary index, kept from the
* first UpdateContributorInsights call on it. {@code rulesCreatedAt} stamps the rule names and is
* reset each time the setting goes from disabled to enabled, when AWS creates the rules again.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ContributorInsights {
private boolean enabled;
private String mode;
private Instant lastUpdateDateTime;
private Instant rulesCreatedAt;
public ContributorInsights() {
}
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public String getMode() { return mode; }
public void setMode(String mode) { this.mode = mode; }
public Instant getLastUpdateDateTime() { return lastUpdateDateTime; }
public void setLastUpdateDateTime(Instant lastUpdateDateTime) { this.lastUpdateDateTime = lastUpdateDateTime; }
public Instant getRulesCreatedAt() { return rulesCreatedAt; }
public void setRulesCreatedAt(Instant rulesCreatedAt) { this.rulesCreatedAt = rulesCreatedAt; }
}
@@ -21,6 +21,8 @@ public class GlobalSecondaryIndex {
private List<String> nonKeyAttributes;
private Integer onDemandMaxReadRequestUnits;
private Integer onDemandMaxWriteRequestUnits;
// Null until the first UpdateContributorInsights call on this index.
private ContributorInsights contributorInsights;
public GlobalSecondaryIndex() {
this.provisionedThroughput = new ProvisionedThroughput(0, 0);
@@ -72,6 +74,11 @@ public class GlobalSecondaryIndex {
public Integer getOnDemandMaxWriteRequestUnits() { return onDemandMaxWriteRequestUnits; }
public void setOnDemandMaxWriteRequestUnits(Integer v) { this.onDemandMaxWriteRequestUnits = v; }
public ContributorInsights getContributorInsights() { return contributorInsights; }
public void setContributorInsights(ContributorInsights contributorInsights) {
this.contributorInsights = contributorInsights;
}
@JsonIgnore
public String getPartitionKeyName() {
return keySchema.stream()
@@ -60,6 +60,8 @@ public class TableDefinition {
// concurrency on subsequent Put/DeleteResourcePolicy calls. Null when no policy is attached.
private String resourcePolicy;
private String resourcePolicyRevisionId;
// Null until the first UpdateContributorInsights call on the table itself.
private ContributorInsights contributorInsights;
public TableDefinition() {
this.keySchema = new ArrayList<>();
@@ -246,6 +248,11 @@ public class TableDefinition {
public String getResourcePolicyRevisionId() { return resourcePolicyRevisionId; }
public void setResourcePolicyRevisionId(String resourcePolicyRevisionId) { this.resourcePolicyRevisionId = resourcePolicyRevisionId; }
public ContributorInsights getContributorInsights() { return contributorInsights; }
public void setContributorInsights(ContributorInsights contributorInsights) {
this.contributorInsights = contributorInsights;
}
@JsonIgnore
public String getPartitionKeyName() {
return keySchema.stream()
@@ -0,0 +1,321 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ContributorInsightsAction;
import software.amazon.awssdk.services.dynamodb.model.ContributorInsightsMode;
import software.amazon.awssdk.services.dynamodb.model.ContributorInsightsStatus;
import software.amazon.awssdk.services.dynamodb.model.ContributorInsightsSummary;
import software.amazon.awssdk.services.dynamodb.model.DescribeContributorInsightsResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateContributorInsightsResponse;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static io.github.hectorvent.floci.testing.DynamoDbRequests.ddb;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class DynamoDbContributorInsightsIntegrationTest {
private static final String TABLE_ARN_PREFIX = "arn:aws:dynamodb:us-east-1:000000000000:table/";
@TestHTTPResource
URI endpoint;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void enablingATableCreatesItsRulesAndDisablingRemovesThem() {
String table = "CiIT-table";
createTable(table, true, "");
describe(table, null)
.statusCode(200)
.body("keySet()", containsInAnyOrder("TableName", "ContributorInsightsStatus"))
.body("TableName", equalTo(table))
.body("ContributorInsightsStatus", equalTo("DISABLED"));
long before = System.currentTimeMillis();
update(table, null, "ENABLE", null)
.statusCode(200)
.body("keySet()", containsInAnyOrder("TableName", "ContributorInsightsStatus", "ContributorInsightsMode"))
.body("TableName", equalTo(table))
.body("ContributorInsightsStatus", equalTo("ENABLING"))
.body("ContributorInsightsMode", equalTo("ACCESSED_AND_THROTTLED_KEYS"));
long after = System.currentTimeMillis();
ValidatableResponse enabled = describe(table, null)
.statusCode(200)
.body("ContributorInsightsStatus", equalTo("ENABLED"))
.body("ContributorInsightsMode", equalTo("ACCESSED_AND_THROTTLED_KEYS"))
.body("LastUpdateDateTime", notNullValue())
.body("IndexName", nullValue());
List<String> rules = enabled.extract().jsonPath().getList("ContributorInsightsRuleList");
assertEquals(4, rules.size(), rules.toString());
long created = ruleTimestamp(rules.getFirst());
assertTrue(before <= created && created <= after, created + " not in [" + before + ", " + after + "]");
assertEquals(List.of(
"DynamoDBContributorInsights-PKC-" + table + "-" + created,
"DynamoDBContributorInsights-SKC-" + table + "-" + created,
"DynamoDBContributorInsights-PKT-" + table + "-" + created,
"DynamoDBContributorInsights-SKT-" + table + "-" + created), rules);
update(table, null, "DISABLE", null)
.statusCode(200)
.body("ContributorInsightsStatus", equalTo("DISABLING"))
.body("ContributorInsightsMode", nullValue());
describe(table, null)
.statusCode(200)
.body("keySet()", containsInAnyOrder("TableName", "ContributorInsightsStatus", "LastUpdateDateTime"))
.body("ContributorInsightsStatus", equalTo("DISABLED"));
}
@Test
void switchingTheModeKeepsTheRulesAndReEnablingCreatesThemAgain() {
String table = "CiIT-mode";
createTable(table, true, "");
update(table, null, "ENABLE", null).statusCode(200);
long created = ruleTimestamp(rulesOf(table, null).getFirst());
update(table, null, "ENABLE", "THROTTLED_KEYS")
.statusCode(200)
.body("ContributorInsightsMode", equalTo("THROTTLED_KEYS"));
assertEquals(List.of(
"DynamoDBContributorInsights-PKT-" + table + "-" + created,
"DynamoDBContributorInsights-SKT-" + table + "-" + created), rulesOf(table, null));
update(table, null, "ENABLE", null)
.statusCode(200)
.body("ContributorInsightsMode", equalTo("THROTTLED_KEYS"));
update(table, null, "DISABLE", null).statusCode(200);
update(table, null, "ENABLE", null)
.statusCode(200)
.body("ContributorInsightsMode", equalTo("ACCESSED_AND_THROTTLED_KEYS"));
List<String> recreated = rulesOf(table, null);
assertEquals(4, recreated.size(), recreated.toString());
assertTrue(ruleTimestamp(recreated.getFirst()) > created, recreated.toString());
}
@Test
void aGlobalSecondaryIndexHasItsOwnSetting() {
String table = "CiIT-index";
createTable(table, false, """
, "GlobalSecondaryIndexes": [{"IndexName": "byOwner",
"KeySchema": [{"AttributeName": "owner", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"}}]
""");
update(table, "byOwner", "ENABLE", "ACCESSED_AND_THROTTLED_KEYS")
.statusCode(200)
.body("TableName", equalTo(table))
.body("IndexName", equalTo("byOwner"))
.body("ContributorInsightsStatus", equalTo("ENABLING"));
List<String> rules = rulesOf(table, "byOwner");
long created = ruleTimestamp(rules.getFirst());
assertEquals(List.of(
"DynamoDBContributorInsights-PKC-" + table + "-byOwner-" + created,
"DynamoDBContributorInsights-PKT-" + table + "-byOwner-" + created), rules);
describe(table, "byOwner").statusCode(200).body("IndexName", equalTo("byOwner"));
describe(table, null).statusCode(200).body("ContributorInsightsStatus", equalTo("DISABLED"));
ddb("ListContributorInsights", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("ContributorInsightsSummaries", hasSize(1))
.body("ContributorInsightsSummaries[0].TableName", equalTo(table))
.body("ContributorInsightsSummaries[0].IndexName", equalTo("byOwner"))
.body("ContributorInsightsSummaries[0].ContributorInsightsStatus", equalTo("ENABLED"))
.body("ContributorInsightsSummaries[0].ContributorInsightsMode", equalTo("ACCESSED_AND_THROTTLED_KEYS"))
.body("NextToken", nullValue());
ddb("UpdateTable", """
{"TableName": "%s", "GlobalSecondaryIndexUpdates": [{"Delete": {"IndexName": "byOwner"}}]}
""".formatted(table)).statusCode(200);
expectError(describe(table, "byOwner"), "ResourceNotFoundException",
"Requested resource not found: Index: byOwner not found for table: " + table);
}
@Test
void deletingTheTableDropsTheSetting() {
String table = "CiIT-recreate";
createTable(table, false, "");
update(table, null, "ENABLE", null).statusCode(200);
ddb("DeleteTable", "{\"TableName\": \"" + table + "\"}").statusCode(200);
createTable(table, false, "");
describe(table, null)
.statusCode(200)
.body("keySet()", containsInAnyOrder("TableName", "ContributorInsightsStatus"))
.body("ContributorInsightsStatus", equalTo("DISABLED"));
}
@Test
void tableArnNamesTheTable() {
String table = "CiIT-arn";
createTable(table, false, "");
update(TABLE_ARN_PREFIX + table, null, "ENABLE", null)
.statusCode(200)
.body("TableName", equalTo(table));
describe(TABLE_ARN_PREFIX + table, null)
.statusCode(200)
.body("TableName", equalTo(table))
.body("ContributorInsightsStatus", equalTo("ENABLED"));
}
@Test
void listPagesTheEnabledTablesAndIndexesInArnOrder() {
List<String> enabled = List.of("CiIT-list-a", "CiIT-list-b", "CiIT-list-c");
for (String table : enabled) {
createTable(table, false, "");
update(table, null, "ENABLE", null).statusCode(200);
}
createTable("CiIT-list-off", false, "");
update("CiIT-list-off", null, "ENABLE", null).statusCode(200);
update("CiIT-list-off", null, "DISABLE", null).statusCode(200);
List<String> listed = new ArrayList<>();
String nextToken = null;
do {
String body = nextToken == null
? "{\"MaxResults\": 2}"
: "{\"MaxResults\": 2, \"NextToken\": \"" + nextToken + "\"}";
ValidatableResponse page = ddb("ListContributorInsights", body)
.statusCode(200)
.body("ContributorInsightsSummaries.size()", lessThanOrEqualTo(2))
.body("ContributorInsightsSummaries.ContributorInsightsStatus", everyItem(equalTo("ENABLED")));
listed.addAll(page.extract().jsonPath().getList("ContributorInsightsSummaries.TableName"));
nextToken = page.extract().jsonPath().getString("NextToken");
} while (nextToken != null);
List<String> ours = listed.stream().filter(name -> name.startsWith("CiIT-list-")).toList();
assertEquals(enabled, ours);
assertEquals(listed.size(), listed.stream().distinct().count(), listed.toString());
}
@Test
void requestsAreValidatedAsTheApiReferenceDescribes() {
String table = "CiIT-errors";
createTable(table, true, """
, "LocalSecondaryIndexes": [{"IndexName": "byOwnerLocal",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "owner", "KeyType": "RANGE"}],
"Projection": {"ProjectionType": "ALL"}}]
""");
expectError(ddb("UpdateContributorInsights", "{\"ContributorInsightsAction\": \"ENABLE\"}"),
"ValidationException", "The parameter 'TableName' is required but was not present in the request");
expectError(ddb("UpdateContributorInsights", "{\"TableName\": \"" + table + "\"}"), "ValidationException",
"1 validation error detected: Value null at 'contributorInsightsAction' failed to satisfy "
+ "constraint: Member must not be null");
expectError(update(table, null, "PAUSE", "ALL_KEYS"), "ValidationException",
"2 validation errors detected: Value 'PAUSE' at 'contributorInsightsAction' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [ENABLE, DISABLE]; Value 'ALL_KEYS' at "
+ "'contributorInsightsMode' failed to satisfy constraint: Member must satisfy enum value set: "
+ "[THROTTLED_KEYS, ACCESSED_AND_THROTTLED_KEYS]");
expectError(update(table, "ab", "ENABLE", null), "ValidationException",
"1 validation error detected: Value 'ab' at 'indexName' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 3");
expectError(update("CiIT-missing", null, "ENABLE", null), "ResourceNotFoundException",
"Requested resource not found: Table: CiIT-missing not found");
expectError(update(table, "nope", "ENABLE", null), "ResourceNotFoundException",
"Requested resource not found: Index: nope not found for table: " + table);
expectError(describe(table, "byOwnerLocal"), "ResourceNotFoundException",
"Requested resource not found: Index: byOwnerLocal not found for table: " + table);
expectError(ddb("DescribeContributorInsights", "{}"), "ValidationException",
"The parameter 'TableName' is required but was not present in the request");
expectError(describe("CiIT-missing", null), "ResourceNotFoundException",
"Requested resource not found: Table: CiIT-missing not found");
expectError(ddb("ListContributorInsights", "{\"TableName\": \"CiIT-missing\"}"),
"ResourceNotFoundException", "Requested resource not found: Table: CiIT-missing not found");
expectError(ddb("ListContributorInsights", "{\"MaxResults\": 101}"), "ValidationException",
"1 validation error detected: Value '101' at 'maxResults' failed to satisfy constraint: "
+ "Member must have value less than or equal to 100");
expectError(ddb("ListContributorInsights", "{\"NextToken\": \"garbage\"}"), "ValidationException",
"The provided next token is invalid");
}
@Test
void awsSdkReadsEveryResponse() {
String table = "CiIT-sdk";
createTable(table, true, "");
try (DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build()) {
UpdateContributorInsightsResponse updated = client.updateContributorInsights(b -> b.tableName(table)
.contributorInsightsAction(ContributorInsightsAction.ENABLE)
.contributorInsightsMode(ContributorInsightsMode.THROTTLED_KEYS));
assertEquals(ContributorInsightsStatus.ENABLING, updated.contributorInsightsStatus());
assertEquals(ContributorInsightsMode.THROTTLED_KEYS, updated.contributorInsightsMode());
DescribeContributorInsightsResponse described = client.describeContributorInsights(b -> b.tableName(table));
assertEquals(ContributorInsightsStatus.ENABLED, described.contributorInsightsStatus());
assertEquals(ContributorInsightsMode.THROTTLED_KEYS, described.contributorInsightsMode());
assertEquals(2, described.contributorInsightsRuleList().size());
assertNotNull(described.lastUpdateDateTime());
List<ContributorInsightsSummary> summaries =
client.listContributorInsights(b -> b.tableName(table)).contributorInsightsSummaries();
assertEquals(1, summaries.size());
assertEquals(table, summaries.getFirst().tableName());
assertEquals(ContributorInsightsStatus.ENABLED, summaries.getFirst().contributorInsightsStatus());
}
}
private static ValidatableResponse update(String table, String index, String action, String mode) {
StringBuilder body = new StringBuilder("{\"TableName\": \"").append(table).append('"');
if (index != null) {
body.append(", \"IndexName\": \"").append(index).append('"');
}
body.append(", \"ContributorInsightsAction\": \"").append(action).append('"');
if (mode != null) {
body.append(", \"ContributorInsightsMode\": \"").append(mode).append('"');
}
return ddb("UpdateContributorInsights", body.append('}').toString());
}
private static ValidatableResponse describe(String table, String index) {
String indexMember = index != null ? ", \"IndexName\": \"" + index + "\"" : "";
return ddb("DescribeContributorInsights", "{\"TableName\": \"" + table + "\"" + indexMember + "}");
}
private static List<String> rulesOf(String table, String index) {
return describe(table, index)
.statusCode(200)
.body("ContributorInsightsStatus", equalTo("ENABLED"))
.extract().jsonPath().getList("ContributorInsightsRuleList");
}
private static long ruleTimestamp(String rule) {
return Long.parseLong(rule.substring(rule.lastIndexOf('-') + 1));
}
/** {@code indexes} is appended to the CreateTable body; an index there keys on {@code owner}. */
private static void createTable(String table, boolean withSortKey, String indexes) {
String sortKey = withSortKey ? ", {\"AttributeName\": \"sk\", \"KeyType\": \"RANGE\"}" : "";
String attributes = (withSortKey ? ", {\"AttributeName\": \"sk\", \"AttributeType\": \"S\"}" : "")
+ (indexes.isEmpty() ? "" : ", {\"AttributeName\": \"owner\", \"AttributeType\": \"S\"}");
ddb("CreateTable", """
{"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}%s],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}%s],
"BillingMode": "PAY_PER_REQUEST"%s}
""".formatted(table, sortKey, attributes, indexes)).statusCode(200);
}
private static void expectError(ValidatableResponse response, String type, String message) {
response.statusCode(400)
.body("__type", containsString(type))
.body("message", equalTo(message));
}
}
@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.services.dynamodb.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The Contributor Insights setting of a table and of its indexes survives the persistent storage modes. */
class ContributorInsightsJacksonRoundTripTest {
/** Same configuration {@code PersistentStorage}, {@code HybridStorage} and {@code WalStorage} use. */
private final ObjectMapper mapper = new ObjectMapper();
ContributorInsightsJacksonRoundTripTest() {
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Test
void tableAndIndexSettingsSurviveARoundTrip() throws Exception {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setKeySchema(List.of(new KeySchemaElement("pk", "HASH")));
table.setContributorInsights(insights(true, "THROTTLED_KEYS", Instant.parse("2026-11-02T10:15:30.123Z")));
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex("byOwner",
List.of(new KeySchemaElement("owner", "HASH")), null, "ALL", null);
gsi.setContributorInsights(insights(false, "ACCESSED_AND_THROTTLED_KEYS",
Instant.parse("2026-11-02T11:00:00Z")));
table.getGlobalSecondaryIndexes().add(gsi);
TableDefinition reloaded = mapper.readValue(mapper.writeValueAsString(table), TableDefinition.class);
ContributorInsights tableInsights = reloaded.getContributorInsights();
assertTrue(tableInsights.isEnabled());
assertEquals("THROTTLED_KEYS", tableInsights.getMode());
assertEquals(Instant.parse("2026-11-02T10:15:30.123Z"), tableInsights.getRulesCreatedAt());
assertEquals(Instant.parse("2026-11-02T10:15:30.123Z"), tableInsights.getLastUpdateDateTime());
ContributorInsights indexInsights = reloaded.findGsi("byOwner").orElseThrow().getContributorInsights();
assertEquals(false, indexInsights.isEnabled());
assertEquals("ACCESSED_AND_THROTTLED_KEYS", indexInsights.getMode());
}
@Test
void aTableStoredBeforeContributorInsightsReadsWithoutIt() throws Exception {
TableDefinition reloaded = mapper.readValue("{\"tableName\":\"legacy\"}", TableDefinition.class);
assertNull(reloaded.getContributorInsights());
}
private static ContributorInsights insights(boolean enabled, String mode, Instant at) {
ContributorInsights insights = new ContributorInsights();
insights.setEnabled(enabled);
insights.setMode(mode);
insights.setLastUpdateDateTime(at);
insights.setRulesCreatedAt(at);
return insights;
}
}