Skip to content

armgit / floci

Public Imported from GitHub
0

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

refactor(dynamodb): move table mutations behind the service (#4378)

Mario Toffia294f36881498
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.java
index 6615675a19..1022df9496 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
@@ -8,6 +8,12 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJsonController;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.CreateTableRequest;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.OnDemandThroughput;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.TableSettings;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.Throughput;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.UpdateTableRequest;
import io.github.hectorvent.floci.services.dynamodb.model.*;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import jakarta.enterprise.context.ApplicationScoped;
@@ -24,27 +30,30 @@ import java.util.function.Supplier;
@ApplicationScoped
public class DynamoDbJsonHandler {
- private static final String DEFAULT_ACCOUNT_ID = "000000000000";
private static final String SSE_TYPE_KMS = "KMS";
- private static final Set<String> VALID_SSE_TYPES = Set.of("AES256", "KMS");
private final DynamoDbService dynamoDbService;
- private final DynamoDbStreamService dynamoDbStreamService;
- private final KinesisService kinesisService;
+ private final NativeDynamoDbTableService tableService;
private final ObjectMapper objectMapper;
private final DynamoDbPartiQLHandler partiQLHandler;
private final Object importLock = new Object();
@Inject
- public DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService,
- KinesisService kinesisService, ObjectMapper objectMapper) {
+ public DynamoDbJsonHandler(DynamoDbService dynamoDbService, NativeDynamoDbTableService tableService,
+ ObjectMapper objectMapper) {
this.dynamoDbService = dynamoDbService;
- this.dynamoDbStreamService = dynamoDbStreamService;
- this.kinesisService = kinesisService;
+ this.tableService = tableService;
this.objectMapper = objectMapper;
this.partiQLHandler = new DynamoDbPartiQLHandler(dynamoDbService, objectMapper);
}
+ /** Package-private constructor for testing. */
+ DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService,
+ KinesisService kinesisService, ObjectMapper objectMapper) {
+ this(dynamoDbService, new NativeDynamoDbTableService(dynamoDbService, dynamoDbStreamService, kinesisService),
+ objectMapper);
+ }
+
public Response handle(String action, JsonNode request, String region) throws Exception {
return switch (action) {
case "CreateTable" -> handleCreateTable(request, region);
@@ -123,12 +132,11 @@ public class DynamoDbJsonHandler {
ad.path("AttributeName").asText(),
ad.path("AttributeType").asText())));
- Long readCapacity = null;
- Long writeCapacity = null;
JsonNode pt = request.path("ProvisionedThroughput");
+ Throughput throughput = null;
if (!pt.isMissingNode()) {
- readCapacity = pt.path("ReadCapacityUnits").asLong(5);
- writeCapacity = pt.path("WriteCapacityUnits").asLong(5);
+ throughput = new Throughput(
+ pt.path("ReadCapacityUnits").asLong(5), pt.path("WriteCapacityUnits").asLong(5));
}
List<GlobalSecondaryIndex> gsis = new ArrayList<>();
@@ -208,107 +216,56 @@ public class DynamoDbJsonHandler {
}
}
- String billingMode = request.has("BillingMode")
- ? request.get("BillingMode").asText() : null;
-
- boolean deletionProtection = request.path("DeletionProtectionEnabled").asBoolean(false);
-
- // Parsed and validated before createTable below: that call and the stream-enable that
- // follows it both have side effects, so an invalid SSEType must fail before either runs
- // rather than after, or ValidationException would leave a real table (and stream) behind.
- JsonNode sseSpec = request.path("SSESpecification");
- boolean sseEnabled = !sseSpec.isMissingNode() && sseSpec.path("Enabled").asBoolean(false);
- String sseType = sseEnabled ? sseSpec.path("SSEType").asText(SSE_TYPE_KMS) : null;
- if (sseEnabled) {
- validateSseType(sseType);
- }
-
- if ("PAY_PER_REQUEST".equals(billingMode) && !pt.isMissingNode()) {
- throw new AwsException("ValidationException",
- "One or more parameter values were invalid: Neither ReadCapacityUnits nor WriteCapacityUnits "
- + "can be specified when BillingMode is PAY_PER_REQUEST", 400);
- }
-
- JsonNode streamSpecCheck = request.path("StreamSpecification");
- if (streamSpecCheck.isObject() && !streamSpecCheck.path("StreamEnabled").asBoolean(false)
- && streamSpecCheck.hasNonNull("StreamViewType")) {
- throw new AwsException("ValidationException",
- "One or more parameter values were invalid: Table is being created with a stream "
- + "disabled, UpdateViewType should not be specified", 400);
- }
-
- TableDefinition table = dynamoDbService.createTable(tableName, keySchema, attrDefs,
- readCapacity, writeCapacity, gsis, lsis, vectorIndexes, billingMode, region);
- table.setTableStatus(initialStatus);
-
- table.setDeletionProtectionEnabled(deletionProtection);
-
- if ("PAY_PER_REQUEST".equals(billingMode)) {
- table.setBillingMode("PAY_PER_REQUEST");
- table.getProvisionedThroughput().setReadCapacityUnits(0L);
- table.getProvisionedThroughput().setWriteCapacityUnits(0L);
- } else {
- table.setBillingMode("PROVISIONED");
- }
-
- if (request.has("TableClass")) {
- table.setTableClass(request.get("TableClass").asText());
- }
-
- JsonNode onDemand = request.path("OnDemandThroughput");
- if (onDemand.isObject()) {
- if (onDemand.has("MaxReadRequestUnits")) {
- table.setOnDemandMaxReadRequestUnits(onDemand.get("MaxReadRequestUnits").asInt());
- }
- if (onDemand.has("MaxWriteRequestUnits")) {
- table.setOnDemandMaxWriteRequestUnits(onDemand.get("MaxWriteRequestUnits").asInt());
- }
- }
-
- // Store tags from CreateTable request
+ Map<String, String> tags = new LinkedHashMap<>();
JsonNode tagsNode = request.path("Tags");
if (tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
- table.getTags().put(tag.path("Key").asText(), tag.path("Value").asText());
+ tags.put(tag.path("Key").asText(), tag.path("Value").asText());
}
}
+ return tableService.createTable(new CreateTableRequest(tableName, keySchema, attrDefs,
+ throughput, gsis, lsis, vectorIndexes, tags, parseTableSettings(request)), initialStatus, region);
+ }
+
+ /**
+ * The table-level settings CreateTable and UpdateTable share. A member absent from the request
+ * is null; the service applies the per-operation defaults.
+ */
+ private static TableSettings parseTableSettings(JsonNode request) {
+ String billingMode = request.has("BillingMode") ? request.get("BillingMode").asText() : null;
+
+ JsonNode deletionProtectionNode = request.path("DeletionProtectionEnabled");
+ Boolean deletionProtection = deletionProtectionNode.isMissingNode()
+ ? null : deletionProtectionNode.asBoolean();
+
+ String tableClass = request.has("TableClass") ? request.get("TableClass").asText() : null;
+
JsonNode streamSpec = request.path("StreamSpecification");
- if (!streamSpec.isMissingNode() && streamSpec.path("StreamEnabled").asBoolean(false)) {
- String viewType = streamSpec.path("StreamViewType").asText("NEW_AND_OLD_IMAGES");
- StreamDescription sd = dynamoDbStreamService.enableStream(
- tableName, table.getTableArn(), viewType, region);
- table.setStreamEnabled(true);
- table.setStreamArn(sd.getStreamArn());
- table.setStreamViewType(viewType);
- }
-
- if (sseEnabled) {
- table.setSseEnabled(true);
- table.setSseType(sseType);
- if (SSE_TYPE_KMS.equals(sseType)) {
- JsonNode kmsMasterKeyId = sseSpec.path("KMSMasterKeyId");
- table.setKmsMasterKeyArn(!kmsMasterKeyId.isMissingNode() && !kmsMasterKeyId.isNull()
- ? kmsMasterKeyId.asText()
- : defaultKmsMasterKeyArn(region));
- }
- }
+ Boolean streamEnabled = streamSpec.isMissingNode()
+ ? null : streamSpec.path("StreamEnabled").asBoolean(false);
+ String streamViewType = streamSpec.hasNonNull("StreamViewType")
+ ? streamSpec.get("StreamViewType").asText() : null;
+
+ JsonNode sseSpec = request.path("SSESpecification");
+ Boolean sseEnabled = sseSpec.isMissingNode() ? null : sseSpec.path("Enabled").asBoolean(false);
+ String sseType = sseSpec.hasNonNull("SSEType") ? sseSpec.get("SSEType").asText() : null;
+ JsonNode kmsMasterKeyIdNode = sseSpec.path("KMSMasterKeyId");
+ String kmsMasterKeyId = kmsMasterKeyIdNode.isMissingNode() || kmsMasterKeyIdNode.isNull()
+ ? null : kmsMasterKeyIdNode.asText();
- // Everything above mutates the table AFTER createTable stored it, and a persistent
- // backend serializes on write rather than holding the live object. Flush once so the
- // stream, billing, class, tag and SSE settings survive a restart -- stream state
- // especially, since startup rebuilds streams from the persisted table.
- dynamoDbService.persistTable(tableName, table, region);
- return table;
+ return new TableSettings(billingMode, deletionProtection, tableClass,
+ parseOnDemandThroughput(request.path("OnDemandThroughput")),
+ streamEnabled, streamViewType, sseEnabled, sseType, kmsMasterKeyId);
}
- private void validateSseType(String sseType) {
- if (!VALID_SSE_TYPES.contains(sseType)) {
- throw new AwsException("ValidationException",
- "1 validation error detected: Value '" + sseType
- + "' at 'sSESpecification.sSEType' failed to satisfy constraint: "
- + "Member must satisfy enum value set: [AES256, KMS]", 400);
+ private static OnDemandThroughput parseOnDemandThroughput(JsonNode onDemand) {
+ if (!onDemand.isObject()) {
+ return null;
}
+ Integer maxRead = onDemand.has("MaxReadRequestUnits") ? onDemand.get("MaxReadRequestUnits").asInt() : null;
+ Integer maxWrite = onDemand.has("MaxWriteRequestUnits") ? onDemand.get("MaxWriteRequestUnits").asInt() : null;
+ return new OnDemandThroughput(maxRead, maxWrite);
}
// AWS reports an empty list as a length constraint on the 1-based member path, before the
@@ -1671,12 +1628,10 @@ public class DynamoDbJsonHandler {
}
}
}
- Long readCapacity = null;
- Long writeCapacity = null;
JsonNode pt = request.path("ProvisionedThroughput");
+ Throughput throughput = null;
if (!pt.isMissingNode()) {
- readCapacity = pt.has("ReadCapacityUnits") ? pt.get("ReadCapacityUnits").asLong() : null;
- writeCapacity = pt.has("WriteCapacityUnits") ? pt.get("WriteCapacityUnits").asLong() : null;
+ throughput = parseThroughput(pt);
}
String billingModeCheck = request.has("BillingMode") ? request.get("BillingMode").asText() : null;
@@ -1687,7 +1642,7 @@ public class DynamoDbJsonHandler {
List<GlobalSecondaryIndex> gsiCreates = new ArrayList<>();
List<String> gsiDeletes = new ArrayList<>();
- List<JsonNode> gsiUpdatesToApply = new ArrayList<>();
+ List<GsiThroughputUpdate> gsiThroughputUpdates = new ArrayList<>();
JsonNode gsiUpdates = request.path("GlobalSecondaryIndexUpdates");
if (!gsiUpdates.isMissingNode() && gsiUpdates.isArray()) {
var updatePosition = 0;
@@ -1735,15 +1690,19 @@ public class DynamoDbJsonHandler {
}
JsonNode updateNode = update.path("Update");
if (updateNode.isObject()) {
- gsiUpdatesToApply.add(updateNode);
+ JsonNode gsiPt = updateNode.path("ProvisionedThroughput");
+ gsiThroughputUpdates.add(new GsiThroughputUpdate(
+ updateNode.path("IndexName").asText(),
+ gsiPt.isObject() ? parseThroughput(gsiPt) : null,
+ parseOnDemandThroughput(updateNode.path("OnDemandThroughput"))));
}
}
}
- if (!gsiUpdatesToApply.isEmpty()) {
+ if (!gsiThroughputUpdates.isEmpty()) {
TableDefinition currentTable = dynamoDbService.describeTable(tableName, region);
- for (JsonNode updateNode : gsiUpdatesToApply) {
- String indexName = updateNode.path("IndexName").asText();
+ for (GsiThroughputUpdate gsiUpdate : gsiThroughputUpdates) {
+ String indexName = gsiUpdate.indexName();
if (gsiDeletes.contains(indexName)) {
throw new AwsException("ValidationException",
"Cannot delete and update the same index: " + indexName, 400);
@@ -1787,129 +1746,21 @@ public class DynamoDbJsonHandler {
}
}
- if (!addRegions.isEmpty() || !removeRegions.isEmpty() || !updateRegions.isEmpty()) {
- dynamoDbService.validateReplicaUpdates(
- tableName, addRegions, removeRegions, updateRegions, region);
- }
-
- // Parsed and validated up front, same as the replica check above: updateTable and the
- // mutations that follow it have side effects (persisted throughput/GSI changes, stream
- // enable/disable), so an invalid SSEType must fail before any of them run rather than
- // after, or ValidationException would leave a partially-applied update behind.
- JsonNode sseSpec = request.path("SSESpecification");
- boolean sseSpecified = !sseSpec.isMissingNode();
- boolean sseEnabled = sseSpecified && sseSpec.path("Enabled").asBoolean(false);
- String sseType = sseEnabled ? sseSpec.path("SSEType").asText(SSE_TYPE_KMS) : null;
- if (sseEnabled) {
- validateSseType(sseType);
- }
-
- TableDefinition table = dynamoDbService.updateTable(tableName, readCapacity, writeCapacity,
- gsiCreates, gsiDeletes, newAttrDefs, vectorCreates, vectorDeletes,
- billingModeCheck, region);
-
- for (JsonNode updateNode : gsiUpdatesToApply) {
- GlobalSecondaryIndex gsi = table.findGsi(updateNode.path("IndexName").asText()).orElseThrow();
- JsonNode gsiPt = updateNode.path("ProvisionedThroughput");
- if (gsiPt.isObject()) {
- if (gsiPt.has("ReadCapacityUnits")) {
- gsi.getProvisionedThroughput().setReadCapacityUnits(gsiPt.get("ReadCapacityUnits").asLong());
- }
- if (gsiPt.has("WriteCapacityUnits")) {
- gsi.getProvisionedThroughput().setWriteCapacityUnits(gsiPt.get("WriteCapacityUnits").asLong());
- }
- }
- JsonNode gsiOnDemand = updateNode.path("OnDemandThroughput");
- if (gsiOnDemand.isObject()) {
- if (gsiOnDemand.has("MaxReadRequestUnits")) {
- gsi.setOnDemandMaxReadRequestUnits(gsiOnDemand.get("MaxReadRequestUnits").asInt());
- }
- if (gsiOnDemand.has("MaxWriteRequestUnits")) {
- gsi.setOnDemandMaxWriteRequestUnits(gsiOnDemand.get("MaxWriteRequestUnits").asInt());
- }
- }
- }
+ TableDefinition table = tableService.updateTable(new UpdateTableRequest(tableName,
+ throughput, newAttrDefs, gsiCreates, gsiDeletes, gsiThroughputUpdates, vectorCreates, vectorDeletes,
+ addRegions, removeRegions, updateRegions, parseTableSettings(request)), region);
- JsonNode deletionProtectionNode = request.path("DeletionProtectionEnabled");
- if (!deletionProtectionNode.isMissingNode()) {
- table.setDeletionProtectionEnabled(deletionProtectionNode.asBoolean());
- }
-
- String billingMode = request.has("BillingMode")
- ? request.get("BillingMode").asText() : null;
- if (billingMode != null) {
- table.setBillingMode(billingMode);
- if ("PAY_PER_REQUEST".equals(billingMode)) {
- table.getProvisionedThroughput().setReadCapacityUnits(0L);
- table.getProvisionedThroughput().setWriteCapacityUnits(0L);
- }
- }
-
- if (request.has("TableClass")) {
- table.setTableClass(request.get("TableClass").asText());
- }
-
- JsonNode onDemand = request.path("OnDemandThroughput");
- if (onDemand.isObject()) {
- if (onDemand.has("MaxReadRequestUnits")) {
- table.setOnDemandMaxReadRequestUnits(onDemand.get("MaxReadRequestUnits").asInt());
- }
- if (onDemand.has("MaxWriteRequestUnits")) {
- table.setOnDemandMaxWriteRequestUnits(onDemand.get("MaxWriteRequestUnits").asInt());
- }
- }
-
- JsonNode streamSpec = request.path("StreamSpecification");
- if (!streamSpec.isMissingNode()) {
- boolean streamEnabled = streamSpec.path("StreamEnabled").asBoolean(false);
- if (streamEnabled) {
- String viewType = streamSpec.path("StreamViewType").asText("NEW_AND_OLD_IMAGES");
- StreamDescription sd = dynamoDbStreamService.enableStream(
- table.getTableName(), table.getTableArn(), viewType, region);
- table.setStreamEnabled(true);
- table.setStreamArn(sd.getStreamArn());
- table.setStreamViewType(viewType);
- } else {
- dynamoDbStreamService.disableStream(table.getTableName(), region);
- table.setStreamEnabled(false);
- }
- }
-
- if (sseSpecified) {
- if (sseEnabled) {
- table.setSseEnabled(true);
- table.setSseType(sseType);
- if (SSE_TYPE_KMS.equals(sseType)) {
- JsonNode kmsMasterKeyId = sseSpec.path("KMSMasterKeyId");
- table.setKmsMasterKeyArn(!kmsMasterKeyId.isMissingNode() && !kmsMasterKeyId.isNull()
- ? kmsMasterKeyId.asText()
- : defaultKmsMasterKeyArn(region));
- } else {
- table.setKmsMasterKeyArn(null);
- }
- } else {
- table.setSseEnabled(false);
- table.setSseType(null);
- table.setKmsMasterKeyArn(null);
- }
- }
-
- // Same flush as CreateTable: the stream and SSE mutations above land after updateTable's
- // write, so without this a retargeted view type or SSE change is rebuilt from the stale
- // persisted value on restart. Must run before applyReplicaUpdates below, which re-fetches
- // the table from storage for its own persist -- a persistent backend serializes on write
- // rather than holding the live object, so without this flush first, that re-fetch would
- // see neither the stream nor the SSE mutations above.
- dynamoDbService.persistTable(tableName, table, region);
-
- if (!addRegions.isEmpty() || !removeRegions.isEmpty() || !updateRegions.isEmpty()) {
- table = dynamoDbService.applyReplicaUpdates(tableName, addRegions, removeRegions, updateRegions, region);
- }
ObjectNode response = objectMapper.createObjectNode();
response.set("TableDescription", tableToNode(table));
return Response.ok(response).build();
}
+ private static Throughput parseThroughput(JsonNode pt) {
+ Long readCapacity = pt.has("ReadCapacityUnits") ? pt.get("ReadCapacityUnits").asLong() : null;
+ Long writeCapacity = pt.has("WriteCapacityUnits") ? pt.get("WriteCapacityUnits").asLong() : null;
+ return new Throughput(readCapacity, writeCapacity);
+ }
+
private static void validateReplicaRegion(String replicaRegion) {
if (replicaRegion == null || replicaRegion.isBlank()) {
throw new AwsException("ValidationException", "Replica RegionName must not be empty", 400);
@@ -2340,34 +2191,8 @@ public class DynamoDbJsonHandler {
400);
}
- TableDefinition table = dynamoDbService.describeTable(tableName, region);
- String resolvedTableName = table.getTableName();
-
- String streamName = streamArn.substring(streamArn.lastIndexOf('/') + 1);
- try {
- kinesisService.describeStream(streamName, region);
- } catch (AwsException e) {
- throw new AwsException("ResourceNotFoundException",
- "Kinesis stream not found: " + streamArn, 400);
- }
-
- Optional<KinesisStreamingDestination> existing = table.findKinesisStreamingDestination(streamArn);
- if (existing.isPresent() && "ACTIVE".equals(existing.get().getDestinationStatus())) {
- throw new AwsException("ValidationException",
- "Table already has an active Kinesis streaming destination with this stream ARN", 400);
- }
-
- if (existing.isPresent()) {
- existing.get().setDestinationStatus("ACTIVE");
- existing.get().setDestinationStatusDescription("Kinesis streaming is enabled for this table");
- existing.get().setApproximateCreationDateTimePrecision(precision);
- } else {
- table.getKinesisStreamingDestinations().add(new KinesisStreamingDestination(streamArn, precision));
- }
-
- // DynamoDB Streams is left as the caller configured it: Kinesis forwarding does not depend on it, and
- // turning it on here showed up as stream_enabled drift on aws_dynamodb_table that never converged.
- dynamoDbService.persistTable(resolvedTableName, table, region);
+ String resolvedTableName = tableService.enableKinesisStreamingDestination(
+ tableName, streamArn, precision, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("TableName", resolvedTableName);
@@ -2383,25 +2208,7 @@ public class DynamoDbJsonHandler {
String tableName = request.path("TableName").asText();
String streamArn = request.path("StreamArn").asText();
- TableDefinition table = dynamoDbService.describeTable(tableName, region);
- String resolvedTableName = table.getTableName();
-
- Optional<KinesisStreamingDestination> existing = table.findKinesisStreamingDestination(streamArn);
- if (existing.isEmpty()) {
- throw new AwsException("ResourceNotFoundException",
- "Kinesis streaming destination not found for stream: " + streamArn, 400);
- }
-
- if ("DISABLED".equals(existing.get().getDestinationStatus())) {
- throw new AwsException("ValidationException",
- "Kinesis streaming destination is already disabled for stream: " + streamArn, 400);
- }
-
- existing.get().setDestinationStatus("DISABLED");
- existing.get().setDestinationStatusDescription("Kinesis streaming is disabled for this table");
- dynamoDbService.persistTable(resolvedTableName, table, region);
- // Stop forwarding and discard buffered CDC records for this now-disabled destination.
- dynamoDbService.onKinesisStreamingDestinationDisabled(resolvedTableName, streamArn, region);
+ String resolvedTableName = tableService.disableKinesisStreamingDestination(tableName, streamArn, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("TableName", resolvedTableName);
@@ -2834,7 +2641,8 @@ public class DynamoDbJsonHandler {
if (SSE_TYPE_KMS.equals(sseType)) {
sseDescription.put("KMSMasterKeyArn", table.getKmsMasterKeyArn() != null
? table.getKmsMasterKeyArn()
- : defaultKmsMasterKeyArn(AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1")));
+ : NativeDynamoDbTableService.defaultKmsMasterKeyArn(
+ AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1")));
}
node.set("SSEDescription", sseDescription);
}
@@ -2996,11 +2804,6 @@ public class DynamoDbJsonHandler {
return vectorIndexNode;
}
- private String defaultKmsMasterKeyArn(String region) {
- return AwsArnUtils.Arn.of("kms", region, DEFAULT_ACCOUNT_ID,
- "key/aws-managed-dynamodb").toString();
- }
-
private ObjectNode continuousBackupsDescriptionNode(TableDefinition table) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ContinuousBackupsStatus", "ENABLED");
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
index 0b9cde59e0..7a89fee3f4 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
@@ -87,12 +87,12 @@ public class DynamoDbService implements ResourceProvider {
* View type applied when a stream is requested without an explicit StreamViewType.
*
* <p>Not an AWS default: the CloudFormation schema marks StreamViewType required inside
- * StreamSpecification, and the DynamoDB API documents no default either. This mirrors the
- * lenient handling {@code DynamoDbJsonHandler} already applies on CreateTable/UpdateTable
- * ({@code path("StreamViewType").asText("NEW_AND_OLD_IMAGES")}), so an under-specified
- * template gets a working stream instead of a rejection, and every entry point agrees.
+ * StreamSpecification, and the DynamoDB API documents no default either.
+ * {@link NativeDynamoDbTableService} applies the same fallback on CreateTable/UpdateTable, so
+ * an under-specified template gets a working stream instead of a rejection, and every entry
+ * point agrees.
*/
- private static final String DEFAULT_STREAM_VIEW_TYPE = "NEW_AND_OLD_IMAGES";
+ static final String DEFAULT_STREAM_VIEW_TYPE = "NEW_AND_OLD_IMAGES";
private final StorageBackend<String, TableDefinition> tableStore;
private final StorageBackend<String, Map<String, JsonNode>> itemStore;
@@ -757,11 +757,11 @@ public class DynamoDbService implements ResourceProvider {
* Turns on the table's stream and persists the result, so DescribeTable reports
* StreamSpecification / LatestStreamArn and event source mappings can find the stream.
*
- * <p>Callers that reach DynamoDB through the service rather than the JSON handler — notably
- * CloudFormation provisioning — need this: the handler enables the stream inline on
+ * <p>Callers that reach DynamoDB through this service directly, notably CloudFormation
+ * provisioning, need this: {@link NativeDynamoDbTableService} enables the stream inline on
* CreateTable/UpdateTable, and without an equivalent entry point a table created by any other
* path is left streamless. A null {@code viewType} falls back to
- * {@link #DEFAULT_STREAM_VIEW_TYPE}, matching the leniency the JSON handler already applies
+ * {@link #DEFAULT_STREAM_VIEW_TYPE}, matching the leniency CreateTable/UpdateTable already apply
* rather than any documented AWS default.
*
* @return the updated table, or the unchanged table when no stream service is wired.
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
new file mode 100644
index 0000000000..08f5b93340
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java
@@ -0,0 +1,387 @@
+package io.github.hectorvent.floci.services.dynamodb;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
+import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
+import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
+import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
+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.kinesis.KinesisService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+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.
+ *
+ * <p>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
+ * table afterwards, stream enable/disable, and the final flush. The JSON handler parses the wire
+ * request into these records and formats the response. It also keeps UpdateTable's
+ * PAY_PER_REQUEST with ProvisionedThroughput check and the GSI update index checks, which must
+ * precede request parsing errors, and the Kinesis precision check.
+ */
+@ApplicationScoped
+public class NativeDynamoDbTableService {
+
+ private static final String DEFAULT_ACCOUNT_ID = "000000000000";
+ private static final String SSE_TYPE_KMS = "KMS";
+ private static final Set<String> VALID_SSE_TYPES = Set.of("AES256", "KMS");
+
+ // A null field or throughput record means "not specified in the request". Collections and the
+ // settings record must not be null.
+ record Throughput(Long readCapacityUnits, Long writeCapacityUnits) {}
+
+ record OnDemandThroughput(Integer maxReadRequestUnits, Integer maxWriteRequestUnits) {}
+
+ record GsiThroughputUpdate(String indexName, Throughput provisionedThroughput,
+ OnDemandThroughput onDemandThroughput) {}
+
+ record TableSettings(String billingMode, Boolean deletionProtectionEnabled, String tableClass,
+ OnDemandThroughput onDemandThroughput,
+ Boolean streamEnabled, String streamViewType,
+ Boolean sseEnabled, String sseType, String kmsMasterKeyId) {}
+
+ record CreateTableRequest(String tableName, List<KeySchemaElement> keySchema,
+ List<AttributeDefinition> attributeDefinitions, Throughput provisionedThroughput,
+ List<GlobalSecondaryIndex> globalSecondaryIndexes,
+ List<LocalSecondaryIndex> localSecondaryIndexes,
+ List<DynamoDbService.VectorIndexCreate> vectorIndexes,
+ Map<String, String> tags, TableSettings settings) {}
+
+ record UpdateTableRequest(String tableName, Throughput provisionedThroughput,
+ List<AttributeDefinition> attributeDefinitions,
+ List<GlobalSecondaryIndex> gsiCreates, List<String> gsiDeletes,
+ List<GsiThroughputUpdate> gsiUpdates,
+ List<DynamoDbService.VectorIndexCreate> vectorCreates, List<String> vectorDeletes,
+ List<String> replicaAdds, List<String> replicaRemoves, List<String> replicaUpdates,
+ TableSettings settings) {}
+
+ private final DynamoDbService dynamoDbService;
+ private final DynamoDbStreamService streamService;
+ private final KinesisService kinesisService;
+
+ @Inject
+ public NativeDynamoDbTableService(DynamoDbService dynamoDbService, DynamoDbStreamService streamService,
+ KinesisService kinesisService) {
+ this.dynamoDbService = dynamoDbService;
+ this.streamService = streamService;
+ this.kinesisService = kinesisService;
+ }
+
+ /**
+ * Creates the table, applies the request's settings to it and persists the result.
+ *
+ * @param initialStatus the status the new table reports: ACTIVE for CreateTable, CREATING for
+ * a table an ImportTable job is still loading
+ */
+ TableDefinition createTable(CreateTableRequest request, String initialStatus, String region) {
+ String tableName = request.tableName();
+ TableSettings settings = request.settings();
+ String billingMode = settings.billingMode();
+
+ // Validated before createTable below: that call and the stream-enable that follows it
+ // both have side effects, so an invalid SSEType must fail before either runs rather than
+ // after, or ValidationException would leave a real table (and stream) behind.
+ boolean sseEnabled = Boolean.TRUE.equals(settings.sseEnabled());
+ String sseType = sseEnabled ? effectiveSseType(settings) : null;
+ if (sseEnabled) {
+ validateSseType(sseType);
+ }
+
+ Throughput throughput = request.provisionedThroughput();
+ if ("PAY_PER_REQUEST".equals(billingMode) && throughput != null) {
+ throw new AwsException("ValidationException",
+ "One or more parameter values were invalid: Neither ReadCapacityUnits nor WriteCapacityUnits "
+ + "can be specified when BillingMode is PAY_PER_REQUEST", 400);
+ }
+
+ if (Boolean.FALSE.equals(settings.streamEnabled()) && settings.streamViewType() != null) {
+ throw new AwsException("ValidationException",
+ "One or more parameter values were invalid: Table is being created with a stream "
+ + "disabled, UpdateViewType should not be specified", 400);
+ }
+
+ TableDefinition table = dynamoDbService.createTable(tableName, request.keySchema(),
+ request.attributeDefinitions(),
+ throughput != null ? throughput.readCapacityUnits() : null,
+ throughput != null ? throughput.writeCapacityUnits() : null,
+ request.globalSecondaryIndexes(), request.localSecondaryIndexes(), request.vectorIndexes(),
+ billingMode, region);
+ table.setTableStatus(initialStatus);
+
+ table.setDeletionProtectionEnabled(Boolean.TRUE.equals(settings.deletionProtectionEnabled()));
+
+ if ("PAY_PER_REQUEST".equals(billingMode)) {
+ table.setBillingMode("PAY_PER_REQUEST");
+ table.getProvisionedThroughput().setReadCapacityUnits(0L);
+ table.getProvisionedThroughput().setWriteCapacityUnits(0L);
+ } else {
+ table.setBillingMode("PROVISIONED");
+ }
+
+ if (settings.tableClass() != null) {
+ table.setTableClass(settings.tableClass());
+ }
+
+ applyOnDemandThroughput(table, settings.onDemandThroughput());
+
+ request.tags().forEach(table.getTags()::put);
+
+ if (Boolean.TRUE.equals(settings.streamEnabled())) {
+ enableStream(table, settings.streamViewType(), region);
+ }
+
+ if (sseEnabled) {
+ table.setSseEnabled(true);
+ table.setSseType(sseType);
+ if (SSE_TYPE_KMS.equals(sseType)) {
+ table.setKmsMasterKeyArn(kmsMasterKeyArn(settings.kmsMasterKeyId(), region));
+ }
+ }
+
+ // Everything above mutates the table AFTER createTable stored it, and a persistent
+ // backend serializes on write rather than holding the live object. Flush once so the
+ // stream, billing, class, tag and SSE settings survive a restart: stream state
+ // especially, since startup rebuilds streams from the persisted table.
+ dynamoDbService.persistTable(tableName, table, region);
+ return table;
+ }
+
+ /**
+ * Updates the table, applies the request's settings and replica changes to it and persists
+ * the result.
+ *
+ * <p>Wire-shape checks, the PAY_PER_REQUEST throughput check and the GSI update index checks
+ * stay with the caller, which runs them while it parses so their error precedence holds.
+ */
+ TableDefinition updateTable(UpdateTableRequest request, String region) {
+ String tableName = request.tableName();
+ TableSettings settings = request.settings();
+ List<String> addRegions = request.replicaAdds();
+ List<String> removeRegions = request.replicaRemoves();
+ List<String> updateRegions = request.replicaUpdates();
+ boolean replicaUpdates = !addRegions.isEmpty() || !removeRegions.isEmpty() || !updateRegions.isEmpty();
+
+ if (replicaUpdates) {
+ dynamoDbService.validateReplicaUpdates(
+ tableName, addRegions, removeRegions, updateRegions, region);
+ }
+
+ // Validated up front, same as the replica check above: updateTable and the mutations that
+ // follow it have side effects (persisted throughput/GSI changes, stream enable/disable),
+ // so an invalid SSEType must fail before any of them run rather than after, or
+ // ValidationException would leave a partially-applied update behind.
+ boolean sseEnabled = Boolean.TRUE.equals(settings.sseEnabled());
+ String sseType = sseEnabled ? effectiveSseType(settings) : null;
+ if (sseEnabled) {
+ validateSseType(sseType);
+ }
+
+ Throughput throughput = request.provisionedThroughput();
+ TableDefinition table = dynamoDbService.updateTable(tableName,
+ throughput != null ? throughput.readCapacityUnits() : null,
+ throughput != null ? throughput.writeCapacityUnits() : null,
+ request.gsiCreates(), request.gsiDeletes(), request.attributeDefinitions(),
+ request.vectorCreates(), request.vectorDeletes(),
+ settings.billingMode(), region);
+
+ for (GsiThroughputUpdate update : request.gsiUpdates()) {
+ GlobalSecondaryIndex gsi = table.findGsi(update.indexName()).orElseThrow();
+ Throughput gsiThroughput = update.provisionedThroughput();
+ if (gsiThroughput != null) {
+ if (gsiThroughput.readCapacityUnits() != null) {
+ gsi.getProvisionedThroughput().setReadCapacityUnits(gsiThroughput.readCapacityUnits());
+ }
+ if (gsiThroughput.writeCapacityUnits() != null) {
+ gsi.getProvisionedThroughput().setWriteCapacityUnits(gsiThroughput.writeCapacityUnits());
+ }
+ }
+ OnDemandThroughput gsiOnDemand = update.onDemandThroughput();
+ if (gsiOnDemand != null) {
+ if (gsiOnDemand.maxReadRequestUnits() != null) {
+ gsi.setOnDemandMaxReadRequestUnits(gsiOnDemand.maxReadRequestUnits());
+ }
+ if (gsiOnDemand.maxWriteRequestUnits() != null) {
+ gsi.setOnDemandMaxWriteRequestUnits(gsiOnDemand.maxWriteRequestUnits());
+ }
+ }
+ }
+
+ if (settings.deletionProtectionEnabled() != null) {
+ table.setDeletionProtectionEnabled(settings.deletionProtectionEnabled());
+ }
+
+ String billingMode = settings.billingMode();
+ if (billingMode != null) {
+ table.setBillingMode(billingMode);
+ if ("PAY_PER_REQUEST".equals(billingMode)) {
+ table.getProvisionedThroughput().setReadCapacityUnits(0L);
+ table.getProvisionedThroughput().setWriteCapacityUnits(0L);
+ }
+ }
+
+ if (settings.tableClass() != null) {
+ table.setTableClass(settings.tableClass());
+ }
+
+ applyOnDemandThroughput(table, settings.onDemandThroughput());
+
+ if (settings.streamEnabled() != null) {
+ if (settings.streamEnabled()) {
+ enableStream(table, settings.streamViewType(), region);
+ } else {
+ streamService.disableStream(table.getTableName(), region);
+ table.setStreamEnabled(false);
+ }
+ }
+
+ if (settings.sseEnabled() != null) {
+ if (sseEnabled) {
+ table.setSseEnabled(true);
+ table.setSseType(sseType);
+ if (SSE_TYPE_KMS.equals(sseType)) {
+ table.setKmsMasterKeyArn(kmsMasterKeyArn(settings.kmsMasterKeyId(), region));
+ } else {
+ table.setKmsMasterKeyArn(null);
+ }
+ } else {
+ table.setSseEnabled(false);
+ table.setSseType(null);
+ table.setKmsMasterKeyArn(null);
+ }
+ }
+
+ // Same flush as CreateTable: the stream and SSE mutations above land after updateTable's
+ // write, so without this a retargeted view type or SSE change is rebuilt from the stale
+ // persisted value on restart. Must run before applyReplicaUpdates below, which re-fetches
+ // the table from storage for its own persist. A persistent backend serializes on write
+ // rather than holding the live object, so without this flush first, that re-fetch would
+ // see neither the stream nor the SSE mutations above.
+ dynamoDbService.persistTable(tableName, table, region);
+
+ if (replicaUpdates) {
+ table = dynamoDbService.applyReplicaUpdates(tableName, addRegions, removeRegions, updateRegions, region);
+ }
+ return table;
+ }
+
+ /**
+ * Turns on forwarding to a Kinesis stream, reusing the table's destination for that stream
+ * when one exists.
+ *
+ * @param precision an already validated ApproximateCreationDateTimePrecision
+ * @return the resolved (canonical) table name
+ */
+ String enableKinesisStreamingDestination(String tableName, String streamArn, String precision, String region) {
+ TableDefinition table = dynamoDbService.describeTable(tableName, region);
+ String resolvedTableName = table.getTableName();
+
+ String streamName = streamArn.substring(streamArn.lastIndexOf('/') + 1);
+ try {
+ kinesisService.describeStream(streamName, region);
+ } catch (AwsException e) {
+ throw new AwsException("ResourceNotFoundException",
+ "Kinesis stream not found: " + streamArn, 400);
+ }
+
+ Optional<KinesisStreamingDestination> existing = table.findKinesisStreamingDestination(streamArn);
+ if (existing.isPresent() && "ACTIVE".equals(existing.get().getDestinationStatus())) {
+ throw new AwsException("ValidationException",
+ "Table already has an active Kinesis streaming destination with this stream ARN", 400);
+ }
+
+ if (existing.isPresent()) {
+ existing.get().setDestinationStatus("ACTIVE");
+ existing.get().setDestinationStatusDescription("Kinesis streaming is enabled for this table");
+ existing.get().setApproximateCreationDateTimePrecision(precision);
+ } else {
+ table.getKinesisStreamingDestinations().add(new KinesisStreamingDestination(streamArn, precision));
+ }
+
+ // DynamoDB Streams is left as the caller configured it: Kinesis forwarding does not depend on it, and
+ // turning it on here showed up as stream_enabled drift on aws_dynamodb_table that never converged.
+ dynamoDbService.persistTable(resolvedTableName, table, region);
+ return resolvedTableName;
+ }
+
+ /**
+ * Turns off forwarding to a Kinesis stream and stops the forwarder draining it.
+ *
+ * @return the resolved (canonical) table name
+ */
+ String disableKinesisStreamingDestination(String tableName, String streamArn, String region) {
+ TableDefinition table = dynamoDbService.describeTable(tableName, region);
+ String resolvedTableName = table.getTableName();
+
+ Optional<KinesisStreamingDestination> existing = table.findKinesisStreamingDestination(streamArn);
+ if (existing.isEmpty()) {
+ throw new AwsException("ResourceNotFoundException",
+ "Kinesis streaming destination not found for stream: " + streamArn, 400);
+ }
+
+ if ("DISABLED".equals(existing.get().getDestinationStatus())) {
+ throw new AwsException("ValidationException",
+ "Kinesis streaming destination is already disabled for stream: " + streamArn, 400);
+ }
+
+ existing.get().setDestinationStatus("DISABLED");
+ existing.get().setDestinationStatusDescription("Kinesis streaming is disabled for this table");
+ dynamoDbService.persistTable(resolvedTableName, table, region);
+ // Stop forwarding and discard buffered CDC records for this now-disabled destination.
+ dynamoDbService.onKinesisStreamingDestinationDisabled(resolvedTableName, streamArn, region);
+ return resolvedTableName;
+ }
+
+ /** The AWS managed key a table reports when SSE is KMS and no customer key was given. */
+ static String defaultKmsMasterKeyArn(String region) {
+ return AwsArnUtils.Arn.of("kms", region, DEFAULT_ACCOUNT_ID,
+ "key/aws-managed-dynamodb").toString();
+ }
+
+ private void enableStream(TableDefinition table, String streamViewType, String region) {
+ String viewType = streamViewType != null ? streamViewType : DynamoDbService.DEFAULT_STREAM_VIEW_TYPE;
+ StreamDescription sd = streamService.enableStream(table.getTableName(), table.getTableArn(), viewType, region);
+ table.setStreamEnabled(true);
+ table.setStreamArn(sd.getStreamArn());
+ table.setStreamViewType(viewType);
+ }
+
+ private static void applyOnDemandThroughput(TableDefinition table, OnDemandThroughput onDemand) {
+ if (onDemand == null) {
+ return;
+ }
+ if (onDemand.maxReadRequestUnits() != null) {
+ table.setOnDemandMaxReadRequestUnits(onDemand.maxReadRequestUnits());
+ }
+ if (onDemand.maxWriteRequestUnits() != null) {
+ table.setOnDemandMaxWriteRequestUnits(onDemand.maxWriteRequestUnits());
+ }
+ }
+
+ private static String kmsMasterKeyArn(String kmsMasterKeyId, String region) {
+ return kmsMasterKeyId != null ? kmsMasterKeyId : defaultKmsMasterKeyArn(region);
+ }
+
+ private static void validateSseType(String sseType) {
+ if (!VALID_SSE_TYPES.contains(sseType)) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value '" + sseType
+ + "' at 'sSESpecification.sSEType' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [AES256, KMS]", 400);
+ }
+ }
+
+ /** SSEType is optional when SSE is enabled; AWS then uses KMS. */
+ private static String effectiveSseType(TableSettings settings) {
+ return settings.sseType() != null ? settings.sseType() : SSE_TYPE_KMS;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java
new file mode 100644
index 0000000000..0870b5fd50
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java
@@ -0,0 +1,402 @@
+package io.github.hectorvent.floci.services.dynamodb;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.PersistentStorage;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.CreateTableRequest;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.OnDemandThroughput;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.TableSettings;
+import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.Throughput;
+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.GlobalSecondaryIndex;
+import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
+import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
+import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
+import io.github.hectorvent.floci.services.kinesis.KinesisService;
+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.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * Table control on the native engine: validation runs before any side effect, and every setting the
+ * service applies after the underlying create or update reaches disk, since a persistent backend
+ * serializes on write rather than holding the live table.
+ */
+class NativeDynamoDbTableServiceTest {
+
+ private static final String TABLE = "native-table";
+ private static final String GSI = "byCategory";
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+ private static final String STREAM_NAME = "orders";
+ private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:000000000000:stream/" + STREAM_NAME;
+ private static final TableSettings NO_SETTINGS =
+ new TableSettings(null, null, null, null, null, null, null, null, null);
+ private static final String BOGUS_SSE_TYPE_MESSAGE = "1 validation error detected: Value 'BOGUS' at "
+ + "'sSESpecification.sSEType' failed to satisfy constraint: Member must satisfy enum value set: "
+ + "[AES256, KMS]";
+
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @TempDir
+ Path tmp;
+
+ private Path file;
+ private DynamoDbStreamService streams;
+ private KinesisService kinesisService;
+ private KinesisStreamingForwarder forwarder;
+ private DynamoDbService dynamoDbService;
+ private NativeDynamoDbTableService tableService;
+
+ @BeforeEach
+ void setUp() {
+ file = tmp.resolve("tables.json");
+ StorageBackend<String, TableDefinition> store = diskStore(file);
+ streams = new DynamoDbStreamService(mapper, store);
+ kinesisService = mock(KinesisService.class);
+ forwarder = mock(KinesisStreamingForwarder.class);
+ dynamoDbService = new DynamoDbService(store, null, new RegionResolver(REGION, ACCOUNT), streams, forwarder);
+ tableService = new NativeDynamoDbTableService(dynamoDbService, streams, kinesisService);
+ }
+
+ private StorageBackend<String, TableDefinition> diskStore(Path path) {
+ PersistentStorage<String, TableDefinition> store =
+ new PersistentStorage<>(path, new TypeReference<Map<String, TableDefinition>>() { });
+ store.load();
+ return store;
+ }
+
+ /** What a restart would read back off disk. */
+ private TableDefinition reloadFromDisk() {
+ return diskStore(file).get(REGION + "::" + TABLE).orElseThrow();
+ }
+
+ private static TableSettings settings(String billingMode, Boolean streamEnabled, String streamViewType,
+ Boolean sseEnabled, String sseType) {
+ return new TableSettings(billingMode, null, null, null, streamEnabled, streamViewType,
+ sseEnabled, sseType, null);
+ }
+
+ private static CreateTableRequest createRequest(Throughput throughput, TableSettings settings) {
+ return new CreateTableRequest(TABLE,
+ new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))),
+ new ArrayList<>(List.of(new AttributeDefinition("id", "S"))),
+ throughput, List.of(), List.of(), List.of(), Map.of(), settings);
+ }
+
+ private static CreateTableRequest createRequestWithGsi(TableSettings settings) {
+ GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(GSI,
+ new ArrayList<>(List.of(new KeySchemaElement("category", "HASH"))), null, "ALL", new ArrayList<>());
+ gsi.getProvisionedThroughput().setReadCapacityUnits(5L);
+ gsi.getProvisionedThroughput().setWriteCapacityUnits(5L);
+ return new CreateTableRequest(TABLE,
+ new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))),
+ new ArrayList<>(List.of(new AttributeDefinition("id", "S"), new AttributeDefinition("category", "S"))),
+ new Throughput(5L, 5L), new ArrayList<>(List.of(gsi)), List.of(), List.of(), Map.of(), settings);
+ }
+
+ private static UpdateTableRequest updateRequest(List<GsiThroughputUpdate> gsiUpdates,
+ List<String> replicaUpdates, TableSettings settings) {
+ return new UpdateTableRequest(TABLE, null, List.of(), List.of(), List.of(), gsiUpdates,
+ List.of(), List.of(), List.of(), List.of(), replicaUpdates, settings);
+ }
+
+ private void assertValidationFailure(Executable call, String message) {
+ AwsException ex = assertThrows(AwsException.class, call);
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals(message, ex.getMessage());
+ }
+
+ private void assertNoTableAndNoStream() {
+ assertTrue(dynamoDbService.findTable(TABLE, REGION).isEmpty(), "no table may be left behind");
+ assertTrue(streams.listStreams(TABLE, REGION).isEmpty(), "no stream may be left behind");
+ }
+
+ @Test
+ void invalidSseTypeOnCreateLeavesNoTable() {
+ CreateTableRequest request = createRequest(null, settings(null, true, "NEW_IMAGE", true, "BOGUS"));
+
+ assertValidationFailure(() -> tableService.createTable(request, "ACTIVE", REGION), BOGUS_SSE_TYPE_MESSAGE);
+
+ assertNoTableAndNoStream();
+ }
+
+ @Test
+ void payPerRequestWithProvisionedThroughputOnCreateLeavesNoTable() {
+ CreateTableRequest request = createRequest(new Throughput(5L, 5L),
+ settings("PAY_PER_REQUEST", true, null, null, null));
+
+ assertValidationFailure(() -> tableService.createTable(request, "ACTIVE", REGION),
+ "One or more parameter values were invalid: Neither ReadCapacityUnits nor WriteCapacityUnits "
+ + "can be specified when BillingMode is PAY_PER_REQUEST");
+
+ assertNoTableAndNoStream();
+ }
+
+ @Test
+ void disabledStreamWithViewTypeOnCreateLeavesNoTable() {
+ CreateTableRequest request = createRequest(null, settings(null, false, "NEW_IMAGE", null, null));
+
+ assertValidationFailure(() -> tableService.createTable(request, "ACTIVE", REGION),
+ "One or more parameter values were invalid: Table is being created with a stream "
+ + "disabled, UpdateViewType should not be specified");
+
+ assertNoTableAndNoStream();
+ }
+
+ @Test
+ void createSettingsSurviveARestart() {
+ Map<String, String> tags = new LinkedHashMap<>();
+ tags.put("env", "test");
+ tags.put("team", "storage");
+ TableSettings settings = new TableSettings("PAY_PER_REQUEST", true, "STANDARD_INFREQUENT_ACCESS",
+ new OnDemandThroughput(100, 200), true, "NEW_IMAGE", true, "KMS", null);
+ CreateTableRequest request = new CreateTableRequest(TABLE,
+ new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))),
+ new ArrayList<>(List.of(new AttributeDefinition("id", "S"))),
+ null, List.of(), List.of(), List.of(), tags, settings);
+
+ TableDefinition created = tableService.createTable(request, "ACTIVE", REGION);
+
+ TableDefinition persisted = reloadFromDisk();
+ assertEquals("ACTIVE", persisted.getTableStatus());
+ assertEquals("PAY_PER_REQUEST", persisted.getBillingMode());
+ assertEquals(0L, persisted.getProvisionedThroughput().getReadCapacityUnits());
+ assertEquals(0L, persisted.getProvisionedThroughput().getWriteCapacityUnits());
+ assertTrue(persisted.isDeletionProtectionEnabled());
+ assertEquals("STANDARD_INFREQUENT_ACCESS", persisted.getTableClass());
+ assertEquals(100, persisted.getOnDemandMaxReadRequestUnits());
+ assertEquals(200, persisted.getOnDemandMaxWriteRequestUnits());
+ assertEquals(tags, persisted.getTags());
+ // Tags are applied one put at a time, so ListTagsOfResource and the stored JSON keep that iteration order.
+ Map<String, String> sequentiallyPut = new HashMap<>();
+ tags.forEach(sequentiallyPut::put);
+ assertEquals(new ArrayList<>(sequentiallyPut.keySet()), new ArrayList<>(created.getTags().keySet()));
+ assertEquals(new ArrayList<>(sequentiallyPut.keySet()), new ArrayList<>(persisted.getTags().keySet()));
+ assertTrue(persisted.isStreamEnabled());
+ assertEquals("NEW_IMAGE", persisted.getStreamViewType());
+ assertEquals(created.getStreamArn(), persisted.getStreamArn());
+ assertTrue(persisted.isSseEnabled());
+ assertEquals("KMS", persisted.getSseType());
+ assertEquals("arn:aws:kms:us-east-1:000000000000:key/aws-managed-dynamodb",
+ persisted.getKmsMasterKeyArn());
+
+ StreamDescription stream = new DynamoDbStreamService(mapper, diskStore(file))
+ .listStreams(TABLE, REGION).get(0);
+ assertEquals("NEW_IMAGE", stream.getStreamViewType(),
+ "a restarted stream must come back with the persisted view type");
+ }
+
+ @Test
+ void createDefaultsToProvisionedWithoutDeletionProtection() {
+ TableDefinition created = tableService.createTable(
+ createRequest(new Throughput(3L, 4L), NO_SETTINGS), "ACTIVE", REGION);
+
+ assertEquals("PROVISIONED", created.getBillingMode());
+ TableDefinition persisted = reloadFromDisk();
+ assertEquals("PROVISIONED", persisted.getBillingMode());
+ assertEquals(3L, persisted.getProvisionedThroughput().getReadCapacityUnits());
+ assertEquals(4L, persisted.getProvisionedThroughput().getWriteCapacityUnits());
+ assertFalse(persisted.isDeletionProtectionEnabled());
+ assertFalse(persisted.isStreamEnabled());
+ assertFalse(persisted.isSseEnabled());
+ }
+
+ @Test
+ void importTableRetainsItsCreationState() {
+ TableDefinition created = tableService.createTable(createRequest(null, NO_SETTINGS), "CREATING", REGION);
+
+ assertEquals("CREATING", created.getTableStatus());
+ assertEquals("CREATING", reloadFromDisk().getTableStatus());
+ }
+
+ @Test
+ void updateSettingsSurviveARestart() {
+ TableDefinition created = tableService.createTable(
+ createRequestWithGsi(settings(null, true, "NEW_AND_OLD_IMAGES", true, "KMS")), "ACTIVE", REGION);
+ TableSettings update = new TableSettings("PAY_PER_REQUEST", true, "STANDARD_INFREQUENT_ACCESS",
+ new OnDemandThroughput(100, 200), true, "NEW_IMAGE", false, null, null);
+ List<GsiThroughputUpdate> gsiUpdates = List.of(
+ new GsiThroughputUpdate(GSI, new Throughput(7L, null), new OnDemandThroughput(30, null)));
+
+ tableService.updateTable(updateRequest(gsiUpdates, List.of(), update), REGION);
+
+ TableDefinition persisted = reloadFromDisk();
+ assertEquals("PAY_PER_REQUEST", persisted.getBillingMode());
+ assertEquals(0L, persisted.getProvisionedThroughput().getReadCapacityUnits());
+ assertEquals(0L, persisted.getProvisionedThroughput().getWriteCapacityUnits());
+ assertTrue(persisted.isDeletionProtectionEnabled());
+ assertEquals("STANDARD_INFREQUENT_ACCESS", persisted.getTableClass());
+ assertEquals(100, persisted.getOnDemandMaxReadRequestUnits());
+ assertEquals(200, persisted.getOnDemandMaxWriteRequestUnits());
+
+ GlobalSecondaryIndex gsi = persisted.findGsi(GSI).orElseThrow();
+ assertEquals(7L, gsi.getProvisionedThroughput().getReadCapacityUnits());
+ assertEquals(5L, gsi.getProvisionedThroughput().getWriteCapacityUnits(),
+ "a member the update leaves out keeps its value");
+ assertEquals(30, gsi.getOnDemandMaxReadRequestUnits());
+ assertNull(gsi.getOnDemandMaxWriteRequestUnits());
+
+ assertTrue(persisted.isStreamEnabled());
+ assertEquals("NEW_IMAGE", persisted.getStreamViewType());
+ assertEquals(created.getStreamArn(), persisted.getStreamArn());
+
+ assertFalse(persisted.isSseEnabled());
+ assertNull(persisted.getSseType());
+ assertNull(persisted.getKmsMasterKeyArn());
+
+ StreamDescription stream = new DynamoDbStreamService(mapper, diskStore(file))
+ .listStreams(TABLE, REGION).get(0);
+ assertEquals("NEW_IMAGE", stream.getStreamViewType(),
+ "a restarted stream must not resume the old image shape");
+ }
+
+ @Test
+ void updateDisablingTheStreamSurvivesARestart() {
+ tableService.createTable(createRequest(null, settings(null, true, "KEYS_ONLY", null, null)),
+ "ACTIVE", REGION);
+
+ tableService.updateTable(updateRequest(List.of(), List.of(), settings(null, false, null, null, null)), REGION);
+
+ assertFalse(reloadFromDisk().isStreamEnabled());
+ assertEquals("DISABLED", streams.listStreams(TABLE, REGION).get(0).getStreamStatus());
+ }
+
+ @Test
+ void updateEnablingAes256SseClearsTheKmsKey() {
+ tableService.createTable(createRequest(null, settings(null, null, null, true, "KMS")), "ACTIVE", REGION);
+
+ tableService.updateTable(updateRequest(List.of(), List.of(), settings(null, null, null, true, "AES256")),
+ REGION);
+
+ TableDefinition persisted = reloadFromDisk();
+ assertTrue(persisted.isSseEnabled());
+ assertEquals("AES256", persisted.getSseType());
+ assertNull(persisted.getKmsMasterKeyArn());
+ }
+
+ @Test
+ void invalidSseTypeOnUpdateLeavesThePersistedTableUnchanged() {
+ tableService.createTable(createRequest(new Throughput(5L, 5L), NO_SETTINGS), "ACTIVE", REGION);
+ TableSettings update = new TableSettings("PAY_PER_REQUEST", true, "STANDARD_INFREQUENT_ACCESS",
+ null, true, "NEW_IMAGE", true, "BOGUS", null);
+
+ assertValidationFailure(() -> tableService.updateTable(updateRequest(List.of(), List.of(), update), REGION),
+ BOGUS_SSE_TYPE_MESSAGE);
+
+ assertUnchangedAfterRejectedUpdate();
+ }
+
+ @Test
+ void invalidReplicaUpdateLeavesThePersistedTableUnchanged() {
+ tableService.createTable(createRequest(new Throughput(5L, 5L), NO_SETTINGS), "ACTIVE", REGION);
+ TableSettings update = new TableSettings("PAY_PER_REQUEST", true, "STANDARD_INFREQUENT_ACCESS",
+ null, true, "NEW_IMAGE", null, null, null);
+
+ assertValidationFailure(() -> tableService.updateTable(
+ updateRequest(List.of(), List.of("eu-west-1"), update), REGION), "Replica eu-west-1 does not exist");
+
+ assertUnchangedAfterRejectedUpdate();
+ }
+
+ private void assertUnchangedAfterRejectedUpdate() {
+ TableDefinition persisted = reloadFromDisk();
+ assertEquals("PROVISIONED", persisted.getBillingMode());
+ assertEquals(5L, persisted.getProvisionedThroughput().getReadCapacityUnits());
+ assertFalse(persisted.isDeletionProtectionEnabled());
+ assertNull(persisted.getTableClass());
+ assertFalse(persisted.isStreamEnabled());
+ assertTrue(streams.listStreams(TABLE, REGION).isEmpty(), "the rejected update must not enable a stream");
+ }
+
+ @Test
+ void kinesisDestinationTransitionsPersistAndRepeatedTransitionsAreRejected() {
+ TableDefinition created = tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
+
+ String resolved = tableService.enableKinesisStreamingDestination(
+ created.getTableArn(), STREAM_ARN, KinesisStreamingDestination.PRECISION_MICROSECOND, REGION);
+
+ assertEquals(TABLE, resolved, "an ARN input resolves to the canonical table name");
+ verify(kinesisService).describeStream(STREAM_NAME, REGION);
+ KinesisStreamingDestination enabled = reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN)
+ .orElseThrow();
+ assertEquals("ACTIVE", enabled.getDestinationStatus());
+ assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND,
+ enabled.getApproximateCreationDateTimePrecision());
+
+ assertValidationFailure(() -> tableService.enableKinesisStreamingDestination(
+ TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MILLISECOND, REGION),
+ "Table already has an active Kinesis streaming destination with this stream ARN");
+
+ assertEquals(TABLE, tableService.disableKinesisStreamingDestination(TABLE, STREAM_ARN, REGION));
+ TableDefinition disabled = reloadFromDisk();
+ assertEquals(1, disabled.getKinesisStreamingDestinations().size());
+ assertEquals("DISABLED", disabled.findKinesisStreamingDestination(STREAM_ARN).orElseThrow()
+ .getDestinationStatus());
+ verify(forwarder).onDestinationDisabled(ACCOUNT, REGION, TABLE, STREAM_ARN);
+
+ assertValidationFailure(() -> tableService.disableKinesisStreamingDestination(TABLE, STREAM_ARN, REGION),
+ "Kinesis streaming destination is already disabled for stream: " + STREAM_ARN);
+
+ tableService.enableKinesisStreamingDestination(
+ TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MILLISECOND, REGION);
+ KinesisStreamingDestination reenabled = reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN)
+ .orElseThrow();
+ assertEquals("ACTIVE", reenabled.getDestinationStatus());
+ assertEquals(KinesisStreamingDestination.PRECISION_MILLISECOND,
+ reenabled.getApproximateCreationDateTimePrecision());
+ assertEquals(1, reloadFromDisk().getKinesisStreamingDestinations().size(),
+ "re-enabling reuses the existing destination");
+ }
+
+ @Test
+ void unknownKinesisStreamIsReportedAsNotFound() {
+ tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
+ String missingArn = "arn:aws:kinesis:us-east-1:000000000000:stream/missing";
+ when(kinesisService.describeStream("missing", REGION))
+ .thenThrow(new AwsException("ResourceNotFoundException", "Stream missing not found", 400));
+
+ AwsException ex = assertThrows(AwsException.class, () -> tableService.enableKinesisStreamingDestination(
+ TABLE, missingArn, KinesisStreamingDestination.PRECISION_MILLISECOND, REGION));
+
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ assertEquals("Kinesis stream not found: " + missingArn, ex.getMessage());
+ assertTrue(reloadFromDisk().getKinesisStreamingDestinations().isEmpty());
+ }
+
+ @Test
+ void disablingAnUnknownDestinationIsReportedAsNotFound() {
+ tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> tableService.disableKinesisStreamingDestination(TABLE, STREAM_ARN, REGION));
+
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ assertEquals("Kinesis streaming destination not found for stream: " + STREAM_ARN, ex.getMessage());
+ verifyNoInteractions(forwarder);
+ }
+}