diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 4cbb30f5c6..0cb06bffac 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -64,6 +64,7 @@ operations keep their existing resource builders, including batch, transaction a | `RestoreTableFromBackup` | Create a new table from a backup | | `DescribeKinesisStreamingDestination` | List Kinesis streaming destinations | | `EnableKinesisStreamingDestination` | Enable Kinesis streaming for a table | +| `UpdateKinesisStreamingDestination` | Update timestamp precision on an active Kinesis destination | | `DisableKinesisStreamingDestination` | Disable Kinesis streaming for a table | | `ExportTableToPointInTime` | Export table data, or the changes of a period, to S3 | | `CreateGlobalTable` | Make an existing table a global table (2017.11.29) | @@ -634,12 +635,20 @@ record as `dynamodb.ApproximateCreationDateTimePrecision`, and reported by `DescribeKinesisStreamingDestination` as well as in the `EnableKinesisStreamingConfiguration` member of the `EnableKinesisStreamingDestination` and `DisableKinesisStreamingDestination` responses. +On the native backend, `UpdateKinesisStreamingDestination` changes an active destination's precision without stopping +forwarding. Its response carries `UpdateKinesisStreamingConfiguration`, and subsequent item changes +use the updated precision. Omitting the configuration or its precision retains the current value. +The update accepts a table name or table ARN, persists across restarts, and rejects missing tables, +missing destinations, inactive destinations, and precision values other than `MILLISECOND` or +`MICROSECOND`. + Enabling a Kinesis streaming destination does not change the table's DynamoDB Streams setting. Kinesis forwarding works whether or not `StreamSpecification.StreamEnabled` is set. Both calls take effect at once, so `EnableKinesisStreamingDestination` answers `ACTIVE` and `DisableKinesisStreamingDestination` answers `DISABLED`. AWS reports the transitional `ENABLING` and `DISABLING` first, because it enables and disables the destination in the background. +Updates also apply at once and answer `ACTIVE`; AWS can report `UPDATING` while applying a change. ### Delivery contract diff --git a/docs/services/index.md b/docs/services/index.md index baff8f0f37..a0b9fcbef1 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -16,7 +16,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [S3](s3.md) | `/{bucket}/{key}` | REST XML | 58 | | [S3 Vectors](s3vectors.md) | `POST /{OperationName}` | REST JSON | 16 | | [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*` | REST JSON | 27 | -| [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 53 | +| [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 54 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | | [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 69 | | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 23 | diff --git a/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java b/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java index 31eda009e0..407c6ffcf8 100644 --- a/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java +++ b/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java @@ -11,6 +11,7 @@ import com.fasterxml.jackson.dataformat.cbor.CBORGenerator; import com.google.gson.JsonParseException; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler; import io.floci.aws.services.dynamodb.DynamoDbJsonHandler; +import io.floci.aws.services.dynamodb.DynamoDbRequestShapes; import io.floci.aws.services.dynamodb.DynamoDbStreamsJsonHandler; import io.floci.aws.services.eventbridgev2.EventBridgeV2Handler; import io.floci.aws.services.kinesis.KinesisJsonHandler; @@ -446,6 +447,7 @@ public class AwsJsonCborController { if (targetMatch.prefix().startsWith("DynamoDBStreams_")) { yield dynamoDbStreamsJsonHandler.handle(action, request, region); } + DynamoDbRequestShapes.check(action, request); yield dynamoDbJsonHandler.handle(action, request, region); } case "sqs" -> sqsJsonHandler.handle(action, request, region); @@ -518,6 +520,7 @@ public class AwsJsonCborController { if ("DynamoDB Streams".equals(serviceId) || serviceId.startsWith("DynamoDBStreams")) { yield dynamoDbStreamsJsonHandler.handle(operation, request, region); } + DynamoDbRequestShapes.check(operation, request); yield dynamoDbJsonHandler.handle(operation, request, region); } case "sqs" -> sqsJsonHandler.handle(operation, request, region); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java index a00597ef57..934a1fbc7c 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -18,6 +18,7 @@ import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.core.common.StripedLocks; import io.floci.aws.core.common.Totp; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -121,6 +122,7 @@ public class DynamoDbService { static final String DEFAULT_STREAM_VIEW_TYPE = "NEW_AND_OLD_IMAGES"; private final StorageBackend tableStore; + private final StripedLocks tableControlLocks = new StripedLocks(256); private final StorageBackend> itemStore; private final StorageBackend exportStore; private final StorageBackend importStore; @@ -1019,7 +1021,19 @@ public class DynamoDbService { return table; } + /** Serializes Kinesis destination mutations with deletion for the same account, Region and table. */ + Object tableControlLock(String tableName, String region) { + String storageKey = regionKey(region, canonicalTableName(region, tableName)); + return tableControlLocks.lockFor(scopedItemsKey(storageKey)); + } + public void deleteTable(String tableName, String region) { + synchronized (tableControlLock(tableName, region)) { + deleteTableLocked(tableName, region); + } + } + + private void deleteTableLocked(String tableName, String region) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); TableDefinition table = tableStore.get(storageKey) @@ -5230,7 +5244,7 @@ public class DynamoDbService { return results; } - private AwsException resourceNotFoundException(String tableName) { + static AwsException resourceNotFoundException(String tableName) { return new AwsException("ResourceNotFoundException", "Requested resource not found: Table: " + tableName + " not found", 400); } diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java index 91351a1203..d4d2003a32 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -149,6 +149,7 @@ public class NativeDynamoDbJsonHandler { case "GetResourcePolicy" -> handleGetResourcePolicy(request, region); case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region); case "EnableKinesisStreamingDestination" -> handleEnableKinesisStreamingDestination(request, region); + case "UpdateKinesisStreamingDestination" -> handleUpdateKinesisStreamingDestination(request, region); case "DisableKinesisStreamingDestination" -> handleDisableKinesisStreamingDestination(request, region); case "DescribeKinesisStreamingDestination" -> handleDescribeKinesisStreamingDestination(request, region); case "ExportTableToPointInTime" -> handleExportTable(request, region); @@ -3515,13 +3516,8 @@ public class NativeDynamoDbJsonHandler { .path("ApproximateCreationDateTimePrecision"); String precision = precisionNode.isMissingNode() || precisionNode.isNull() ? KinesisStreamingDestination.PRECISION_MILLISECOND : precisionNode.asText(); - if (!KinesisStreamingDestination.PRECISION_MILLISECOND.equals(precision) - && !KinesisStreamingDestination.PRECISION_MICROSECOND.equals(precision)) { - throw SmithyValidationErrors.validationException( - "Value '" + precision - + "' at 'enableKinesisStreamingConfiguration.approximateCreationDateTimePrecision' " - + "failed to satisfy constraint: Member must satisfy enum value set: [MILLISECOND, MICROSECOND]"); - } + validateKinesisPrecision(precision, + "enableKinesisStreamingConfiguration.approximateCreationDateTimePrecision"); return Response.ok(kinesisDestinationResponse( tableService.enableKinesisStreamingDestination(tableName, streamArn, precision, region))).build(); @@ -3535,6 +3531,51 @@ public class NativeDynamoDbJsonHandler { tableService.disableKinesisStreamingDestination(tableName, streamArn, region))).build(); } + private Response handleUpdateKinesisStreamingDestination(JsonNode request, String region) { + String tableName = kinesisUpdateString(request, "TableName", "tableName", 1); + String streamArn = kinesisUpdateString(request, "StreamArn", "streamArn", 37); + String precision = kinesisUpdatePrecision(request); + KinesisDestination result = tableService.updateKinesisStreamingDestination( + tableName, streamArn, precision, region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("TableName", result.tableName()); + response.put("StreamArn", result.streamArn()); + response.put("DestinationStatus", result.destinationStatus()); + response.putObject("UpdateKinesisStreamingConfiguration") + .put("ApproximateCreationDateTimePrecision", result.approximateCreationDateTimePrecision()); + return Response.ok(response).build(); + } + + private static String kinesisUpdatePrecision(JsonNode request) { + JsonNode precisionNode = request.path("UpdateKinesisStreamingConfiguration") + .path("ApproximateCreationDateTimePrecision"); + String precision = precisionNode.isMissingNode() || precisionNode.isNull() ? null : precisionNode.asText(); + validateKinesisPrecision(precision, + "updateKinesisStreamingConfiguration.approximateCreationDateTimePrecision"); + return precision; + } + + private static void validateKinesisPrecision(String precision, String member) { + if (precision != null && !KinesisStreamingDestination.PRECISION_MILLISECOND.equals(precision) + && !KinesisStreamingDestination.PRECISION_MICROSECOND.equals(precision)) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notInEnum(precision, member, + List.of(KinesisStreamingDestination.PRECISION_MILLISECOND, + KinesisStreamingDestination.PRECISION_MICROSECOND))); + } + } + + private static String kinesisUpdateString(JsonNode request, String member, String path, int minimumLength) { + JsonNode value = request.path(member); + if (value.isMissingNode() || value.isNull()) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull(path)); + } + String violation = SmithyValidationErrors.lengthOutOfRange(path, value.asText(), minimumLength, 1024); + if (violation != null) { + throw SmithyValidationErrors.validationException(violation); + } + return value.asText(); + } + /** * The shape Enable and Disable both answer with: TableName, StreamArn, DestinationStatus and * EnableKinesisStreamingConfiguration. DestinationStatusDescription belongs to Describe only. diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java index 6caba57b8d..1cb7e2c063 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java @@ -539,6 +539,13 @@ public class NativeDynamoDbTableService { */ public KinesisDestination enableKinesisStreamingDestination(String tableName, String streamArn, String precision, String region) { + synchronized (dynamoDbService.tableControlLock(tableName, region)) { + return enableKinesisStreamingDestinationLocked(tableName, streamArn, precision, region); + } + } + + private KinesisDestination enableKinesisStreamingDestinationLocked(String tableName, String streamArn, + String precision, String region) { TableDefinition table = dynamoDbService.describeTable(tableName, region); String resolvedTableName = table.getTableName(); @@ -558,9 +565,6 @@ public class NativeDynamoDbTableService { KinesisStreamingDestination destination; if (existing.isPresent()) { destination = existing.get(); - // The precision goes in before the status. A concurrent Disable gets past its - // already-disabled check only once the status reads ACTIVE, so writing the status last - // means that call can no longer read the precision this one is replacing. destination.setApproximateCreationDateTimePrecision(precision); destination.setDestinationStatusDescription("Kinesis streaming is enabled for this table"); destination.setDestinationStatus("ACTIVE"); @@ -582,6 +586,12 @@ public class NativeDynamoDbTableService { * @return a snapshot of what this call left on the destination, with the canonical table name */ public KinesisDestination disableKinesisStreamingDestination(String tableName, String streamArn, String region) { + synchronized (dynamoDbService.tableControlLock(tableName, region)) { + return disableKinesisStreamingDestinationLocked(tableName, streamArn, region); + } + } + + private KinesisDestination disableKinesisStreamingDestinationLocked(String tableName, String streamArn, String region) { TableDefinition table = dynamoDbService.describeTable(tableName, region); String resolvedTableName = table.getTableName(); @@ -613,12 +623,22 @@ public class NativeDynamoDbTableService { * does. Forwarding never stops: records already captured are still delivered, and the forwarder * stamps each later write with the new precision. * - * @param precision an already validated ApproximateCreationDateTimePrecision + * @param precision an already validated ApproximateCreationDateTimePrecision, or null to retain it * @return a snapshot of what this call left on the destination, with the canonical table name */ public KinesisDestination updateKinesisStreamingDestination(String tableName, String streamArn, String precision, String region) { + synchronized (dynamoDbService.tableControlLock(tableName, region)) { + return updateKinesisStreamingDestinationLocked(tableName, streamArn, precision, region); + } + } + + private KinesisDestination updateKinesisStreamingDestinationLocked(String tableName, String streamArn, + String precision, String region) { TableDefinition table = dynamoDbService.describeTable(tableName, region); + if (AwsArnUtils.looksLikeArn(tableName) && !tableName.equals(table.getTableArn())) { + throw DynamoDbService.resourceNotFoundException(table.getTableName()); + } String resolvedTableName = table.getTableName(); Optional existing = table.findKinesisStreamingDestination(streamArn); @@ -631,8 +651,10 @@ public class NativeDynamoDbTableService { "Kinesis streaming destination is not active for stream: " + streamArn, 400); } - existing.get().setApproximateCreationDateTimePrecision(precision); - KinesisDestination updated = new KinesisDestination(resolvedTableName, streamArn, "ACTIVE", precision); + KinesisStreamingDestination destination = existing.get(); + String effectivePrecision = precision != null ? precision : destination.getApproximateCreationDateTimePrecision(); + destination.setApproximateCreationDateTimePrecision(effectivePrecision); + KinesisDestination updated = new KinesisDestination(resolvedTableName, streamArn, "ACTIVE", effectivePrecision); dynamoDbService.persistTable(resolvedTableName, table, region); return updated; } diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIamIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIamIntegrationTest.java new file mode 100644 index 0000000000..cfa87ee6f6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIamIntegrationTest.java @@ -0,0 +1,83 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.kinesis.KinesisClient; + +import java.util.UUID; + +import static io.floci.aws.testing.DynamoDbTableFixtures.createKeyedTable; +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class DynamoDbKinesisUpdateIamIntegrationTest { + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void permissionIsForTheUpdateActionAndRequestedTable() { + String account = "000000000000"; + String allowed = "kinesis-update-iam-" + UUID.randomUUID(); + String denied = allowed + "-denied"; + DynamoDbClient root = AwsTestClients.create(DynamoDbClient.builder(), account, Region.US_EAST_1); + cleanup.register(root::close); + KinesisClient kinesis = AwsTestClients.create(KinesisClient.builder(), account, Region.US_EAST_1); + cleanup.register(kinesis::close); + kinesis.createStream(b -> b.streamName(allowed).shardCount(1)); + cleanup.register(() -> kinesis.deleteStream(b -> b.streamName(allowed))); + String streamArn = kinesis.describeStreamSummary(b -> b.streamName(allowed)) + .streamDescriptionSummary().streamARN(); + String allowedArn = createKeyedTable(root, allowed); + cleanup.register(() -> root.deleteTable(b -> b.tableName(allowed))); + String deniedArn = createKeyedTable(root, denied); + cleanup.register(() -> root.deleteTable(b -> b.tableName(denied))); + root.enableKinesisStreamingDestination(b -> b.tableName(allowed).streamArn(streamArn)); + root.enableKinesisStreamingDestination(b -> b.tableName(denied).streamArn(streamArn)); + String name = "kinesis-updater-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(account, "iam"), name); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(account, "iam"), name, "update-one", """ + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "dynamodb:UpdateKinesisStreamingDestination", + "Resource": "%s" + } + ] + } + """.formatted(allowedArn)); + try (DynamoDbClient user = AwsTestClients.create(DynamoDbClient.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1)) { + assertEquals("MICROSECOND", user.updateKinesisStreamingDestination( + b -> b.tableName(allowedArn).streamArn(streamArn) + .updateKinesisStreamingConfiguration(c -> c + .approximateCreationDateTimePrecision("MICROSECOND"))) + .updateKinesisStreamingConfiguration().approximateCreationDateTimePrecisionAsString()); + DynamoDbException error = assertThrows(DynamoDbException.class, + () -> user.updateKinesisStreamingDestination(b -> b.tableName(deniedArn).streamArn(streamArn))); + assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode()); + DynamoDbException wrongAction = assertThrows(DynamoDbException.class, + () -> user.disableKinesisStreamingDestination(b -> b.tableName(allowed).streamArn(streamArn))); + assertEquals("AccessDeniedException", wrongAction.awsErrorDetails().errorCode()); + } + assertEquals("MILLISECOND", root.describeKinesisStreamingDestination(b -> b.tableName(denied)) + .kinesisDataStreamDestinations().getFirst().approximateCreationDateTimePrecisionAsString()); + assertEquals("ACTIVE", root.describeKinesisStreamingDestination(b -> b.tableName(allowed)) + .kinesisDataStreamDestinations().getFirst().destinationStatusAsString()); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIntegrationTest.java new file mode 100644 index 0000000000..fb932e04b5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateIntegrationTest.java @@ -0,0 +1,272 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.dynamodb.model.UpdateKinesisStreamingDestinationResponse; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.Record; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.testing.DynamoDbTableFixtures.createKeyedTable; +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +class DynamoDbKinesisUpdateIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + private static final String TARGET = "DynamoDB_20120810.UpdateKinesisStreamingDestination"; + private final ObjectMapper mapper = new ObjectMapper(); + + @Inject + KinesisStreamingForwarder forwarder; + + private DynamoDbClient dynamoDb; + private KinesisClient kinesis; + private String table; + private String tableArn; + private String streamArn; + + @BeforeEach + void createDestination() { + dynamoDb = AwsTestClients.create(DynamoDbClient.builder(), ACCOUNT, Region.US_EAST_1); + kinesis = AwsTestClients.create(KinesisClient.builder(), ACCOUNT, Region.US_EAST_1); + table = "kinesis-update-" + UUID.randomUUID(); + kinesis.createStream(b -> b.streamName(table).shardCount(1)); + streamArn = kinesis.describeStreamSummary(b -> b.streamName(table)).streamDescriptionSummary().streamARN(); + tableArn = createKeyedTable(dynamoDb, table); + dynamoDb.enableKinesisStreamingDestination(b -> b.tableName(table).streamArn(streamArn)); + } + + @AfterEach + void cleanUp() { + try (DynamoDbClient dynamoDbClient = dynamoDb; KinesisClient kinesisClient = kinesis) { + try { + dynamoDbClient.deleteTable(b -> b.tableName(table)); + } finally { + kinesisClient.deleteStream(b -> b.streamName(table)); + } + } + } + + @Test + void sdkUpdateChangesDeliveredRecordPrecisionAndPreservesTheDestination() throws Exception { + WriteWindow before = put("before"); + UpdateKinesisStreamingDestinationResponse updated = update(tableArn, "MICROSECOND"); + assertEquals(table, updated.tableName()); + assertEquals(streamArn, updated.streamArn()); + assertEquals("ACTIVE", updated.destinationStatusAsString()); + assertEquals("MICROSECOND", + updated.updateKinesisStreamingConfiguration().approximateCreationDateTimePrecisionAsString()); + WriteWindow after = put("after"); + assertPrecision("MICROSECOND"); + update(table, "MILLISECOND"); + WriteWindow restored = put("restored"); + assertPrecision("MILLISECOND"); + + List changes = changes(); + assertEquals(List.of("before", "after", "restored"), + changes.stream().map(n -> n.path("Keys").path("pk").path("S").asText()).toList()); + List writes = List.of(before, after, restored); + for (int index = 0; index < changes.size(); index++) { + boolean microsecond = index == 1; + JsonNode change = changes.get(index); + assertEquals(microsecond ? "MICROSECOND" : "MILLISECOND", + change.path("ApproximateCreationDateTimePrecision").asText()); + ChronoUnit unit = microsecond ? ChronoUnit.MICROS : ChronoUnit.MILLIS; + long timestamp = change.path("ApproximateCreationDateTime").asLong(); + WriteWindow write = writes.get(index); + assertTrue(timestamp >= unit.between(Instant.EPOCH, write.started()) + && timestamp <= unit.between(Instant.EPOCH, write.finished()), change.toString()); + } + } + + @Test + void omittedAndEmptyConfigurationRetainTheCurrentPrecision() { + update(table, "MICROSECOND"); + UpdateKinesisStreamingDestinationResponse omitted = dynamoDb.updateKinesisStreamingDestination( + b -> b.tableName(table).streamArn(streamArn)); + assertEquals("MICROSECOND", + omitted.updateKinesisStreamingConfiguration().approximateCreationDateTimePrecisionAsString()); + UpdateKinesisStreamingDestinationResponse empty = dynamoDb.updateKinesisStreamingDestination( + b -> b.tableName(table).streamArn(streamArn).updateKinesisStreamingConfiguration(c -> { })); + assertEquals("MICROSECOND", + empty.updateKinesisStreamingConfiguration().approximateCreationDateTimePrecisionAsString()); + assertPrecision("MICROSECOND"); + } + + @Test + void invalidPrecisionMissingResourcesAndDisabledDestinationLeaveStateIntact() { + DynamoDbException invalidUpdate = assertError("ValidationException", () -> update(table, "SECOND")); + DynamoDbException invalidEnable = assertError("ValidationException", + () -> dynamoDb.enableKinesisStreamingDestination(b -> b.tableName(table).streamArn(streamArn) + .enableKinesisStreamingConfiguration(c -> c.approximateCreationDateTimePrecision("SECOND")))); + String enumConstraint = "Value 'SECOND' at '%s.approximateCreationDateTimePrecision' " + + "failed to satisfy constraint: Member must satisfy enum value set: [MILLISECOND, MICROSECOND]"; + assertTrue(invalidUpdate.awsErrorDetails().errorMessage().endsWith( + enumConstraint.formatted("updateKinesisStreamingConfiguration"))); + assertTrue(invalidEnable.awsErrorDetails().errorMessage().endsWith( + enumConstraint.formatted("enableKinesisStreamingConfiguration"))); + assertPrecision("MILLISECOND"); + assertError("ResourceNotFoundException", () -> update(table + "-missing", "MICROSECOND")); + assertError("ResourceNotFoundException", () -> dynamoDb.updateKinesisStreamingDestination( + b -> b.tableName(table).streamArn(streamArn + "-missing") + .updateKinesisStreamingConfiguration(c -> c.approximateCreationDateTimePrecision("MICROSECOND")))); + assertPrecision("MILLISECOND"); + dynamoDb.disableKinesisStreamingDestination(b -> b.tableName(table).streamArn(streamArn)); + assertError("ValidationException", () -> update(table, "MICROSECOND")); + assertEquals("DISABLED", dynamoDb.describeKinesisStreamingDestination(b -> b.tableName(table)) + .kinesisDataStreamDestinations().getFirst().destinationStatusAsString()); + assertPrecision("MILLISECOND"); + } + + @Test + void updatesCannotCrossAccountRegionOrArnOwnership() { + try (DynamoDbClient foreignAccount = AwsTestClients.create( + DynamoDbClient.builder(), "222222222222", Region.US_EAST_1); + DynamoDbClient foreignRegion = AwsTestClients.create( + DynamoDbClient.builder(), ACCOUNT, Region.US_WEST_2)) { + assertError("ResourceNotFoundException", () -> foreignAccount.updateKinesisStreamingDestination( + b -> b.tableName(table).streamArn(streamArn))); + assertError("ResourceNotFoundException", () -> foreignRegion.updateKinesisStreamingDestination( + b -> b.tableName(table).streamArn(streamArn))); + DynamoDbException wrongAccount = assertError("ResourceNotFoundException", () -> update( + tableArn.replace(ACCOUNT, "222222222222"), "MICROSECOND")); + assertEquals("Requested resource not found: Table: " + table + " not found", + wrongAccount.awsErrorDetails().errorMessage()); + assertError("ValidationException", () -> update( + tableArn.replace("us-east-1", "us-west-2"), "MICROSECOND")); + DynamoDbException wrongPartition = assertError("ResourceNotFoundException", () -> update( + tableArn.replace("arn:aws:", "arn:aws-us-gov:"), "MICROSECOND")); + assertEquals("Requested resource not found: Table: " + table + " not found", + wrongPartition.awsErrorDetails().errorMessage()); + } + assertPrecision("MILLISECOND"); + } + + @Test + void jsonAndCborExposeOnlyTheUpdateConfigurationMember() throws Exception { + Map request = Map.of("TableName", table, "StreamArn", streamArn, + "UpdateKinesisStreamingConfiguration", Map.of("ApproximateCreationDateTimePrecision", "MICROSECOND")); + for (String protocol : List.of("json", "cbor", "rpc-v2-cbor")) { + JsonNode response = invokeUpdate(request, protocol, 200); + assertEquals(table, response.path("TableName").asText()); + assertEquals(streamArn, response.path("StreamArn").asText()); + assertEquals("MICROSECOND", response.path("UpdateKinesisStreamingConfiguration") + .path("ApproximateCreationDateTimePrecision").asText()); + assertFalse(response.has("EnableKinesisStreamingConfiguration"), response.toString()); + assertFalse(response.has("DestinationStatusDescription"), response.toString()); + } + assertPrecision("MICROSECOND"); + } + + @Test + void requiredMembersAndConfigurationShapeAreValidatedBeforeMutation() throws Exception { + for (Map request : List.>of( + Map.of("StreamArn", streamArn), + Map.of("TableName", table), + Map.of("TableName", table, "StreamArn", ""))) { + assertInvalidRequest(request, "ValidationException"); + } + for (Map request : List.>of( + Map.of("TableName", 123, "StreamArn", streamArn), + Map.of("TableName", table, "StreamArn", 123), + Map.of("TableName", table, "StreamArn", streamArn, "UpdateKinesisStreamingConfiguration", "MICROSECOND"), + Map.of("TableName", table, "StreamArn", streamArn, + "UpdateKinesisStreamingConfiguration", Map.of("ApproximateCreationDateTimePrecision", 123)), + Map.of("TableName", table, "StreamArn", streamArn, + "UpdateKinesisStreamingConfiguration", Map.of("ApproximateCreationDateTimePrecision", true)), + Map.of("TableName", table, "StreamArn", streamArn, + "UpdateKinesisStreamingConfiguration", Map.of("ApproximateCreationDateTimePrecision", Map.of())))) { + assertInvalidRequest(request, "SerializationException"); + } + assertPrecision("MILLISECOND"); + } + + private void assertInvalidRequest(Map request, String code) throws Exception { + for (String protocol : List.of("json", "cbor", "rpc-v2-cbor")) { + JsonNode error = invokeUpdate(request, protocol, 400); + assertEquals(code, error.path("__type").asText().replaceFirst(".*#", ""), + protocol + ": " + error); + } + } + + private JsonNode invokeUpdate(Map request, String protocol, int statusCode) throws Exception { + boolean cbor = !"json".equals(protocol); + boolean rpcV2 = "rpc-v2-cbor".equals(protocol); + ObjectMapper codec = cbor ? new ObjectMapper(new CBORFactory()) : mapper; + RequestSpecification call = given().header("Authorization", auth(ACCOUNT, "dynamodb")); + if (rpcV2) { + call.header("smithy-protocol", "rpc-v2-cbor").contentType("application/cbor"); + } else { + call.header("X-Amz-Target", TARGET) + .contentType(cbor ? "application/x-amz-cbor-1.1" : "application/x-amz-json-1.0"); + } + byte[] body = call.body(codec.writeValueAsBytes(request)) + .post(rpcV2 ? "/service/DynamoDB_20120810/operation/UpdateKinesisStreamingDestination" : "/") + .then().statusCode(statusCode).extract().asByteArray(); + return codec.readTree(body); + } + + private UpdateKinesisStreamingDestinationResponse update(String tableIdentifier, String precision) { + return dynamoDb.updateKinesisStreamingDestination(b -> b.tableName(tableIdentifier).streamArn(streamArn) + .updateKinesisStreamingConfiguration(c -> c.approximateCreationDateTimePrecision(precision))); + } + + private void assertPrecision(String precision) { + assertEquals(1, dynamoDb.describeKinesisStreamingDestination(b -> b.tableName(table)) + .kinesisDataStreamDestinations().size()); + assertEquals(precision, dynamoDb.describeKinesisStreamingDestination(b -> b.tableName(table)) + .kinesisDataStreamDestinations().getFirst().approximateCreationDateTimePrecisionAsString()); + } + + private record WriteWindow(Instant started, Instant finished) {} + + private WriteWindow put(String key) { + Instant started = Instant.now(); + dynamoDb.putItem(b -> b.tableName(table).item(Map.of("pk", AttributeValue.fromS(key)))); + Instant finished = Instant.now(); + forwarder.awaitIdle(Duration.ofSeconds(5)); + return new WriteWindow(started, finished); + } + + private List changes() throws Exception { + String shardId = kinesis.describeStream(b -> b.streamName(table)).streamDescription().shards().getFirst().shardId(); + String iterator = kinesis.getShardIterator(b -> b.streamName(table).shardId(shardId) + .shardIteratorType(ShardIteratorType.TRIM_HORIZON)).shardIterator(); + List changes = new ArrayList<>(); + for (Record record : kinesis.getRecords(b -> b.shardIterator(iterator)).records()) { + changes.add(mapper.readTree(record.data().asByteArray()).path("dynamodb")); + } + return changes; + } + + private static DynamoDbException assertError(String code, Executable operation) { + DynamoDbException error = assertThrows(DynamoDbException.class, operation); + assertEquals(400, error.statusCode()); + assertEquals(code, error.awsErrorDetails().errorCode()); + return error; + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateServiceTest.java new file mode 100644 index 0000000000..036f43b0b5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbKinesisUpdateServiceTest.java @@ -0,0 +1,174 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.CreateTableRequest; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.TableSettings; +import io.floci.aws.services.dynamodb.model.AttributeDefinition; +import io.floci.aws.services.dynamodb.model.KeySchemaElement; +import io.floci.aws.services.dynamodb.model.KinesisStreamingDestination; +import io.floci.aws.services.dynamodb.model.TableDefinition; +import io.floci.aws.services.kinesis.KinesisService; +import io.floci.aws.testing.StorageTestBackends; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; + +class DynamoDbKinesisUpdateServiceTest { + + private static final String REGION = "us-east-1"; + private static final String TABLE = "persistent-kinesis-update"; + private static final String STREAM = "arn:aws:kinesis:us-east-1:000000000000:stream/updates"; + private static final TypeReference> TYPE = new TypeReference<>() { }; + + enum Mode { + MEMORY, PERSISTENT, HYBRID, WAL + } + + @ParameterizedTest + @EnumSource(Mode.class) + void updatedPrecisionAndOmittedUpdateSurviveTheStorageLifecycle(Mode mode, @TempDir Path directory) { + StorageBackend storage = storage(mode, directory); + try { + DynamoDbStreamService streams = new DynamoDbStreamService(new ObjectMapper(), storage); + DynamoDbService dynamoDb = new DynamoDbService(storage, null, + new RegionResolver(REGION, "000000000000"), streams, mock(KinesisStreamingForwarder.class)); + NativeDynamoDbTableService tables = new NativeDynamoDbTableService( + dynamoDb, streams, mock(KinesisService.class)); + TableDefinition created = tables.createTable(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(), Map.of(), + new TableSettings("PAY_PER_REQUEST", null, null, null, null, null, null, null, null), null), + "ACTIVE", REGION); + tables.enableKinesisStreamingDestination(TABLE, STREAM, "MILLISECOND", REGION); + storage.flush(); + tables.updateKinesisStreamingDestination(created.getTableArn(), STREAM, "MICROSECOND", REGION); + tables.updateKinesisStreamingDestination(TABLE, STREAM, null, REGION); + storage.flush(); + if (mode != Mode.MEMORY) { + StorageTestBackends.close(storage); + storage = storage(mode, directory); + } + TableDefinition reloaded = storage.get(REGION + "::" + TABLE).orElseThrow(); + assertEquals(1, reloaded.getKinesisStreamingDestinations().size()); + KinesisStreamingDestination destination = reloaded.findKinesisStreamingDestination(STREAM).orElseThrow(); + assertEquals("ACTIVE", destination.getDestinationStatus()); + assertEquals("MICROSECOND", destination.getApproximateCreationDateTimePrecision()); + assertFalse(reloaded.isStreamEnabled(), "changing Kinesis precision must not enable DynamoDB Streams"); + } finally { + StorageTestBackends.close(storage); + } + } + + @ParameterizedTest + @ValueSource(strings = {"enable", "update", "disable"}) + void deletingDuringDestinationMutationCannotResurrectTheTable(String operation) throws Exception { + PausingStorage storage = new PausingStorage(); + DynamoDbStreamService streams = new DynamoDbStreamService(new ObjectMapper(), storage); + DynamoDbService dynamoDb = new DynamoDbService(storage, null, + new RegionResolver(REGION, "000000000000"), streams, mock(KinesisStreamingForwarder.class)); + NativeDynamoDbTableService tables = new NativeDynamoDbTableService( + dynamoDb, streams, mock(KinesisService.class)); + String tableArn = tables.createTable(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(), Map.of(), + new TableSettings("PAY_PER_REQUEST", null, null, null, null, null, null, null, null), null), + "ACTIVE", REGION).getTableArn(); + if (!"enable".equals(operation)) { + tables.enableKinesisStreamingDestination(TABLE, STREAM, "MILLISECOND", REGION); + } + storage.pauseWrites = true; + AtomicReference deletionThread = new AtomicReference<>(); + AtomicReference mutationThread = new AtomicReference<>(); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future mutation = executor.submit(() -> { + mutationThread.set(Thread.currentThread()); + switch (operation) { + case "enable" -> tables.enableKinesisStreamingDestination(tableArn, STREAM, "MICROSECOND", REGION); + case "update" -> tables.updateKinesisStreamingDestination(tableArn, STREAM, "MICROSECOND", REGION); + case "disable" -> tables.disableKinesisStreamingDestination(tableArn, STREAM, REGION); + default -> throw new IllegalArgumentException(operation); + } + }); + try { + assertTrue(storage.atWrite.await(5, TimeUnit.SECONDS), "mutation must reach its persistence point"); + Future deletion = executor.submit(() -> { + deletionThread.set(Thread.currentThread()); + dynamoDb.deleteTable(TABLE, REGION); + }); + // Without the shared table lock, deletion completes here and the paused put restores + // the deleted table. With it, deletion waits for the complete mutation before removing it. + await().atMost(Duration.ofSeconds(5)).until(() -> { + if (deletion.isDone()) { + return true; + } + Thread deleting = deletionThread.get(); + ThreadInfo info = deleting == null ? null + : ManagementFactory.getThreadMXBean().getThreadInfo(deleting.threadId()); + return info != null && info.getLockOwnerId() == mutationThread.get().threadId(); + }); + storage.resume.countDown(); + mutation.get(5, TimeUnit.SECONDS); + deletion.get(5, TimeUnit.SECONDS); + assertTrue(dynamoDb.findTable(TABLE, REGION).isEmpty(), "a completed delete must leave no table"); + } finally { + storage.resume.countDown(); + } + } + } + + private static final class PausingStorage extends InMemoryStorage { + private final CountDownLatch atWrite = new CountDownLatch(1); + private final CountDownLatch resume = new CountDownLatch(1); + private volatile boolean pauseWrites; + + @Override + public void put(String key, TableDefinition value) { + if (pauseWrites) { + atWrite.countDown(); + try { + if (!resume.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("timed out waiting to resume the destination mutation"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + super.put(key, value); + } + } + + private static StorageBackend storage(Mode mode, Path directory) { + StorageBackend storage = StorageTestBackends.create( + mode.name().toLowerCase(Locale.ROOT), directory.resolve("tables.json"), + directory.resolve("tables.wal"), TYPE, 60_000); + storage.load(); + return storage; + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java index 660e9219e5..1d88f64fee 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java @@ -412,6 +412,12 @@ class NativeDynamoDbTableServiceTest { assertEquals("ACTIVE", persisted.getDestinationStatus()); assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND, persisted.getApproximateCreationDateTimePrecision()); + NativeDynamoDbTableService.KinesisDestination unchanged = tableService.updateKinesisStreamingDestination( + TABLE, STREAM_ARN, null, REGION); + assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND, unchanged.approximateCreationDateTimePrecision()); + assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND, + reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN).orElseThrow() + .getApproximateCreationDateTimePrecision()); verify(forwarder, never()).onDestinationDisabled(ACCOUNT, REGION, TABLE, STREAM_ARN); } diff --git a/src/test/java/io/floci/aws/testing/DynamoDbTableFixtures.java b/src/test/java/io/floci/aws/testing/DynamoDbTableFixtures.java new file mode 100644 index 0000000000..ed52206406 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/DynamoDbTableFixtures.java @@ -0,0 +1,24 @@ +package io.floci.aws.testing; + +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.BillingMode; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; + +/** SDK table fixtures shared by DynamoDB integration tests. */ +public final class DynamoDbTableFixtures { + + private DynamoDbTableFixtures() { + } + + /** Creates an on-demand table with a string partition key named {@code pk}, returning its ARN. */ + public static String createKeyedTable(DynamoDbClient client, String name) { + return client.createTable(b -> b.tableName(name).billingMode(BillingMode.PAY_PER_REQUEST) + .keySchema(KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build()) + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("pk").attributeType(ScalarAttributeType.S).build())) + .tableDescription().tableArn(); + } +}