Light, fluffy, and always free - The AWS Local Emulator alternative
feat(dynamodb): add the legacy global table operations (#4288)
lex0072231c09cff8
diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.mdindex c229505181..0aa5ed41a9 100644--- a/docs/services/dynamodb.md+++ b/docs/services/dynamodb.md@@ -34,6 +34,10 @@| `EnableKinesisStreamingDestination` | Enable Kinesis streaming for a table || `DisableKinesisStreamingDestination` | Disable Kinesis streaming for a table || `ExportTableToPointInTime` | Export table data to S3 as gzip NDJSON |+| `CreateGlobalTable` | Make an existing table a global table (2017.11.29) |+| `DescribeGlobalTable` | Read a global table's replication group |+| `UpdateGlobalTable` | Add or remove replica regions |+| `ListGlobalTables` | List global tables, optionally filtered by region || `DescribeExport` | Get export status and metadata || `ListExports` | List exports, optionally filtered by table ARN || `ImportTable` | Create a table and load DynamoDB JSON from S3 into it |diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.javaindex 6f2441b9b2..e992d24299 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java@@ -77,6 +77,10 @@ public class DynamoDbJsonHandler {case "DisableKinesisStreamingDestination" -> handleDisableKinesisStreamingDestination(request, region);case "DescribeKinesisStreamingDestination" -> handleDescribeKinesisStreamingDestination(request, region);case "ExportTableToPointInTime" -> handleExportTable(request, region);+ case "CreateGlobalTable" -> handleCreateGlobalTable(request, region);+ case "DescribeGlobalTable" -> handleDescribeGlobalTable(request, region);+ case "UpdateGlobalTable" -> handleUpdateGlobalTable(request, region);+ case "ListGlobalTables" -> handleListGlobalTables(request, region);case "DescribeExport" -> handleDescribeExport(request, region);case "ListExports" -> handleListExports(request, region);case "ImportTable" -> handleImportTable(request, region);@@ -388,6 +392,104 @@ public class DynamoDbJsonHandler {return Response.ok(response).build();}+ // ── Global tables, the 2017.11.29 API ────────────────────────────────────++ private Response handleCreateGlobalTable(JsonNode request, String region) {+ String name = request.path("GlobalTableName").asText();+ TableDefinition table = dynamoDbService.createGlobalTable(+ name, replicationGroupRegions(request), region);+ ObjectNode root = objectMapper.createObjectNode();+ root.set("GlobalTableDescription", globalTableDescription(table, name));+ return Response.ok(root).build();+ }++ private Response handleDescribeGlobalTable(JsonNode request, String region) {+ String name = request.path("GlobalTableName").asText();+ TableDefinition table = dynamoDbService.describeGlobalTable(name, region);+ ObjectNode root = objectMapper.createObjectNode();+ root.set("GlobalTableDescription", globalTableDescription(table, name));+ return Response.ok(root).build();+ }++ private Response handleUpdateGlobalTable(JsonNode request, String region) {+ String name = request.path("GlobalTableName").asText();+ List<String> adds = new ArrayList<>();+ List<String> removes = new ArrayList<>();+ for (JsonNode update : request.path("ReplicaUpdates")) {+ String create = update.path("Create").path("RegionName").asText(null);+ String delete = update.path("Delete").path("RegionName").asText(null);+ if (create != null) {+ adds.add(create);+ }+ if (delete != null) {+ removes.add(delete);+ }+ }+ TableDefinition table = dynamoDbService.updateGlobalTable(name, adds, removes, region);+ ObjectNode root = objectMapper.createObjectNode();+ root.set("GlobalTableDescription", globalTableDescription(table, name));+ return Response.ok(root).build();+ }++ private Response handleListGlobalTables(JsonNode request, String region) {+ String regionFilter = request.path("RegionName").asText(null);+ ArrayNode list = objectMapper.createArrayNode();+ for (TableDefinition table : dynamoDbService.listGlobalTables(regionFilter, region)) {+ ObjectNode entry = objectMapper.createObjectNode();+ entry.put("GlobalTableName", table.getTableName());+ entry.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), false));+ list.add(entry);+ }+ ObjectNode root = objectMapper.createObjectNode();+ root.set("GlobalTables", list);+ return Response.ok(root).build();+ }++ private static List<String> replicationGroupRegions(JsonNode request) {+ List<String> regions = new ArrayList<>();+ for (JsonNode replica : request.path("ReplicationGroup")) {+ String name = replica.path("RegionName").asText(null);+ if (name != null && !name.isBlank()) {+ regions.add(name);+ }+ }+ return regions;+ }++ private ObjectNode globalTableDescription(TableDefinition table, String globalTableName) {+ ObjectNode description = objectMapper.createObjectNode();+ description.put("GlobalTableName", globalTableName);+ description.put("GlobalTableStatus", "ACTIVE");+ description.put("GlobalTableArn", table.getTableArn());+ if (table.getCreationDateTime() != null) {+ description.put("CreationDateTime", table.getCreationDateTime().getEpochSecond());+ }+ description.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), true));+ return description;+ }++ /**+ * The replica list of a global table: every tracked replica plus the home region, which AWS+ * reports as a replica of its own global table. ReplicaStatus is only carried by the+ * description shapes, not by the ListGlobalTables entry.+ */+ private ArrayNode replicaNodes(TableDefinition table, ArrayNode replicas, boolean withStatus) {+ LinkedHashSet<String> regions = new LinkedHashSet<>(+ table.getReplicaRegions() != null ? table.getReplicaRegions() : List.of());+ if (table.getGlobalTableHomeRegion() != null) {+ regions.add(table.getGlobalTableHomeRegion());+ }+ for (String replicaRegion : regions) {+ ObjectNode replica = objectMapper.createObjectNode();+ replica.put("RegionName", replicaRegion);+ if (withStatus) {+ replica.put("ReplicaStatus", "ACTIVE");+ }+ replicas.add(replica);+ }+ return replicas;+ }+private Response handleDescribeTable(JsonNode request, String region) {String tableName = request.path("TableName").asText();TableDefinition table = dynamoDbService.describeTable(tableName, region);diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.javaindex 3251544225..1462f35155 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java@@ -2505,6 +2505,110 @@ public class DynamoDbService implements ResourceProvider {return table;}+ /**+ * CreateGlobalTable, the 2017.11.29 API. It builds a global table out of a table that already+ * exists, so the table is resolved first and an absent one is TableNotFoundException rather+ * than the ResourceNotFoundException the item operations raise.+ *+ * <p>The model states the conditions a replica must meet, and the one this emulator can check+ * is the stream: the table must have DynamoDB Streams enabled with both the new and the old+ * image. The rest concern tables in other regions, which a single-process emulator serves from+ * this same table, so there is nothing separate to compare.+ */+ public TableDefinition createGlobalTable(String globalTableName, List<String> replicaRegions,+ String region) {+ String canonicalTableName = canonicalTableName(region, globalTableName);+ TableDefinition table = tableStore.get(regionKey(region, canonicalTableName))+ .orElseThrow(() -> new AwsException("TableNotFoundException",+ "Table not found: " + canonicalTableName, 400));+ if (table.getGlobalTableHomeRegion() != null) {+ throw new AwsException("GlobalTableAlreadyExistsException",+ "Global table already exists: " + globalTableName, 400);+ }+ requireStreamWithBothImages(table, canonicalTableName);+ List<String> adds = replicaRegions == null ? List.of() : replicaRegions.stream()+ .filter(r -> r != null && !r.isBlank() && !r.equals(region))+ .toList();+ applyReplicaUpdates(globalTableName, adds, List.of(), region);+ return ensureGlobalTable(globalTableName, region);+ }++ /** DescribeGlobalTable. A table that is not a global table has no description to give. */+ public TableDefinition describeGlobalTable(String globalTableName, String region) {+ String canonicalTableName = canonicalTableName(region, globalTableName);+ TableDefinition table = tableStore.get(regionKey(region, canonicalTableName))+ .filter(t -> t.getGlobalTableHomeRegion() != null)+ .orElseThrow(() -> new AwsException("GlobalTableNotFoundException",+ "Global table not found: " + globalTableName, 400));+ return table;+ }++ /**+ * UpdateGlobalTable's replica adds and removes, on a table that is already a global table.+ *+ * <p>The membership checks live here rather than in {@link #applyReplicaUpdates}, which stays+ * idempotent for the UpdateTable and CloudFormation paths that re-apply an unchanged set. The+ * model draws the same line: UpdateGlobalTable declares ReplicaAlreadyExistsException and+ * ReplicaNotFoundException, and UpdateTable declares neither, so delegating without checking+ * first is exactly what would drop them.+ */+ public TableDefinition updateGlobalTable(String globalTableName, List<String> addRegions,+ List<String> removeRegions, String region) {+ TableDefinition table = describeGlobalTable(globalTableName, region);+ Set<String> replicas = currentReplicaRegions(table);+ if (addRegions != null) {+ for (String add : addRegions) {+ if (replicas.contains(add)) {+ throw new AwsException("ReplicaAlreadyExistsException",+ "Replica already exists in region " + add + ".", 400);+ }+ }+ }+ if (removeRegions != null) {+ for (String remove : removeRegions) {+ if (!replicas.contains(remove)) {+ throw new AwsException("ReplicaNotFoundException",+ "Replica not found in region " + remove + ".", 400);+ }+ }+ }+ return applyReplicaUpdates(globalTableName, addRegions, removeRegions, region);+ }++ /** The tracked replicas plus the home region, which is a replica of its own global table. */+ private static Set<String> currentReplicaRegions(TableDefinition table) {+ Set<String> regions = new LinkedHashSet<>(+ table.getReplicaRegions() != null ? table.getReplicaRegions() : List.of());+ if (table.getGlobalTableHomeRegion() != null) {+ regions.add(table.getGlobalTableHomeRegion());+ }+ return regions;+ }++ /** ListGlobalTables, optionally narrowed to the tables replicated into one region. */+ public List<TableDefinition> listGlobalTables(String regionFilter, String region) {+ return tableStore.scan(k -> k.startsWith(region + "::")).stream()+ .filter(t -> t.getGlobalTableHomeRegion() != null)+ .filter(t -> regionFilter == null || regionFilter.isBlank()+ || regionFilter.equals(t.getGlobalTableHomeRegion())+ || t.getReplicaRegions().contains(regionFilter))+ .sorted(Comparator.comparing(TableDefinition::getTableName))+ .toList();+ }++ /**+ * The one replica precondition a single-process emulator can actually test. A global table+ * replicates by reading the stream, so a table without one, or with a view that omits either+ * image, cannot be a replica source.+ */+ private static void requireStreamWithBothImages(TableDefinition table, String tableName) {+ if (!table.isStreamEnabled() || !"NEW_AND_OLD_IMAGES".equals(table.getStreamViewType())) {+ throw new AwsException("ValidationException",+ "Table " + tableName + " must have DynamoDB Streams enabled with "+ + "StreamViewType NEW_AND_OLD_IMAGES to join a global table.", 400);+ }+ }+public void validateReplicaUpdates(String tableName, List<String> addRegions,List<String> removeRegions, List<String> updateRegions, String region) {validateReplicaUpdatesAndGetTable(tableName, addRegions, removeRegions, updateRegions, region);diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGlobalTableIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGlobalTableIntegrationTest.javanew file mode 100644index 0000000000..75dc4ef98f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGlobalTableIntegrationTest.java@@ -0,0 +1,169 @@+package io.github.hectorvent.floci.services.dynamodb;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.RestAssured;+import io.restassured.parsing.Parser;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.containsInAnyOrder;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.is;+import static org.hamcrest.Matchers.not;++/** CreateGlobalTable and its Describe, Update and List siblings, the 2017.11.29 API. */+@QuarkusTest+class DynamoDbGlobalTableIntegrationTest {++ @BeforeAll+ static void readTheJson10ResponsesAsJson() {+ RestAssured.registerParser("application/x-amz-json-1.0", Parser.JSON);+ }++ private static io.restassured.response.Response call(String target, String body) {+ return given()+ .header("X-Amz-Target", "DynamoDB_20120810." + target)+ .contentType("application/x-amz-json-1.0")+ .body(body.getBytes(java.nio.charset.StandardCharsets.UTF_8))+ .when().post("/");+ }++ private static void createTable(String name, boolean streams, String viewType) {+ String stream = streams+ ? ",\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"" + viewType + "\"}"+ : "";+ call("CreateTable", "{\"TableName\":\"" + name + "\","+ + "\"AttributeDefinitions\":[{\"AttributeName\":\"pk\",\"AttributeType\":\"S\"}],"+ + "\"KeySchema\":[{\"AttributeName\":\"pk\",\"KeyType\":\"HASH\"}],"+ + "\"BillingMode\":\"PAY_PER_REQUEST\"" + stream + "}")+ .then().statusCode(200);+ }++ @Test+ void createDescribeAndUpdateAGlobalTable() {+ String name = "gt-lifecycle-" + Long.toString(System.nanoTime(), 36);+ createTable(name, true, "NEW_AND_OLD_IMAGES");++ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}")+ .then().statusCode(200)+ .body("GlobalTableDescription.GlobalTableName", is(name))+ .body("GlobalTableDescription.GlobalTableStatus", is("ACTIVE"))+ .body("GlobalTableDescription.ReplicationGroup.RegionName",+ containsInAnyOrder("eu-west-1", "us-east-1"))+ .body("GlobalTableDescription.ReplicationGroup.ReplicaStatus", hasItem("ACTIVE"));++ call("DescribeGlobalTable", "{\"GlobalTableName\":\"" + name + "\"}")+ .then().statusCode(200)+ .body("GlobalTableDescription.ReplicationGroup.RegionName", hasItem("eu-west-1"));++ call("UpdateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicaUpdates\":[{\"Create\":{\"RegionName\":\"ap-south-1\"}},"+ + "{\"Delete\":{\"RegionName\":\"eu-west-1\"}}]}")+ .then().statusCode(200)+ .body("GlobalTableDescription.ReplicationGroup.RegionName", hasItem("ap-south-1"))+ .body("GlobalTableDescription.ReplicationGroup.RegionName", not(hasItem("eu-west-1")));++ call("ListGlobalTables", "{}")+ .then().statusCode(200)+ .body("GlobalTables.GlobalTableName", hasItem(name));+ }++ @Test+ void aSecondCreateOnTheSameTableIsRefused() {+ String name = "gt-dup-" + Long.toString(System.nanoTime(), 36);+ createTable(name, true, "NEW_AND_OLD_IMAGES");++ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}").then().statusCode(200);++ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}")+ .then().statusCode(400)+ .body("__type", is("GlobalTableAlreadyExistsException"));+ }++ @Test+ void aTableThatDoesNotExistIsTableNotFound() {+ call("CreateGlobalTable", "{\"GlobalTableName\":\"gt-missing-table\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}")+ .then().statusCode(400)+ .body("__type", is("TableNotFoundException"));+ }++ @Test+ void aTableWithoutBothStreamImagesCannotJoin() {+ String noStream = "gt-nostream-" + Long.toString(System.nanoTime(), 36);+ createTable(noStream, false, null);+ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + noStream + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}")+ .then().statusCode(400)+ // The code matters: this file raises ValidationException everywhere else, so a+ // different shape here would slip past a client catching that one.+ .body("__type", is("ValidationException"));++ String newOnly = "gt-newonly-" + Long.toString(System.nanoTime(), 36);+ createTable(newOnly, true, "NEW_IMAGE");+ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + newOnly + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}")+ .then().statusCode(400)+ .body("__type", is("ValidationException"));+ }++ @Test+ void describingATableThatIsNotGlobalIsNotFound() {+ String name = "gt-plain-" + Long.toString(System.nanoTime(), 36);+ createTable(name, true, "NEW_AND_OLD_IMAGES");+ call("DescribeGlobalTable", "{\"GlobalTableName\":\"" + name + "\"}")+ .then().statusCode(400)+ .body("__type", is("GlobalTableNotFoundException"));+ }++ @Test+ void updateRefusesADuplicateAddAndAnAbsentRemove() {+ String name = "gt-replicafault-" + Long.toString(System.nanoTime(), 36);+ createTable(name, true, "NEW_AND_OLD_IMAGES");+ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"eu-west-1\"}]}").then().statusCode(200);++ call("UpdateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicaUpdates\":[{\"Create\":{\"RegionName\":\"eu-west-1\"}}]}")+ .then().statusCode(400)+ .body("__type", is("ReplicaAlreadyExistsException"));++ // The home region is a replica of its own global table, so re-adding it clashes too.+ call("UpdateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicaUpdates\":[{\"Create\":{\"RegionName\":\"us-east-1\"}}]}")+ .then().statusCode(400)+ .body("__type", is("ReplicaAlreadyExistsException"));++ call("UpdateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicaUpdates\":[{\"Delete\":{\"RegionName\":\"ap-northeast-1\"}}]}")+ .then().statusCode(400)+ .body("__type", is("ReplicaNotFoundException"));++ // UpdateTable keeps its idempotent behaviour: the same re-add is accepted there, because+ // the model declares neither fault for it.+ call("UpdateTable", "{\"TableName\":\"" + name + "\","+ + "\"ReplicaUpdates\":[{\"Create\":{\"RegionName\":\"eu-west-1\"}}]}")+ .then().statusCode(200);+ }++ @Test+ void listFiltersByRegion() {+ String name = "gt-filter-" + Long.toString(System.nanoTime(), 36);+ createTable(name, true, "NEW_AND_OLD_IMAGES");+ call("CreateGlobalTable", "{\"GlobalTableName\":\"" + name + "\","+ + "\"ReplicationGroup\":[{\"RegionName\":\"sa-east-1\"}]}").then().statusCode(200);++ call("ListGlobalTables", "{\"RegionName\":\"sa-east-1\"}")+ .then().statusCode(200)+ .body("GlobalTables.GlobalTableName", hasItem(name));++ call("ListGlobalTables", "{\"RegionName\":\"me-south-1\"}")+ .then().statusCode(200)+ .body("GlobalTables.GlobalTableName", not(hasItem(name)));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.javaindex 293e901b8d..19f5476a54 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java@@ -3379,7 +3379,7 @@ given()@Testvoid unsupportedOperation() {given()- .header("X-Amz-Target", "DynamoDB_20120810.CreateGlobalTable")+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeGlobalTableSettings").contentType(DYNAMODB_CONTENT_TYPE).body("{}").when()