violations = new ArrayList<>();
+ if (indexName.asText().length() < 3) {
+ violations.add(value + "Member must have length greater than or equal to 3");
+ }
+ if (255 < indexName.asText().length()) {
+ violations.add(value + "Member must have length less than or equal to 255");
+ }
+ if (!INDEX_NAME_CHARS.matcher(indexName.asText()).matches()) {
+ violations.add(value + "Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+");
+ }
+ return violations;
+ }
+
+ private static String textOrNull(JsonNode node, String member) {
+ return node.hasNonNull(member) ? node.get(member).asText() : null;
+ }
+
+ private static Instant timestampOrNull(JsonNode request, String member) {
+ JsonNode node = request.path(member);
+ return node.isNumber() ? Instant.ofEpochMilli(node.decimalValue().movePointRight(3).longValue()) : null;
+ }
+
+ private static BigDecimal epochSeconds(Instant instant) {
+ return BigDecimal.valueOf(instant.toEpochMilli(), 3);
+ }
+
+ private ObjectNode backupDetailsNode(TableBackup backup, String status) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("BackupArn", backup.getBackupArn());
+ node.put("BackupName", backup.getBackupName());
+ node.put("BackupSizeBytes", backup.getSizeBytes());
+ node.put("BackupStatus", status);
+ node.put("BackupType", backup.getBackupType());
+ node.put("BackupCreationDateTime", epochSeconds(backup.getCreationDateTime()));
+ if (backup.getExpiryDateTime() != null) {
+ node.put("BackupExpiryDateTime", epochSeconds(backup.getExpiryDateTime()));
+ }
+ return node;
+ }
+
+ private ObjectNode backupSummaryNode(TableBackup backup) {
+ ObjectNode node = backupDetailsNode(backup, "AVAILABLE");
+ TableDefinition table = backup.getTable();
+ node.put("TableName", table.getTableName());
+ node.put("TableId", table.getTableId());
+ node.put("TableArn", table.getTableArn());
+ return node;
+ }
+
+ /** The source table parts are DescribeTable's, minus the members that only describe a live table. */
+ private ObjectNode backupDescriptionNode(TableBackup backup, String status) {
+ TableDefinition table = backup.getTable();
+ ObjectNode described = tableToNode(table);
+
+ ObjectNode source = objectMapper.createObjectNode();
+ source.put("TableName", table.getTableName());
+ source.put("TableId", table.getTableId());
+ source.put("TableArn", table.getTableArn());
+ source.put("TableSizeBytes", table.getTableSizeBytes());
+ source.set("KeySchema", described.get("KeySchema"));
+ source.set("TableCreationDateTime", described.get("CreationDateTime"));
+ ObjectNode throughput = (ObjectNode) described.get("ProvisionedThroughput");
+ throughput.remove("NumberOfDecreasesToday");
+ source.set("ProvisionedThroughput", throughput);
+ if (described.has("OnDemandThroughput")) {
+ source.set("OnDemandThroughput", described.get("OnDemandThroughput"));
+ }
+ source.put("ItemCount", table.getItemCount());
+ source.put("BillingMode", "PAY_PER_REQUEST".equals(table.getBillingMode()) ? "PAY_PER_REQUEST" : "PROVISIONED");
+
+ ObjectNode features = objectMapper.createObjectNode();
+ if (described.has("LocalSecondaryIndexes")) {
+ for (JsonNode lsi : described.get("LocalSecondaryIndexes")) {
+ ((ObjectNode) lsi).remove(List.of("IndexArn", "IndexSizeBytes", "ItemCount"));
+ }
+ features.set("LocalSecondaryIndexes", described.get("LocalSecondaryIndexes"));
+ }
+ if (described.has("GlobalSecondaryIndexes")) {
+ for (JsonNode gsi : described.get("GlobalSecondaryIndexes")) {
+ ((ObjectNode) gsi).remove(List.of("IndexArn", "IndexStatus", "IndexSizeBytes", "ItemCount"));
+ ((ObjectNode) gsi.get("ProvisionedThroughput")).remove("NumberOfDecreasesToday");
+ }
+ features.set("GlobalSecondaryIndexes", described.get("GlobalSecondaryIndexes"));
+ }
+ if (table.isStreamEnabled()) {
+ ObjectNode stream = features.putObject("StreamDescription");
+ stream.put("StreamEnabled", true);
+ stream.put("StreamViewType", table.getStreamViewType());
+ }
+ if (table.isTtlEnabled()) {
+ ObjectNode ttl = features.putObject("TimeToLiveDescription");
+ ttl.put("AttributeName", table.getTtlAttributeName());
+ ttl.put("TimeToLiveStatus", "ENABLED");
+ }
+ if (described.has("SSEDescription")) {
+ features.set("SSEDescription", described.get("SSEDescription"));
+ }
+ if (described.has("VectorIndexes")) {
+ for (JsonNode vectorIndex : described.get("VectorIndexes")) {
+ ((ObjectNode) vectorIndex).remove(
+ List.of("IndexArn", "IndexStatus", "Backfilling", "IndexSizeBytes", "ItemCount"));
+ }
+ features.set("VectorIndexes", described.get("VectorIndexes"));
+ }
+
+ ObjectNode node = objectMapper.createObjectNode();
+ node.set("BackupDetails", backupDetailsNode(backup, status));
+ node.set("SourceTableDetails", source);
+ node.set("SourceTableFeatureDetails", features);
+ return node;
+ }
+
+ private ObjectNode restoreSummaryNode(String sourceBackupArn, String sourceTableArn, Instant restoreDateTime) {
+ ObjectNode node = objectMapper.createObjectNode();
+ if (sourceBackupArn != null) {
+ node.put("SourceBackupArn", sourceBackupArn);
+ }
+ node.put("SourceTableArn", sourceTableArn);
+ node.put("RestoreDateTime", epochSeconds(restoreDateTime));
+ node.put("RestoreInProgress", true);
+ return node;
+ }
+
private Response handleTransactWriteItems(JsonNode request, String region) {
JsonNode transactItemsNode = requireValidTransactRequest(request);
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java
index fb287ece19..a9ab0402ab 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java
@@ -10,18 +10,21 @@ import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestin
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
+import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
- * Table control operations on the native DynamoDB engine: CreateTable, UpdateTable and the Kinesis
- * streaming destination toggles.
+ * Table control operations on the native DynamoDB engine: CreateTable, UpdateTable, the table a
+ * restore creates and the Kinesis streaming destination toggles.
*
* Owns the sequence each operation runs against the backend: the validation that must fail
* before any side effect, the underlying create or update, the settings applied to the stored
@@ -74,6 +77,18 @@ public class NativeDynamoDbTableService {
record KinesisDestination(String tableName, String streamArn, String destinationStatus,
String approximateCreationDateTimePrecision) {}
+ /** One GlobalSecondaryIndexOverride or LocalSecondaryIndexOverride entry; LSIs carry no throughput. */
+ record IndexOverride(String indexName, List keySchema, String projectionType,
+ List nonKeyAttributes, Throughput provisionedThroughput,
+ OnDemandThroughput onDemandThroughput) {}
+
+ /** The overrides of a restore request. A null member or list means the request did not override it. */
+ record RestoreOverrides(String billingMode, Throughput provisionedThroughput,
+ OnDemandThroughput onDemandThroughput,
+ List globalSecondaryIndexes, List localSecondaryIndexes,
+ List vectorIndexes,
+ Boolean sseEnabled, String sseType, String kmsMasterKeyId) {}
+
private final DynamoDbService dynamoDbService;
private final DynamoDbStreamService streamService;
private final KinesisService kinesisService;
@@ -165,6 +180,225 @@ public class NativeDynamoDbTableService {
return table;
}
+ /**
+ * Creates the target of a restore in CREATING from {@code source}, a copy of the table the
+ * backup holds, with the request's overrides applied. Like AWS, the new table gets the keys,
+ * indexes, capacity and encryption, and none of the stream, TTL, point-in-time recovery, tags,
+ * deletion protection or table class.
+ */
+ TableDefinition restoreTable(TableDefinition source, String targetTableName, RestoreOverrides overrides,
+ String region) {
+ String billingMode = overrides.billingMode() != null
+ ? overrides.billingMode()
+ : "PAY_PER_REQUEST".equals(source.getBillingMode()) ? "PAY_PER_REQUEST" : "PROVISIONED";
+ boolean provisioned = "PROVISIONED".equals(billingMode);
+ checkThroughputOverrides(overrides.billingMode(), provisioned, overrides.provisionedThroughput(),
+ overrides.onDemandThroughput(), "");
+ Throughput throughput = null;
+ if (provisioned) {
+ throughput = overrides.provisionedThroughput() != null
+ ? overrides.provisionedThroughput()
+ : new Throughput(source.getProvisionedThroughput().getReadCapacityUnits(),
+ source.getProvisionedThroughput().getWriteCapacityUnits());
+ }
+
+ List gsis = restoredGlobalSecondaryIndexes(source, overrides, provisioned);
+ List lsis = restoredLocalSecondaryIndexes(source, overrides);
+ List vectorIndexes = restoredVectorIndexes(source, overrides);
+
+ Set usedAttributes = new HashSet<>();
+ source.getKeySchema().forEach(k -> usedAttributes.add(k.getAttributeName()));
+ gsis.forEach(g -> g.getKeySchema().forEach(k -> usedAttributes.add(k.getAttributeName())));
+ lsis.forEach(l -> l.getKeySchema().forEach(k -> usedAttributes.add(k.getAttributeName())));
+ vectorIndexes.forEach(v -> usedAttributes.addAll(v.index().getSearchSchemaAttributeNames()));
+ List attributeDefinitions = source.getAttributeDefinitions().stream()
+ .filter(a -> usedAttributes.contains(a.getAttributeName()))
+ .toList();
+
+ Boolean sseEnabled = overrides.sseEnabled() != null ? overrides.sseEnabled() : source.isSseEnabled();
+ String sseType = overrides.sseEnabled() != null ? overrides.sseType() : source.getSseType();
+ String kmsMasterKeyId = overrides.sseEnabled() != null ? overrides.kmsMasterKeyId() : source.getKmsMasterKeyArn();
+ OnDemandThroughput onDemand = provisioned ? null : mergedOnDemand(overrides.onDemandThroughput(),
+ source.getOnDemandMaxReadRequestUnits(), source.getOnDemandMaxWriteRequestUnits());
+ TableSettings settings = new TableSettings(billingMode, false, null, onDemand, null, null,
+ sseEnabled, sseType, kmsMasterKeyId);
+ dynamoDbService.requireRestoreTarget(targetTableName, region);
+ return createTable(new CreateTableRequest(targetTableName, new ArrayList<>(source.getKeySchema()),
+ new ArrayList<>(attributeDefinitions), throughput, gsis, lsis, vectorIndexes, Map.of(), settings),
+ "CREATING", region);
+ }
+
+ private static List restoredGlobalSecondaryIndexes(TableDefinition source,
+ RestoreOverrides overrides, boolean provisioned) {
+ List restored = new ArrayList<>();
+ if (overrides.globalSecondaryIndexes() == null) {
+ for (GlobalSecondaryIndex gsi : source.getGlobalSecondaryIndexes()) {
+ if ("PROVISIONED".equals(overrides.billingMode())) {
+ throw invalidRestore("Must override ProvisionedThroughput if BillingMode is overridden to "
+ + "PROVISIONED for index " + gsi.getIndexName());
+ }
+ restored.add(restoredGsi(gsi.getIndexName(), gsi, provisioned, null, null));
+ }
+ return restored;
+ }
+ for (IndexOverride override : overrides.globalSecondaryIndexes()) {
+ GlobalSecondaryIndex match = source.getGlobalSecondaryIndexes().stream()
+ .filter(gsi -> sameIndex(override, gsi.getKeySchema(), gsi.getProjectionType(),
+ gsi.getNonKeyAttributes()))
+ .findFirst()
+ .orElseThrow(() -> indexMismatch(override.indexName()));
+ String forIndex = " for index " + override.indexName();
+ checkThroughputOverrides(overrides.billingMode(), provisioned, override.provisionedThroughput(),
+ override.onDemandThroughput(), forIndex);
+ if (provisioned && override.provisionedThroughput() == null) {
+ throw invalidRestore("Must specify provisioned throughput" + forIndex);
+ }
+ restored.add(restoredGsi(override.indexName(), match, provisioned, override.provisionedThroughput(),
+ override.onDemandThroughput()));
+ }
+ return restored;
+ }
+
+ /**
+ * The table and each index override go through the same checks in this order. An empty
+ * OnDemandThroughput is ignored, and the message names the first member the override sets.
+ */
+ private static void checkThroughputOverrides(String billingModeOverride, boolean provisioned,
+ Throughput throughput, OnDemandThroughput onDemand, String suffix) {
+ if ("PAY_PER_REQUEST".equals(billingModeOverride) && throughput != null) {
+ throw invalidRestore("Cannot override ProvisionedThroughput if BillingMode is overridden to "
+ + "PAY_PER_REQUEST" + suffix);
+ }
+ if ("PROVISIONED".equals(billingModeOverride) && throughput == null) {
+ throw invalidRestore("Must override ProvisionedThroughput if BillingMode is overridden to PROVISIONED"
+ + suffix);
+ }
+ if (onDemand != null && (onDemand.maxReadRequestUnits() != null || onDemand.maxWriteRequestUnits() != null)) {
+ String cannot = "Cannot override "
+ + (onDemand.maxReadRequestUnits() != null ? "MaxReadRequestUnits" : "MaxWriteRequestUnits")
+ + " for OnDemandThroughput ";
+ if ("PROVISIONED".equals(billingModeOverride)) {
+ throw invalidRestore(cannot + "when BillingMode is PROVISIONED" + suffix);
+ }
+ if (throughput != null) {
+ throw invalidRestore(cannot + "when ProvisionedThroughputOverride is present" + suffix);
+ }
+ if (provisioned) {
+ throw invalidRestore(cannot + "unless BillingModeOverride is PAY_PER_REQUEST" + suffix);
+ }
+ }
+ if (!provisioned && throughput != null) {
+ throw invalidRestore("Cannot override ProvisionedThroughput unless BillingMode is PROVISIONED" + suffix);
+ }
+ }
+
+ /** An on-demand override replaces only the members it sets. */
+ private static OnDemandThroughput mergedOnDemand(OnDemandThroughput override, Integer maxReadRequestUnits,
+ Integer maxWriteRequestUnits) {
+ Integer maxRead = override != null && override.maxReadRequestUnits() != null
+ ? override.maxReadRequestUnits() : maxReadRequestUnits;
+ Integer maxWrite = override != null && override.maxWriteRequestUnits() != null
+ ? override.maxWriteRequestUnits() : maxWriteRequestUnits;
+ return maxRead == null && maxWrite == null ? null : new OnDemandThroughput(maxRead, maxWrite);
+ }
+
+ private static GlobalSecondaryIndex restoredGsi(String indexName, GlobalSecondaryIndex source, boolean provisioned,
+ Throughput throughput, OnDemandThroughput onDemandOverride) {
+ GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(indexName, new ArrayList<>(source.getKeySchema()), null,
+ source.getProjectionType(), new ArrayList<>(source.getNonKeyAttributes()));
+ if (provisioned) {
+ gsi.getProvisionedThroughput().setReadCapacityUnits(throughput != null ? throughput.readCapacityUnits()
+ : source.getProvisionedThroughput().getReadCapacityUnits());
+ gsi.getProvisionedThroughput().setWriteCapacityUnits(throughput != null ? throughput.writeCapacityUnits()
+ : source.getProvisionedThroughput().getWriteCapacityUnits());
+ return gsi;
+ }
+ OnDemandThroughput onDemand = mergedOnDemand(onDemandOverride, source.getOnDemandMaxReadRequestUnits(),
+ source.getOnDemandMaxWriteRequestUnits());
+ if (onDemand != null) {
+ gsi.setOnDemandMaxReadRequestUnits(onDemand.maxReadRequestUnits());
+ gsi.setOnDemandMaxWriteRequestUnits(onDemand.maxWriteRequestUnits());
+ }
+ return gsi;
+ }
+
+ private static List restoredLocalSecondaryIndexes(TableDefinition source,
+ RestoreOverrides overrides) {
+ List restored = new ArrayList<>();
+ if (overrides.localSecondaryIndexes() == null) {
+ for (LocalSecondaryIndex lsi : source.getLocalSecondaryIndexes()) {
+ restored.add(new LocalSecondaryIndex(lsi.getIndexName(), new ArrayList<>(lsi.getKeySchema()), null,
+ lsi.getProjectionType(), new ArrayList<>(lsi.getNonKeyAttributes())));
+ }
+ return restored;
+ }
+ for (IndexOverride override : overrides.localSecondaryIndexes()) {
+ LocalSecondaryIndex match = source.getLocalSecondaryIndexes().stream()
+ .filter(lsi -> sameIndex(override, lsi.getKeySchema(), lsi.getProjectionType(),
+ lsi.getNonKeyAttributes()))
+ .findFirst()
+ .orElseThrow(() -> indexMismatch(override.indexName()));
+ restored.add(new LocalSecondaryIndex(override.indexName(), new ArrayList<>(match.getKeySchema()), null,
+ match.getProjectionType(), new ArrayList<>(match.getNonKeyAttributes())));
+ }
+ return restored;
+ }
+
+ /** Vector indexes, unlike the others, are matched by name. */
+ private static List restoredVectorIndexes(TableDefinition source,
+ RestoreOverrides overrides) {
+ List kept = new ArrayList<>();
+ if (overrides.vectorIndexes() == null) {
+ kept.addAll(source.getVectorIndexes());
+ } else {
+ for (VectorIndex override : overrides.vectorIndexes()) {
+ kept.add(source.getVectorIndexes().stream()
+ .filter(v -> v.getIndexName().equals(override.getIndexName()))
+ .findFirst()
+ .orElseThrow(() -> invalidRestore("Vector index " + override.getIndexName()
+ + " does not match a vector index that existed in the source table and cannot be "
+ + "created during the restore operation")));
+ }
+ }
+ List restored = new ArrayList<>();
+ for (int i = 0; i < kept.size(); i++) {
+ VectorIndex v = kept.get(i);
+ VectorIndex copy = new VectorIndex(v.getIndexName(), v.getVectorAttributeName(),
+ new ArrayList<>(v.getSearchSchema()), v.getProjectionType(),
+ new ArrayList<>(v.getNonKeyAttributes()), v.getDimensions(), v.getDistanceFunction());
+ restored.add(new DynamoDbService.VectorIndexCreate(copy, "vectorIndexOverride." + (i + 1) + ".member"));
+ }
+ return restored;
+ }
+
+ private static boolean sameIndex(IndexOverride override, List keySchema, String projectionType,
+ List nonKeyAttributes) {
+ if (override.keySchema().size() != keySchema.size()) {
+ return false;
+ }
+ for (int i = 0; i < keySchema.size(); i++) {
+ KeySchemaElement want = override.keySchema().get(i);
+ KeySchemaElement have = keySchema.get(i);
+ if (!want.getAttributeName().equals(have.getAttributeName()) || !want.getKeyType().equals(have.getKeyType())) {
+ return false;
+ }
+ }
+ String type = projectionType != null ? projectionType : "ALL";
+ if (!type.equals(override.projectionType())) {
+ return false;
+ }
+ return !"INCLUDE".equals(type) || Set.copyOf(nonKeyAttributes).equals(Set.copyOf(override.nonKeyAttributes()));
+ }
+
+ private static AwsException indexMismatch(String indexName) {
+ return invalidRestore("Index " + indexName + " does not match a secondary index that existed in the source "
+ + "table and cannot be created during the restore operation");
+ }
+
+ private static AwsException invalidRestore(String message) {
+ return new AwsException("ValidationException", "Invalid Request: " + message, 400);
+ }
+
/**
* Updates the table, applies the request's settings and replica changes to it and persists
* the result.
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableBackup.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableBackup.java
new file mode 100644
index 0000000000..6ed037daf7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableBackup.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.dynamodb.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * An on-demand backup: its details, the source table as it was when the backup was taken, and
+ * the items it holds.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TableBackup {
+
+ private String backupArn;
+ private String backupName;
+ private String backupType;
+ private Instant creationDateTime;
+ private Instant expiryDateTime;
+ private long sizeBytes;
+ private String region;
+ private TableDefinition table;
+ private List items;
+
+ public TableBackup() {
+ this.items = new ArrayList<>();
+ }
+
+ public String getBackupArn() { return backupArn; }
+ public void setBackupArn(String backupArn) { this.backupArn = backupArn; }
+
+ public String getBackupName() { return backupName; }
+ public void setBackupName(String backupName) { this.backupName = backupName; }
+
+ public String getBackupType() { return backupType; }
+ public void setBackupType(String backupType) { this.backupType = backupType; }
+
+ public Instant getCreationDateTime() { return creationDateTime; }
+ public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
+
+ public Instant getExpiryDateTime() { return expiryDateTime; }
+ public void setExpiryDateTime(Instant expiryDateTime) { this.expiryDateTime = expiryDateTime; }
+
+ public long getSizeBytes() { return sizeBytes; }
+ public void setSizeBytes(long sizeBytes) { this.sizeBytes = sizeBytes; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public TableDefinition getTable() { return table; }
+ public void setTable(TableDefinition table) { this.table = table; }
+
+ public List getItems() { return items; }
+ public void setItems(List items) { this.items = items != null ? items : new ArrayList<>(); }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbBackupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbBackupIntegrationTest.java
new file mode 100644
index 0000000000..4a8578cfd6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbBackupIntegrationTest.java
@@ -0,0 +1,773 @@
+package io.github.hectorvent.floci.services.dynamodb;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+@QuarkusTest
+class DynamoDbBackupIntegrationTest {
+
+ private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
+ // JsonPath reads numbers as float, which drops whole seconds at epoch magnitude.
+ private static final ObjectMapper EXACT = new ObjectMapper().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
+ private static final String TABLE_ARN_PREFIX = "arn:aws:dynamodb:us-east-1:000000000000:table/";
+ private static final String BACKUP_ARN_PATTERN =
+ "arn:aws:dynamodb:us-east-1:000000000000:table/%s/backup/\\d{14}-[0-9a-f]{8}";
+ private static final String OTHER_REGION_AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260215/eu-west-2/dynamodb/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+ private static final String OTHER_ACCOUNT_AUTH =
+ "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/dynamodb/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void createBackupAnswersCreatingAndDescribeBackupAnswersAvailable() {
+ String table = "BackupIT-describe";
+ createIndexedTable(table);
+ putItem(table, "a", "1");
+ ddb("UpdateTimeToLive", """
+ {"TableName": "%s", "TimeToLiveSpecification": {"Enabled": true, "AttributeName": "ttl"}}
+ """.formatted(table)).statusCode(200);
+
+ String backupArn = ddb("CreateBackup", """
+ {"TableName": "%s", "BackupName": "describe_me"}
+ """.formatted(table))
+ .statusCode(200)
+ .body("BackupDetails.BackupName", equalTo("describe_me"))
+ .body("BackupDetails.BackupStatus", equalTo("CREATING"))
+ .body("BackupDetails.BackupType", equalTo("USER"))
+ .body("BackupDetails.BackupSizeBytes", equalTo(0))
+ .body("BackupDetails.BackupCreationDateTime", notNullValue())
+ .body("BackupDetails", not(hasKey("BackupExpiryDateTime")))
+ .extract().path("BackupDetails.BackupArn");
+ assertTrue(backupArn.matches(BACKUP_ARN_PATTERN.formatted(table)), backupArn);
+
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}")
+ .statusCode(200)
+ .body("BackupDescription.BackupDetails.BackupArn", equalTo(backupArn))
+ .body("BackupDescription.BackupDetails.BackupStatus", equalTo("AVAILABLE"))
+ .body("BackupDescription.SourceTableDetails.TableName", equalTo(table))
+ .body("BackupDescription.SourceTableDetails.TableArn", equalTo(TABLE_ARN_PREFIX + table))
+ .body("BackupDescription.SourceTableDetails.TableId", notNullValue())
+ .body("BackupDescription.SourceTableDetails.TableCreationDateTime", notNullValue())
+ .body("BackupDescription.SourceTableDetails.ItemCount", equalTo(1))
+ .body("BackupDescription.SourceTableDetails.BillingMode", equalTo("PAY_PER_REQUEST"))
+ .body("BackupDescription.SourceTableDetails.KeySchema.AttributeName", contains("pk", "sk"))
+ .body("BackupDescription.SourceTableDetails.ProvisionedThroughput.ReadCapacityUnits", equalTo(0))
+ .body("BackupDescription.SourceTableDetails.ProvisionedThroughput",
+ not(hasKey("NumberOfDecreasesToday")))
+ .body("BackupDescription.SourceTableFeatureDetails.GlobalSecondaryIndexes[0].IndexName",
+ equalTo("gsi1"))
+ .body("BackupDescription.SourceTableFeatureDetails.GlobalSecondaryIndexes[0]",
+ not(hasKey("IndexStatus")))
+ .body("BackupDescription.SourceTableFeatureDetails.LocalSecondaryIndexes[0].IndexName",
+ equalTo("lsi1"))
+ .body("BackupDescription.SourceTableFeatureDetails.LocalSecondaryIndexes[0]",
+ not(hasKey("IndexArn")))
+ .body("BackupDescription.SourceTableFeatureDetails.StreamDescription.StreamEnabled", equalTo(true))
+ .body("BackupDescription.SourceTableFeatureDetails.StreamDescription.StreamViewType",
+ equalTo("NEW_AND_OLD_IMAGES"))
+ .body("BackupDescription.SourceTableFeatureDetails.TimeToLiveDescription.AttributeName",
+ equalTo("ttl"))
+ .body("BackupDescription.SourceTableFeatureDetails.TimeToLiveDescription.TimeToLiveStatus",
+ equalTo("ENABLED"))
+ .body("BackupDescription.SourceTableFeatureDetails.SSEDescription.SSEType", equalTo("KMS"));
+ }
+
+ @Test
+ void plainTableBackupHasNoFeatureDetails() {
+ String table = "BackupIT-plain";
+ createPlainTable(table);
+ String backupArn = createBackup(table, "plain");
+
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}")
+ .statusCode(200)
+ .body("BackupDescription.SourceTableDetails.BillingMode", equalTo("PROVISIONED"))
+ .body("BackupDescription.SourceTableDetails.ProvisionedThroughput.ReadCapacityUnits", equalTo(1))
+ .body("BackupDescription.SourceTableFeatureDetails.size()", equalTo(0));
+ }
+
+ @Test
+ void createBackupOfMissingTableIsTableNotFound() {
+ ddb("CreateBackup", "{\"TableName\": \"BackupIT-missing\", \"BackupName\": \"abc\"}")
+ .statusCode(400)
+ .body("__type", containsString("TableNotFoundException"))
+ .body("message", equalTo("Table not found: BackupIT-missing"));
+ }
+
+ @Test
+ void createBackupValidatesItsMembers() {
+ ddb("CreateBackup", "{\"BackupName\": \"abc\"}")
+ .statusCode(400)
+ .body("message", equalTo("The parameter 'TableName' is required but was not present in the request"));
+ ddb("CreateBackup", "{\"TableName\": \"BackupIT-missing\"}")
+ .statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value null at 'backupName' failed to "
+ + "satisfy constraint: Member must not be null"));
+ ddb("CreateBackup", "{\"TableName\": \"BackupIT-missing\", \"BackupName\": \"ab\"}")
+ .statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value 'ab' at 'backupName' failed to "
+ + "satisfy constraint: Member must have length greater than or equal to 3"));
+ ddb("CreateBackup", "{\"TableName\": \"BackupIT-missing\", \"BackupName\": \"a b\"}")
+ .statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value 'a b' at 'backupName' failed to "
+ + "satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+"));
+ ddb("CreateBackup", "{\"TableName\": \"a b\", \"BackupName\": \"c d\"}")
+ .statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value 'a b' at 'tableName' failed to "
+ + "satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+"));
+ }
+
+ @Test
+ void backupArnsAreCheckedInTwoSteps() {
+ String base = TABLE_ARN_PREFIX + "BackupIT-none/backup/";
+ for (String arn : List.of("x".repeat(40), base, base + "xy", base + "01700000000000-abcdef12/extra")) {
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + arn + "\"}")
+ .statusCode(400)
+ .body("__type", containsString("ValidationException"))
+ .body("message", equalTo("Invalid Backup ARN"));
+ }
+ for (String arn : List.of(base + "xyz", base + "1700000000000-abcdef12", base + "01700000000000-abcdefgh",
+ "arn:aws:s3:us-east-1:000000000000:table/BackupIT-none/backup/01700000000000-abcdef12",
+ "arn:aws:dynamodb:nowhere-1:000000000000:table/BackupIT-none/backup/01700000000000-abcdef12")) {
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + arn + "\"}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: BackupArn is not valid"));
+ }
+ ddb("DeleteBackup", "{}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Backup ARN"));
+ }
+
+ @Test
+ void unknownBackupIsBackupNotFound() {
+ String arn = TABLE_ARN_PREFIX + "BackupIT-none/backup/01700000000000-ABCDEF12";
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + arn + "\"}")
+ .statusCode(400)
+ .body("__type", containsString("BackupNotFoundException"))
+ .body("message", equalTo("Backup not found: " + arn));
+ ddb("DeleteBackup", "{\"BackupArn\": \"" + arn + "\"}")
+ .statusCode(400)
+ .body("__type", containsString("BackupNotFoundException"));
+ ddb("RestoreTableFromBackup", "{\"BackupArn\": \"" + arn + "\", \"TargetTableName\": \"BackupIT-describe\"}")
+ .statusCode(400)
+ .body("__type", containsString("BackupNotFoundException"));
+ }
+
+ @Test
+ void backupIsScopedToItsRegionAndAccount() {
+ String table = "BackupIT-scope";
+ createPlainTable(table);
+ String backupArn = createBackup(table, "scoped");
+
+ given().header("Authorization", OTHER_REGION_AUTH)
+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeBackup")
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body("{\"BackupArn\": \"" + backupArn + "\"}")
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("BackupNotFoundException"));
+ given().header("Authorization", OTHER_REGION_AUTH)
+ .header("X-Amz-Target", "DynamoDB_20120810.ListBackups")
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body("{\"TableName\": \"" + table + "\"}")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body("BackupSummaries", empty());
+ given().header("Authorization", OTHER_ACCOUNT_AUTH)
+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeBackup")
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body("{\"BackupArn\": \"" + backupArn + "\"}")
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("AccessDeniedException"))
+ .body("message", equalTo("Access is denied"));
+ }
+
+ @Test
+ void listBackupsPagesInCreationOrder() {
+ String table = "BackupIT-list";
+ createPlainTable(table);
+ String first = createBackup(table, "same_name");
+ String second = createBackup(table, "same_name");
+ String third = createBackup(table, "third");
+
+ ddb("ListBackups", "{\"TableName\": \"" + table + "\"}")
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(first, second, third))
+ .body("BackupSummaries[0].BackupStatus", equalTo("AVAILABLE"))
+ .body("BackupSummaries[0].TableName", equalTo(table))
+ .body("BackupSummaries[0].TableArn", equalTo(TABLE_ARN_PREFIX + table))
+ .body("BackupSummaries[0].TableId", notNullValue())
+ .body("$", not(hasKey("LastEvaluatedBackupArn")));
+ ddb("ListBackups", "{\"TableName\": \"" + TABLE_ARN_PREFIX + table + "\", \"Limit\": 2}")
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(first, second))
+ .body("LastEvaluatedBackupArn", equalTo(second));
+ ddb("ListBackups", """
+ {"TableName": "%s", "Limit": 2, "ExclusiveStartBackupArn": "%s"}
+ """.formatted(table, second))
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(third))
+ .body("$", not(hasKey("LastEvaluatedBackupArn")));
+ ddb("ListBackups", """
+ {"TableName": "%s", "ExclusiveStartBackupArn": "%s"}
+ """.formatted(table, TABLE_ARN_PREFIX + table + "/backup/01700000000000-abcdef12"))
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(first, second, third));
+ }
+
+ @Test
+ void listBackupsFiltersByTableTypeAndTime() throws Exception {
+ String table = "BackupIT-filter";
+ createPlainTable(table);
+ String backupArn = createBackup(table, "filtered");
+ BigDecimal created = decimalAt(ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}"),
+ "/BackupDescription/BackupDetails/BackupCreationDateTime");
+
+ ddb("ListBackups", "{\"TableName\": \"BackupIT-nosuch\"}")
+ .statusCode(200)
+ .body("BackupSummaries", empty());
+ ddb("ListBackups", "{\"TableName\": \"" + table + "\", \"BackupType\": \"SYSTEM\"}")
+ .statusCode(200)
+ .body("BackupSummaries", empty());
+ ddb("ListBackups", "{\"TableName\": \"" + table + "\", \"BackupType\": \"ALL\"}")
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(backupArn));
+ ddb("ListBackups", """
+ {"TableName": "%s", "TimeRangeLowerBound": %s, "TimeRangeUpperBound": %s}
+ """.formatted(table, created, created.add(BigDecimal.ONE)))
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(backupArn));
+ ddb("ListBackups", """
+ {"TableName": "%s", "TimeRangeLowerBound": %s, "TimeRangeUpperBound": %s}
+ """.formatted(table, created.subtract(BigDecimal.ONE), created))
+ .statusCode(200)
+ .body("BackupSummaries", empty());
+ ddb("ListBackups", """
+ {"TableName": "%s", "TimeRangeLowerBound": %s, "TimeRangeUpperBound": %s}
+ """.formatted(table, created, created.subtract(BigDecimal.ONE)))
+ .statusCode(400)
+ .body("message", equalTo("One or more parameter values were invalid: "
+ + "Time range lower bound must be less than or equal to upper bound"));
+ }
+
+ @Test
+ void listBackupsReportsEveryViolation() {
+ ddb("ListBackups", "{\"Limit\": 0, \"BackupType\": \"BAD\"}")
+ .statusCode(400)
+ .body("message", equalTo("2 validation errors detected: Value '0' at 'limit' failed to satisfy "
+ + "constraint: Member must have value greater than or equal to 1; Value 'BAD' at "
+ + "'backupType' failed to satisfy constraint: Member must satisfy enum value set: "
+ + "[ALL, AWS_BACKUP, USER, SYSTEM]"));
+ ddb("ListBackups", "{\"Limit\": 101}")
+ .statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value '101' at 'limit' failed to satisfy "
+ + "constraint: Member must have value less than or equal to 100"));
+ ddb("ListBackups", "{\"ExclusiveStartBackupArn\": \"" + "x".repeat(40) + "\"}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Backup ARN"));
+ }
+
+ @Test
+ void deleteBackupAnswersDeletedAndTheBackupIsGone() {
+ String table = "BackupIT-delete";
+ createPlainTable(table);
+ String backupArn = createBackup(table, "doomed");
+
+ ddb("DeleteBackup", "{\"BackupArn\": \"" + backupArn + "\"}")
+ .statusCode(200)
+ .body("BackupDescription.BackupDetails.BackupArn", equalTo(backupArn))
+ .body("BackupDescription.BackupDetails.BackupStatus", equalTo("DELETED"))
+ .body("BackupDescription.SourceTableDetails.TableName", equalTo(table));
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}")
+ .statusCode(400)
+ .body("__type", containsString("BackupNotFoundException"));
+ ddb("ListBackups", "{\"TableName\": \"" + table + "\"}")
+ .statusCode(200)
+ .body("BackupSummaries", empty());
+ }
+
+ @Test
+ void backupOutlivesItsTable() {
+ String table = "BackupIT-outlive";
+ createPlainTable(table);
+ putItem(table, "kept");
+ String backupArn = createBackup(table, "survivor");
+ ddb("DeleteTable", "{\"TableName\": \"" + table + "\"}").statusCode(200);
+
+ ddb("ListBackups", "{\"TableName\": \"" + table + "\"}")
+ .statusCode(200)
+ .body("BackupSummaries.BackupArn", contains(backupArn));
+ ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}")
+ .statusCode(200)
+ .body("BackupDescription.SourceTableDetails.TableName", equalTo(table));
+ ddb("RestoreTableFromBackup", "{\"BackupArn\": \"" + backupArn + "\", \"TargetTableName\": \"" + table + "\"}")
+ .statusCode(200);
+ ddb("GetItem", "{\"TableName\": \"" + table + "\", \"Key\": {\"pk\": {\"S\": \"kept\"}}}")
+ .statusCode(200)
+ .body("Item.pk.S", equalTo("kept"));
+ }
+
+ @Test
+ void restoreTableFromBackupCopiesTheBackedUpItemsAndSchema() throws Exception {
+ String table = "BackupIT-restore-src";
+ String target = "BackupIT-restore-dst";
+ createIndexedTable(table);
+ ddb("UpdateTimeToLive", """
+ {"TableName": "%s", "TimeToLiveSpecification": {"Enabled": true, "AttributeName": "ttl"}}
+ """.formatted(table)).statusCode(200);
+ ddb("UpdateContinuousBackups", """
+ {"TableName": "%s", "PointInTimeRecoverySpecification": {"PointInTimeRecoveryEnabled": true}}
+ """.formatted(table)).statusCode(200);
+ putItem(table, "a", "1");
+ putItem(table, "a", "2");
+ String backupArn = createBackup(table, "restore_me");
+ putItem(table, "a", "after-backup");
+ BigDecimal backupCreated = decimalAt(ddb("DescribeBackup", "{\"BackupArn\": \"" + backupArn + "\"}"),
+ "/BackupDescription/BackupDetails/BackupCreationDateTime");
+
+ ValidatableResponse restored = ddb("RestoreTableFromBackup",
+ "{\"BackupArn\": \"" + backupArn + "\", \"TargetTableName\": \"" + target + "\"}");
+ assertEquals(0, backupCreated.compareTo(decimalAt(restored, "/TableDescription/RestoreSummary/RestoreDateTime")));
+ restored.statusCode(200)
+ .body("TableDescription.TableName", equalTo(target))
+ .body("TableDescription.TableArn", equalTo(TABLE_ARN_PREFIX + target))
+ .body("TableDescription.TableStatus", equalTo("CREATING"))
+ .body("TableDescription.RestoreSummary.SourceBackupArn", equalTo(backupArn))
+ .body("TableDescription.RestoreSummary.SourceTableArn", equalTo(TABLE_ARN_PREFIX + table))
+ .body("TableDescription.RestoreSummary.RestoreInProgress", equalTo(true))
+ .body("TableDescription.GlobalSecondaryIndexes[0].IndexArn",
+ equalTo(TABLE_ARN_PREFIX + target + "/index/gsi1"))
+ .body("TableDescription.LocalSecondaryIndexes[0].IndexName", equalTo("lsi1"))
+ .body("TableDescription.SSEDescription.SSEType", equalTo("KMS"));
+
+ ddb("DescribeTable", "{\"TableName\": \"" + target + "\"}")
+ .statusCode(200)
+ .body("Table.TableStatus", equalTo("ACTIVE"))
+ .body("Table", not(hasKey("RestoreSummary")))
+ .body("Table", not(hasKey("StreamSpecification")))
+ .body("Table.DeletionProtectionEnabled", equalTo(false))
+ .body("Table.TableClassSummary.TableClass", equalTo("STANDARD"))
+ .body("Table.BillingModeSummary.BillingMode", equalTo("PAY_PER_REQUEST"))
+ .body("Table.ItemCount", equalTo(2));
+ ddb("DescribeTimeToLive", "{\"TableName\": \"" + target + "\"}")
+ .statusCode(200)
+ .body("TimeToLiveDescription.TimeToLiveStatus", equalTo("DISABLED"));
+ ddb("DescribeContinuousBackups", "{\"TableName\": \"" + target + "\"}")
+ .statusCode(200)
+ .body("ContinuousBackupsDescription.PointInTimeRecoveryDescription.PointInTimeRecoveryStatus",
+ equalTo("DISABLED"));
+ ddb("ListTagsOfResource", "{\"ResourceArn\": \"" + TABLE_ARN_PREFIX + target + "\"}")
+ .statusCode(200)
+ .body("Tags", empty());
+ ddb("Scan", "{\"TableName\": \"" + target + "\"}")
+ .statusCode(200)
+ .body("Items.sk.S", containsInAnyOrder("1", "2"));
+ ddb("Query", """
+ {"TableName": "%s", "IndexName": "gsi1", "KeyConditionExpression": "g = :g",
+ "ExpressionAttributeValues": {":g": {"S": "g-1"}}}
+ """.formatted(target))
+ .statusCode(200)
+ .body("Count", equalTo(1));
+ }
+
+ @Test
+ void restoreTableFromBackupRefusesAnExistingTarget() {
+ String table = "BackupIT-exists";
+ createPlainTable(table);
+ String backupArn = createBackup(table, "exists");
+
+ ddb("RestoreTableFromBackup", "{\"BackupArn\": \"" + backupArn + "\", \"TargetTableName\": \"" + table + "\"}")
+ .statusCode(400)
+ .body("__type", containsString("TableAlreadyExistsException"))
+ .body("message", equalTo("Table already exists: " + table));
+ }
+
+ @Test
+ void restoreTableFromBackupChecksTheArnFirst() {
+ ddb("RestoreTableFromBackup", "{\"BackupArn\": \"" + "x".repeat(40) + "\", \"TargetTableName\": \"a b\"}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Backup ARN"));
+ String arn = TABLE_ARN_PREFIX + "BackupIT-none/backup/01700000000000-abcdef12";
+ ddb("RestoreTableFromBackup", "{\"BackupArn\": \"" + arn + "\"}")
+ .statusCode(400)
+ .body("message", equalTo("The parameter 'TableName' is required but was not present in the request"));
+ ddb("RestoreTableFromBackup", """
+ {"BackupArn": "%s", "TargetTableName": "a b", "BillingModeOverride": "BAD"}
+ """.formatted(arn))
+ .statusCode(400)
+ .body("message", equalTo("2 validation errors detected: Value 'BAD' at 'billingModeOverride' "
+ + "failed to satisfy constraint: Member must satisfy enum value set: "
+ + "[PROVISIONED, PAY_PER_REQUEST]; Value 'a b' at 'targetTableName' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+"));
+ }
+
+ @Test
+ void restoreReportsEveryViolationBeforeTheBackupLookup() {
+ String arn = TABLE_ARN_PREFIX + "BackupIT-none/backup/01700000000000-abcdef12";
+ String notNull = "failed to satisfy constraint: Member must not be null";
+ String atLeastOne = "failed to satisfy constraint: Member must have value greater than or equal to 1";
+ ddb("RestoreTableFromBackup", """
+ {"BackupArn": "%s", "TargetTableName": "bad name!", "BillingModeOverride": "BAD",
+ "ProvisionedThroughputOverride": {},
+ "GlobalSecondaryIndexOverride": [%s]}
+ """.formatted(arn, gsi1(", \"ProvisionedThroughput\": {}").replace("\"gsi1\"", "\"x!\"")))
+ .statusCode(400)
+ .body("message", equalTo("8 validation errors detected: "
+ + "Value null at 'provisionedThroughputOverride.writeCapacityUnits' " + notNull + "; "
+ + "Value null at 'provisionedThroughputOverride.readCapacityUnits' " + notNull + "; "
+ + "Value 'BAD' at 'billingModeOverride' failed to satisfy constraint: Member must satisfy "
+ + "enum value set: [PROVISIONED, PAY_PER_REQUEST]; "
+ + "Value 'bad name!' at 'targetTableName' failed to satisfy constraint: Member must satisfy "
+ + "regular expression pattern: [a-zA-Z0-9_.-]+; "
+ + "Value 'x!' at 'globalSecondaryIndexOverride.1.member.indexName' failed to satisfy "
+ + "constraint: Member must have length greater than or equal to 3; "
+ + "Value 'x!' at 'globalSecondaryIndexOverride.1.member.indexName' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+; "
+ + "Value null at 'globalSecondaryIndexOverride.1.member.provisionedThroughput."
+ + "writeCapacityUnits' " + notNull + "; "
+ + "Value null at 'globalSecondaryIndexOverride.1.member.provisionedThroughput."
+ + "readCapacityUnits' " + notNull));
+ ddb("RestoreTableFromBackup", """
+ {"BackupArn": "%s", "TargetTableName": "BackupIT-none-x", "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 0}}
+ """.formatted(arn))
+ .statusCode(400)
+ .body("message", equalTo("2 validation errors detected: "
+ + "Value null at 'provisionedThroughputOverride.writeCapacityUnits' " + notNull + "; "
+ + "Value '0' at 'provisionedThroughputOverride.readCapacityUnits' " + atLeastOne));
+ ddb("RestoreTableFromBackup", """
+ {"BackupArn": "%s", "TargetTableName": "BackupIT-none-x", "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 0, "WriteCapacityUnits": 1},
+ "GlobalSecondaryIndexOverride": [%s]}
+ """.formatted(arn, gsi1(", \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 0, "
+ + "\"WriteCapacityUnits\": 0}")))
+ .statusCode(400)
+ .body("message", equalTo("3 validation errors detected: "
+ + "Value '0' at 'provisionedThroughputOverride.readCapacityUnits' " + atLeastOne + "; "
+ + "Value '0' at 'globalSecondaryIndexOverride.1.member.provisionedThroughput."
+ + "writeCapacityUnits' " + atLeastOne + "; "
+ + "Value '0' at 'globalSecondaryIndexOverride.1.member.provisionedThroughput."
+ + "readCapacityUnits' " + atLeastOne));
+ }
+
+ @Test
+ void restoreOverridesFollowTheBillingMode() {
+ String table = "BackupIT-billing";
+ createIndexedTable(table);
+ String backupArn = createBackup(table, "billing");
+
+ restore(backupArn, "BackupIT-billing-x", "\"BillingModeOverride\": \"PROVISIONED\"")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Must override ProvisionedThroughput if BillingMode is "
+ + "overridden to PROVISIONED"));
+ restore(backupArn, "BackupIT-billing-x", """
+ "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3}
+ """)
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Must override ProvisionedThroughput if BillingMode is "
+ + "overridden to PROVISIONED for index gsi1"));
+ restore(backupArn, "BackupIT-billing-x",
+ "\"ProvisionedThroughputOverride\": {\"ReadCapacityUnits\": 2, \"WriteCapacityUnits\": 3}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override ProvisionedThroughput unless "
+ + "BillingMode is PROVISIONED"));
+ restore(backupArn, "BackupIT-billing-x", """
+ "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3},
+ "OnDemandThroughputOverride": {"MaxReadRequestUnits": 10}
+ """)
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxReadRequestUnits for "
+ + "OnDemandThroughput when BillingMode is PROVISIONED"));
+ restore(backupArn, "BackupIT-billing-x", "\"GlobalSecondaryIndexOverride\": [" + gsi1(
+ ", \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 4, \"WriteCapacityUnits\": 5}") + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override ProvisionedThroughput unless "
+ + "BillingMode is PROVISIONED for index gsi1"));
+
+ restore(backupArn, "BackupIT-billing-provisioned", """
+ "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3},
+ "GlobalSecondaryIndexOverride": [%s]
+ """.formatted(gsi1(", \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 4, \"WriteCapacityUnits\": 5}")))
+ .statusCode(200)
+ .body("TableDescription", not(hasKey("BillingModeSummary")))
+ .body("TableDescription.ProvisionedThroughput.ReadCapacityUnits", equalTo(2))
+ .body("TableDescription.ProvisionedThroughput.WriteCapacityUnits", equalTo(3))
+ .body("TableDescription.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits",
+ equalTo(4));
+ restore(backupArn, "BackupIT-billing-ondemand", "\"OnDemandThroughputOverride\": {\"MaxReadRequestUnits\": 10}")
+ .statusCode(200)
+ .body("TableDescription.OnDemandThroughput.MaxReadRequestUnits", equalTo(10));
+ }
+
+ @Test
+ void restoreOnDemandOverridesMergeWithTheSourceAndFollowTheBillingMode() {
+ String table = "BackupIT-ondemand";
+ ddb("CreateTable", """
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "g", "AttributeType": "S"}],
+ "GlobalSecondaryIndexes": [%s],
+ "BillingMode": "PAY_PER_REQUEST",
+ "OnDemandThroughput": {"MaxReadRequestUnits": 7, "MaxWriteRequestUnits": 8}
+ }
+ """.formatted(table, gsi1(", \"OnDemandThroughput\": {\"MaxReadRequestUnits\": 5, "
+ + "\"MaxWriteRequestUnits\": 6}"))).statusCode(200);
+ String backupArn = createBackup(table, "ondemand");
+ String gsiThroughput = ", \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 1, \"WriteCapacityUnits\": 1}";
+ String provisioned = """
+ "BillingModeOverride": "PROVISIONED",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3},
+ """;
+
+ restore(backupArn, "BackupIT-ondemand-x", provisioned + "\"GlobalSecondaryIndexOverride\": [" + gsi1(
+ gsiThroughput + ", \"OnDemandThroughput\": {\"MaxWriteRequestUnits\": 5}") + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxWriteRequestUnits for "
+ + "OnDemandThroughput when BillingMode is PROVISIONED for index gsi1"));
+ restore(backupArn, "BackupIT-ondemand-x", "\"GlobalSecondaryIndexOverride\": [" + gsi1(
+ gsiThroughput + ", \"OnDemandThroughput\": {\"MaxReadRequestUnits\": 5}") + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxReadRequestUnits for "
+ + "OnDemandThroughput when ProvisionedThroughputOverride is present for index gsi1"));
+ restore(backupArn, "BackupIT-ondemand-x", """
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3},
+ "OnDemandThroughputOverride": {"MaxReadRequestUnits": 10}
+ """)
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxReadRequestUnits for "
+ + "OnDemandThroughput when ProvisionedThroughputOverride is present"));
+ restore(backupArn, "BackupIT-ondemand-x", """
+ "BillingModeOverride": "PAY_PER_REQUEST",
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3}
+ """)
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override ProvisionedThroughput if BillingMode "
+ + "is overridden to PAY_PER_REQUEST"));
+ restore(backupArn, "BackupIT-ondemand-x", "\"BillingModeOverride\": \"PAY_PER_REQUEST\", "
+ + "\"GlobalSecondaryIndexOverride\": [" + gsi1(gsiThroughput) + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override ProvisionedThroughput if BillingMode "
+ + "is overridden to PAY_PER_REQUEST for index gsi1"));
+
+ restore(backupArn, "BackupIT-ondemand-provisioned",
+ provisioned + "\"GlobalSecondaryIndexOverride\": [" + gsi1(gsiThroughput) + "]")
+ .statusCode(200)
+ .body("TableDescription", not(hasKey("OnDemandThroughput")))
+ .body("TableDescription.GlobalSecondaryIndexes[0]", not(hasKey("OnDemandThroughput")));
+ restore(backupArn, "BackupIT-ondemand-merged", """
+ "OnDemandThroughputOverride": {"MaxReadRequestUnits": 10},
+ "GlobalSecondaryIndexOverride": [%s]
+ """.formatted(gsi1(", \"OnDemandThroughput\": {\"MaxWriteRequestUnits\": 9}")))
+ .statusCode(200)
+ .body("TableDescription.OnDemandThroughput.MaxReadRequestUnits", equalTo(10))
+ .body("TableDescription.OnDemandThroughput.MaxWriteRequestUnits", equalTo(8))
+ .body("TableDescription.GlobalSecondaryIndexes[0].OnDemandThroughput.MaxReadRequestUnits", equalTo(5))
+ .body("TableDescription.GlobalSecondaryIndexes[0].OnDemandThroughput.MaxWriteRequestUnits",
+ equalTo(9));
+ restore(backupArn, "BackupIT-ondemand-empty", """
+ "OnDemandThroughputOverride": {},
+ "GlobalSecondaryIndexOverride": [%s]
+ """.formatted(gsi1(", \"OnDemandThroughput\": {}")))
+ .statusCode(200)
+ .body("TableDescription.OnDemandThroughput.MaxReadRequestUnits", equalTo(7))
+ .body("TableDescription.GlobalSecondaryIndexes[0].OnDemandThroughput.MaxWriteRequestUnits",
+ equalTo(6));
+ }
+
+ @Test
+ void restoreOfAProvisionedTableNeedsThroughputForEveryIndexOverride() {
+ String table = "BackupIT-provisioned";
+ String gsiThroughput = ", \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 1, \"WriteCapacityUnits\": 1}";
+ ddb("CreateTable", """
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "g", "AttributeType": "S"}],
+ "GlobalSecondaryIndexes": [%s],
+ "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}
+ }
+ """.formatted(table, gsi1(gsiThroughput))).statusCode(200);
+ String backupArn = createBackup(table, "provisioned");
+
+ restore(backupArn, "BackupIT-provisioned-x", "\"GlobalSecondaryIndexOverride\": [" + gsi1("") + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Must specify provisioned throughput for index gsi1"));
+ restore(backupArn, "BackupIT-provisioned-x", "\"GlobalSecondaryIndexOverride\": [" + gsi1(
+ ", \"OnDemandThroughput\": {\"MaxReadRequestUnits\": 5}") + "]")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxReadRequestUnits for "
+ + "OnDemandThroughput unless BillingModeOverride is PAY_PER_REQUEST for index gsi1"));
+ restore(backupArn, "BackupIT-provisioned-x", "\"OnDemandThroughputOverride\": {\"MaxReadRequestUnits\": 10}")
+ .statusCode(400)
+ .body("message", equalTo("Invalid Request: Cannot override MaxReadRequestUnits for "
+ + "OnDemandThroughput unless BillingModeOverride is PAY_PER_REQUEST"));
+
+ restore(backupArn, "BackupIT-provisioned-kept", """
+ "ProvisionedThroughputOverride": {"ReadCapacityUnits": 2, "WriteCapacityUnits": 3},
+ "OnDemandThroughputOverride": {},
+ "GlobalSecondaryIndexOverride": [%s]
+ """.formatted(gsi1(gsiThroughput + ", \"OnDemandThroughput\": {}")))
+ .statusCode(200)
+ .body("TableDescription.ProvisionedThroughput.ReadCapacityUnits", equalTo(2))
+ .body("TableDescription.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits",
+ equalTo(1))
+ .body("TableDescription.GlobalSecondaryIndexes[0]", not(hasKey("OnDemandThroughput")));
+ restore(backupArn, "BackupIT-provisioned-ondemand", """
+ "BillingModeOverride": "PAY_PER_REQUEST",
+ "GlobalSecondaryIndexOverride": [%s]
+ """.formatted(gsi1(", \"OnDemandThroughput\": {\"MaxReadRequestUnits\": 5}")))
+ .statusCode(200)
+ .body("TableDescription.BillingModeSummary.BillingMode", equalTo("PAY_PER_REQUEST"))
+ .body("TableDescription.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits",
+ equalTo(0))
+ .body("TableDescription.GlobalSecondaryIndexes[0].OnDemandThroughput.MaxReadRequestUnits", equalTo(5))
+ .body("TableDescription.GlobalSecondaryIndexes[0].OnDemandThroughput",
+ not(hasKey("MaxWriteRequestUnits")));
+ }
+
+ @Test
+ void restoreIndexOverridesMustMatchTheSourceIndexes() {
+ String table = "BackupIT-indexes";
+ createIndexedTable(table);
+ String backupArn = createBackup(table, "indexes");
+ String mismatch = "Invalid Request: Index %s does not match a secondary index that existed in the source "
+ + "table and cannot be created during the restore operation";
+
+ restore(backupArn, "BackupIT-indexes-x", """
+ "GlobalSecondaryIndexOverride": [{"IndexName": "gsi1",
+ "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], "Projection": {"ProjectionType": "KEYS_ONLY"}}]
+ """)
+ .statusCode(400)
+ .body("message", equalTo(mismatch.formatted("gsi1")));
+ restore(backupArn, "BackupIT-indexes-x", """
+ "LocalSecondaryIndexOverride": [{"IndexName": "lsi1",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "l", "KeyType": "RANGE"}],
+ "Projection": {"ProjectionType": "ALL"}}]
+ """)
+ .statusCode(400)
+ .body("message", equalTo(mismatch.formatted("lsi1")));
+
+ restore(backupArn, "BackupIT-indexes-renamed", """
+ "LocalSecondaryIndexOverride": [{"IndexName": "renamed",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "l", "KeyType": "RANGE"}],
+ "Projection": {"ProjectionType": "KEYS_ONLY"}}]
+ """)
+ .statusCode(200)
+ .body("TableDescription.LocalSecondaryIndexes.IndexName", contains("renamed"))
+ .body("TableDescription.GlobalSecondaryIndexes.IndexName", contains("gsi1"));
+ restore(backupArn, "BackupIT-indexes-dropped", """
+ "GlobalSecondaryIndexOverride": [], "LocalSecondaryIndexOverride": [],
+ "SSESpecificationOverride": {"Enabled": false}
+ """)
+ .statusCode(200)
+ .body("TableDescription", not(hasKey("GlobalSecondaryIndexes")))
+ .body("TableDescription", not(hasKey("LocalSecondaryIndexes")))
+ .body("TableDescription", not(hasKey("SSEDescription")))
+ .body("TableDescription.AttributeDefinitions.AttributeName", containsInAnyOrder("pk", "sk"));
+ }
+
+ private void createIndexedTable(String table) {
+ ddb("CreateTable", """
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}],
+ "AttributeDefinitions": [
+ {"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "sk", "AttributeType": "S"},
+ {"AttributeName": "g", "AttributeType": "S"},
+ {"AttributeName": "l", "AttributeType": "S"}
+ ],
+ "GlobalSecondaryIndexes": [%s],
+ "LocalSecondaryIndexes": [{"IndexName": "lsi1",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "l", "KeyType": "RANGE"}],
+ "Projection": {"ProjectionType": "KEYS_ONLY"}}],
+ "BillingMode": "PAY_PER_REQUEST",
+ "StreamSpecification": {"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"},
+ "SSESpecification": {"Enabled": true, "SSEType": "KMS"},
+ "TableClass": "STANDARD_INFREQUENT_ACCESS",
+ "DeletionProtectionEnabled": true,
+ "Tags": [{"Key": "k", "Value": "v"}]
+ }
+ """.formatted(table, gsi1(""))).statusCode(200);
+ }
+
+ private static String gsi1(String extra) {
+ return "{\"IndexName\": \"gsi1\", \"KeySchema\": [{\"AttributeName\": \"g\", \"KeyType\": \"HASH\"}], "
+ + "\"Projection\": {\"ProjectionType\": \"ALL\"}" + extra + "}";
+ }
+
+ private void createPlainTable(String table) {
+ ddb("CreateTable", """
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}
+ }
+ """.formatted(table)).statusCode(200);
+ }
+
+ private void putItem(String table, String pk) {
+ ddb("PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"" + pk + "\"}}}")
+ .statusCode(200);
+ }
+
+ private void putItem(String table, String pk, String sk) {
+ ddb("PutItem", """
+ {"TableName": "%s", "Item": {"pk": {"S": "%s"}, "sk": {"S": "%s"}, "g": {"S": "g-%s"},
+ "l": {"S": "l-%s"}, "ttl": {"N": "4102444800"}}}
+ """.formatted(table, pk, sk, sk, sk)).statusCode(200);
+ }
+
+ private String createBackup(String table, String backupName) {
+ return ddb("CreateBackup", "{\"TableName\": \"" + table + "\", \"BackupName\": \"" + backupName + "\"}")
+ .statusCode(200)
+ .extract().path("BackupDetails.BackupArn");
+ }
+
+ private ValidatableResponse restore(String backupArn, String target, String overrides) {
+ return ddb("RestoreTableFromBackup", """
+ {"BackupArn": "%s", "TargetTableName": "%s", %s}
+ """.formatted(backupArn, target, overrides));
+ }
+
+ private static BigDecimal decimalAt(ValidatableResponse response, String pointer) throws Exception {
+ return EXACT.readTree(response.extract().asString()).at(pointer).decimalValue();
+ }
+
+ private ValidatableResponse ddb(String action, String body) {
+ return given()
+ .header("X-Amz-Target", "DynamoDB_20120810." + action)
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body(body)
+ .when().post("/")
+ .then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
index 5e19bcd51d..785435c017 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.dynamodb;
+import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -8,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
@@ -16,16 +18,19 @@ import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.ImportTableDescription;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
+import io.github.hectorvent.floci.services.dynamodb.model.TableBackup;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
@@ -4587,4 +4592,34 @@ class DynamoDbServiceTest {
assertEquals("InterruptedByRestart", restarted.describeImport(importDesc.getImportArn()).getFailureCode());
assertEquals("FAILED", restarted.describeExport(exportDesc.getExportArn()).getExportStatus());
}
+
+ @Test
+ void backupKeepsItsSnapshotAcrossLaterWritesAndARestart(@TempDir Path dir) {
+ RegionResolver resolver = new RegionResolver("us-east-1", "000000000000");
+ StorageBackend tables = new InMemoryStorage<>();
+ StorageBackend> items = new InMemoryStorage<>();
+ Path backupFile = dir.resolve("dynamodb-backups.json");
+ TypeReference