mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dynamodb): update Kinesis destination precision (#9072)
* feat(dynamodb): update Kinesis destination precision * fix(dynamodb): reuse validation for Kinesis precision updates Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
546065dc53
commit
ab7fc6f81f
11 files changed
+663
-15
No files matched your search
+83
@@ -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());
|
||||
}
|
||||
}
|
||||
+272
@@ -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<JsonNode> changes = changes();
|
||||
assertEquals(List.of("before", "after", "restored"),
|
||||
changes.stream().map(n -> n.path("Keys").path("pk").path("S").asText()).toList());
|
||||
List<WriteWindow> 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<String, Object> 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<String, Object> request : List.<Map<String, Object>>of(
|
||||
Map.of("StreamArn", streamArn),
|
||||
Map.of("TableName", table),
|
||||
Map.of("TableName", table, "StreamArn", ""))) {
|
||||
assertInvalidRequest(request, "ValidationException");
|
||||
}
|
||||
for (Map<String, Object> request : List.<Map<String, Object>>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<String, Object> 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<String, Object> 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<JsonNode> 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<JsonNode> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Map<String, TableDefinition>> TYPE = new TypeReference<>() { };
|
||||
|
||||
enum Mode {
|
||||
MEMORY, PERSISTENT, HYBRID, WAL
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Mode.class)
|
||||
void updatedPrecisionAndOmittedUpdateSurviveTheStorageLifecycle(Mode mode, @TempDir Path directory) {
|
||||
StorageBackend<String, TableDefinition> 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<Thread> deletionThread = new AtomicReference<>();
|
||||
AtomicReference<Thread> 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<String, TableDefinition> {
|
||||
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<String, TableDefinition> storage(Mode mode, Path directory) {
|
||||
StorageBackend<String, TableDefinition> storage = StorageTestBackends.create(
|
||||
mode.name().toLowerCase(Locale.ROOT), directory.resolve("tables.json"),
|
||||
directory.resolve("tables.wal"), TYPE, 60_000);
|
||||
storage.load();
|
||||
return storage;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user