mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(kinesis): add configurable stream status windows (#8227)
This commit is contained in:
1 parent
35a9ca0f4b
commit
c3e9dbad96
16 files changed
+1143
-89
No files matched your search
+46
-14
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -19,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -77,14 +79,14 @@ class KinesisCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void createUsesTheExplicitNameAndExposesTheArn() {
|
||||
when(kinesis.createStream(eq("s"), anyInt(), any(), eq(REGION)))
|
||||
when(kinesis.createStream(eq("s"), anyInt(), any(), any(), anyMap(), any(), eq(REGION)))
|
||||
.thenReturn(stream("arn:aws:kinesis:us-east-1:000000000000:stream/s", 24));
|
||||
|
||||
StackResource r = provision("""
|
||||
{"Name": "s", "ShardCount": "3"}
|
||||
""", null);
|
||||
|
||||
verify(kinesis).createStream("s", 3, null, REGION);
|
||||
verify(kinesis).createStream("s", 3, null, null, Map.of(), null, REGION);
|
||||
assertEquals("s", r.getPhysicalId(), "Ref is the stream name");
|
||||
// aws-kinesis-stream.json readOnlyProperties
|
||||
assertEquals(Map.of("Arn", "arn:aws:kinesis:us-east-1:000000000000:stream/s"), r.getAttributes());
|
||||
@@ -92,28 +94,30 @@ class KinesisCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void shardCountDefaultsToOneWhenAbsentOrUnparseable() {
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
|
||||
provision("""
|
||||
{"Name": "a"}
|
||||
""", null);
|
||||
verify(kinesis).createStream("a", 1, null, REGION);
|
||||
verify(kinesis).createStream("a", 1, null, null, Map.of(), null, REGION);
|
||||
|
||||
provision("""
|
||||
{"Name": "b", "ShardCount": "many"}
|
||||
""", null);
|
||||
verify(kinesis).createStream("b", 1, null, REGION);
|
||||
verify(kinesis).createStream("b", 1, null, null, Map.of(), null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamModeDetailsAreForwarded() {
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
|
||||
provision("""
|
||||
{"Name": "s", "StreamModeDetails": {"StreamMode": "ON_DEMAND"}}
|
||||
""", null);
|
||||
|
||||
verify(kinesis).createStream("s", 1, "ON_DEMAND", REGION);
|
||||
verify(kinesis).createStream("s", 1, "ON_DEMAND", null, Map.of(), null, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,8 +132,8 @@ class KinesisCfnProvisionerTest {
|
||||
{"Name": "s"}
|
||||
""", "s");
|
||||
|
||||
verify(kinesis, never()).createStream(anyString(), anyInt(), any(), anyString());
|
||||
verify(kinesis).updateStreamMode("s", "PROVISIONED", REGION);
|
||||
verify(kinesis, never()).createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString());
|
||||
verify(kinesis, never()).updateStreamMode("s", "PROVISIONED", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -166,23 +170,49 @@ class KinesisCfnProvisionerTest {
|
||||
verify(kinesis).addTagsToStream("s", Map.of("kept", "2"), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconcileAllowsReplacingOneTagAtTheFiftyTagLimit() throws Exception {
|
||||
when(kinesis.describeStream("s", REGION)).thenReturn(stream("arn", 24));
|
||||
Map<String, String> existingTags = new LinkedHashMap<>();
|
||||
Map<String, String> desiredTags = new LinkedHashMap<>();
|
||||
for (int i = 0; i < 50; i++) {
|
||||
existingTags.put("tag-" + i, "old");
|
||||
if (i < 49) {
|
||||
desiredTags.put("tag-" + i, "old");
|
||||
}
|
||||
}
|
||||
desiredTags.put("tag-new", "new");
|
||||
when(kinesis.listTagsForStream("s", REGION)).thenReturn(existingTags);
|
||||
List<Map<String, String>> desiredTagEntries = desiredTags.entrySet().stream()
|
||||
.map(entry -> Map.of("Key", entry.getKey(), "Value", entry.getValue()))
|
||||
.toList();
|
||||
String body = MAPPER.writeValueAsString(Map.of("Name", "s", "Tags", desiredTagEntries));
|
||||
|
||||
provision(body, "s");
|
||||
|
||||
verify(kinesis).removeTagsFromStream("s", List.of("tag-49"), REGION);
|
||||
verify(kinesis).addTagsToStream("s", desiredTags, REGION);
|
||||
}
|
||||
|
||||
/** A stream deleted out of band since the last update falls back to a fresh create. */
|
||||
@Test
|
||||
void aMissingStreamFallsBackToCreate() {
|
||||
when(kinesis.describeStream("s", REGION))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 400));
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
|
||||
provision("""
|
||||
{"Name": "s"}
|
||||
""", "s");
|
||||
|
||||
verify(kinesis).createStream("s", 1, null, REGION);
|
||||
verify(kinesis).createStream("s", 1, null, null, Map.of(), null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenameCreatesTheNewStreamAndBestEffortDeletesTheOld() {
|
||||
when(kinesis.createStream(eq("new"), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
|
||||
StackResource r = provision("""
|
||||
{"Name": "new"}
|
||||
@@ -195,7 +225,8 @@ class KinesisCfnProvisionerTest {
|
||||
/** A failure deleting the renamed-away stream must not fail the resource. */
|
||||
@Test
|
||||
void aFailedCleanupOfTheRenamedStreamIsSwallowed() {
|
||||
when(kinesis.createStream(eq("new"), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
Mockito.doThrow(new RuntimeException("boom"))
|
||||
.when(kinesis).deleteStream("old", REGION);
|
||||
|
||||
@@ -208,7 +239,8 @@ class KinesisCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void anUnnamedStreamGetsAGeneratedNameKeptAcrossUpdates() {
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24));
|
||||
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
|
||||
.thenReturn(stream("arn", 24));
|
||||
|
||||
StackResource created = provision("{}", null);
|
||||
assertTrue(created.getPhysicalId().startsWith("my-stack-Stream-"), created.getPhysicalId());
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ import static org.mockito.Mockito.when;
|
||||
* hands scalars back as text and nodes back unchanged, and an update context carrying the previous
|
||||
* template's properties, as the stack hands them over.
|
||||
*/
|
||||
final class ProvisionContexts {
|
||||
public final class ProvisionContexts {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@@ -24,7 +24,7 @@ final class ProvisionContexts {
|
||||
* Scalar properties only: intrinsic resolution (Ref/GetAtt) is the engine's job and is covered by
|
||||
* its own tests, so a passthrough keeps a provisioner test a true isolated unit test.
|
||||
*/
|
||||
static CloudFormationTemplateEngine passthroughEngine() {
|
||||
public static CloudFormationTemplateEngine passthroughEngine() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package io.floci.aws.services.kinesis;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.PersistentStorage;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.cloudformation.provisioners.KinesisCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.ProvisionContext;
|
||||
import io.floci.aws.services.cloudformation.provisioners.ProvisionContexts;
|
||||
import io.floci.aws.services.kinesis.model.KinesisStream;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class KinesisCfnServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void updateReconcilesRetentionAndTagsBeforeChangingStreamMode() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 60_000);
|
||||
KinesisStream stream = service.createStream("s", 1, REGION);
|
||||
service.addTagsToStream("s", Map.of("stale", "1"), REGION);
|
||||
|
||||
provision(service, """
|
||||
{"Name": "s", "RetentionPeriodHours": "48",
|
||||
"StreamModeDetails": {"StreamMode": "ON_DEMAND"},
|
||||
"Tags": [{"Key": "fresh", "Value": "2"}]}
|
||||
""", "s");
|
||||
|
||||
assertEquals(48, stream.getRetentionPeriodHours());
|
||||
assertEquals(Map.of("fresh", "2"), stream.getTags());
|
||||
assertEquals("ON_DEMAND", stream.getStreamMode());
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPersistsInitialTagsAndRetentionBeforeTheStreamBecomesActive() throws Exception {
|
||||
Path path = tempDir.resolve("cfn-kinesis-streams.json");
|
||||
TypeReference<Map<String, KinesisStream>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, KinesisStream> store = new PersistentStorage<>(path, type);
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 0);
|
||||
|
||||
provision(service, """
|
||||
{"Name": "s", "RetentionPeriodHours": "48", "Tags": [{"Key": "env", "Value": "dev"}]}
|
||||
""", null);
|
||||
|
||||
PersistentStorage<String, KinesisStream> reloaded = new PersistentStorage<>(path, type);
|
||||
reloaded.load();
|
||||
KinesisStream restored = reloaded.get(REGION + "::s").orElseThrow();
|
||||
assertEquals("CREATING", restored.getStreamStatus(clock.instant()));
|
||||
assertEquals(Map.of("env", "dev"), restored.getTags());
|
||||
assertEquals(48, restored.getRetentionPeriodHours());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {12, 9000})
|
||||
void createRejectsOutOfRangeRetentionWithoutLeavingStream(int retentionHours) throws Exception {
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> provision(service, """
|
||||
{"Name": "s", "RetentionPeriodHours": "%d"}
|
||||
""".formatted(retentionHours), null));
|
||||
|
||||
assertEquals("InvalidArgumentException", error.getErrorCode());
|
||||
assertEquals(0, service.listStreamDetails(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedStreamModeDoesNotRequireActiveDuringCreatingWindow() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 0);
|
||||
KinesisStream stream = service.createStream("s", 1, REGION);
|
||||
|
||||
provision(service, """
|
||||
{"Name": "s"}
|
||||
""", "s");
|
||||
|
||||
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retentionOnlyUpdateCannotMutateCreatingStream() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 0);
|
||||
KinesisStream stream = service.createStream("s", 1, REGION);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> provision(service, """
|
||||
{"Name": "s", "RetentionPeriodHours": "48"}
|
||||
""", "s"));
|
||||
|
||||
assertEquals("ResourceInUseException", error.getErrorCode());
|
||||
assertEquals(24, stream.getRetentionPeriodHours());
|
||||
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidUpdateModeLeavesExistingTagsUntouched() throws Exception {
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"));
|
||||
KinesisStream stream = service.createStream("s", 1, REGION);
|
||||
service.addTagsToStream("s", Map.of("old", "1"), REGION);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> provision(service, """
|
||||
{"Name": "s", "StreamModeDetails": {"StreamMode": "INVALID"},
|
||||
"Tags": [{"Key": "new", "Value": "2"}]}
|
||||
""", "s"));
|
||||
|
||||
assertEquals("InvalidArgumentException", error.getErrorCode());
|
||||
assertEquals(Map.of("old", "1"), stream.getTags());
|
||||
assertEquals("PROVISIONED", stream.getStreamMode());
|
||||
}
|
||||
|
||||
private static void provision(KinesisService service, String json, String priorPhysicalId) throws Exception {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Stream");
|
||||
resource.setResourceType("AWS::Kinesis::Stream");
|
||||
resource.setPhysicalId(priorPhysicalId);
|
||||
resource.setAttributes(new HashMap<>());
|
||||
new KinesisCfnProvisioner(service).provision(resource, MAPPER.readTree(json),
|
||||
new ProvisionContext(ProvisionContexts.passthroughEngine(), REGION, "000000000000",
|
||||
"my-stack", priorPhysicalId));
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.kinesis.model.KinesisShard;
|
||||
import io.floci.aws.services.kinesis.model.KinesisStream;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -23,6 +24,7 @@ import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
@@ -470,6 +472,91 @@ class KinesisJsonHandlerTest {
|
||||
assertEquals("test-stream", desc.get("StreamName").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusResponsesUseTheServiceClock() {
|
||||
MutableClock clock = new MutableClock();
|
||||
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
|
||||
service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
resolver, clock, 60_000, 60_000);
|
||||
handler = new KinesisJsonHandler(service, MAPPER, 300_000);
|
||||
KinesisInspectionController inspection = new KinesisInspectionController(service, MAPPER, resolver);
|
||||
service.createStream("test-stream", 1, REGION);
|
||||
ObjectNode request = MAPPER.createObjectNode().put("StreamName", "test-stream");
|
||||
|
||||
assertEquals("CREATING", responseEntity(handler.handle("DescribeStream", request, REGION))
|
||||
.path("StreamDescription").path("StreamStatus").asText());
|
||||
assertEquals("CREATING", responseEntity(handler.handle("DescribeStreamSummary", request, REGION))
|
||||
.path("StreamDescriptionSummary").path("StreamStatus").asText());
|
||||
assertEquals("CREATING", responseEntity(handler.handle("ListStreams", MAPPER.createObjectNode(), REGION))
|
||||
.path("StreamSummaries").get(0).path("StreamStatus").asText());
|
||||
assertEquals("CREATING", responseEntity(inspection.getStreams(null))
|
||||
.path("streams").get(0).path("StreamStatus").asText());
|
||||
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
service.updateStreamMode("test-stream", "ON_DEMAND", REGION);
|
||||
assertEquals("UPDATING", responseEntity(handler.handle("DescribeStreamSummary", request, REGION))
|
||||
.path("StreamDescriptionSummary").path("StreamStatus").asText());
|
||||
assertEquals("UPDATING", responseEntity(inspection.getStreams(null))
|
||||
.path("streams").get(0).path("StreamStatus").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStreamAcceptsInitialTagsDuringCreatingWindow() {
|
||||
MutableClock clock = new MutableClock();
|
||||
service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), clock, 60_000, 0);
|
||||
handler = new KinesisJsonHandler(service, MAPPER, 300_000);
|
||||
ObjectNode request = MAPPER.createObjectNode().put("StreamName", "test-stream").put("ShardCount", 1);
|
||||
request.putObject("Tags").put("env", "dev");
|
||||
|
||||
assertEquals(200, handler.handle("CreateStream", request, REGION).getStatus());
|
||||
KinesisStream stream = service.describeStream("test-stream", REGION);
|
||||
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
|
||||
assertEquals(Map.of("env", "dev"), stream.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStreamRejectsExcessInitialTagsWithoutLeavingAStream() {
|
||||
ObjectNode request = MAPPER.createObjectNode().put("StreamName", "too-many-tags").put("ShardCount", 1);
|
||||
ObjectNode tags = request.putObject("Tags");
|
||||
for (int i = 0; i < 51; i++) {
|
||||
tags.put("tag-" + i, "value");
|
||||
}
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> handler.handle("CreateStream", request, REGION));
|
||||
assertEquals("LimitExceededException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(service.listStreamDetails(REGION).isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"PutRecord", "PutRecords"})
|
||||
void recordsRequireCreatedStreamToBecomeActiveButCanWriteWhileUpdating(String action) {
|
||||
MutableClock clock = new MutableClock();
|
||||
service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), clock, 60_000, 60_000);
|
||||
handler = new KinesisJsonHandler(service, MAPPER, 300_000);
|
||||
KinesisStream stream = service.createStream("test-stream", 1, REGION);
|
||||
ObjectNode request = MAPPER.createObjectNode().put("StreamName", "test-stream");
|
||||
ObjectNode record = "PutRecords".equals(action) ? request.putArray("Records").addObject() : request;
|
||||
record.put("PartitionKey", "pk").put("Data", "AQ==");
|
||||
|
||||
AwsException creating = assertThrows(AwsException.class, () -> handler.handle(action, request, REGION));
|
||||
assertEquals("ResourceNotFoundException", creating.getErrorCode());
|
||||
assertEquals(400, creating.getHttpStatus());
|
||||
assertEquals(0, stream.getShards().getFirst().recordCount());
|
||||
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
service.updateStreamMode("test-stream", "ON_DEMAND", REGION);
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
ObjectNode response = responseEntity(handler.handle(action, request, REGION));
|
||||
if ("PutRecords".equals(action)) {
|
||||
assertEquals(0, response.path("FailedRecordCount").asInt());
|
||||
}
|
||||
assertEquals(1, stream.getShards().getFirst().recordCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeStreamSerializesCreationTimestampAsPlainDecimal() throws Exception {
|
||||
createStream("test-stream");
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package io.floci.aws.services.kinesis;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.PersistentStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.services.kinesis.model.KinesisConsumer;
|
||||
import io.floci.aws.services.kinesis.model.KinesisRecord;
|
||||
@@ -12,6 +14,7 @@ import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
@@ -19,6 +22,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -53,6 +57,9 @@ class KinesisServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private KinesisService kinesisService;
|
||||
|
||||
@BeforeEach
|
||||
@@ -81,6 +88,66 @@ class KinesisServiceTest {
|
||||
kinesisService.createStream("my-stream", 1, REGION));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("streamTagMutations")
|
||||
void streamTagMutationsRequireActiveStatus(String operation, Consumer<KinesisService> mutate) {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 2_000, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
stream.getTags().put("env", "dev");
|
||||
|
||||
AwsException creating = assertThrows(AwsException.class, () -> mutate.accept(service), operation);
|
||||
assertEquals("ResourceInUseException", creating.getErrorCode());
|
||||
assertEquals(Map.of("env", "dev"), stream.getTags());
|
||||
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.updateStreamMode("my-stream", "ON_DEMAND", REGION);
|
||||
AwsException updating = assertThrows(AwsException.class, () -> mutate.accept(service), operation);
|
||||
assertEquals("ResourceInUseException", updating.getErrorCode());
|
||||
assertEquals(Map.of("env", "dev"), stream.getTags());
|
||||
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
mutate.accept(service);
|
||||
assertEquals(operation.startsWith("Remove") || operation.startsWith("Untag")
|
||||
? Map.of() : Map.of("env", "prod"), stream.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retentionChangesRejectUpdatingStream() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
service.increaseStreamRetentionPeriod("my-stream", 48, REGION);
|
||||
service.updateStreamMode("my-stream", "ON_DEMAND", REGION);
|
||||
|
||||
AwsException increase = assertThrows(AwsException.class,
|
||||
() -> service.increaseStreamRetentionPeriod("my-stream", 72, REGION));
|
||||
AwsException decrease = assertThrows(AwsException.class,
|
||||
() -> service.decreaseStreamRetentionPeriod("my-stream", 24, REGION));
|
||||
|
||||
assertEquals("ResourceInUseException", increase.getErrorCode());
|
||||
assertEquals("ResourceInUseException", decrease.getErrorCode());
|
||||
assertEquals(48, stream.getRetentionPeriodHours());
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.decreaseStreamRetentionPeriod("my-stream", 24, REGION);
|
||||
assertEquals(24, stream.getRetentionPeriodHours());
|
||||
}
|
||||
|
||||
static Stream<Arguments> streamTagMutations() {
|
||||
String arn = "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream";
|
||||
return Stream.of(
|
||||
Arguments.of("AddTagsToStream", (Consumer<KinesisService>) service ->
|
||||
service.addTagsToStream("my-stream", Map.of("env", "prod"), REGION)),
|
||||
Arguments.of("RemoveTagsFromStream", (Consumer<KinesisService>) service ->
|
||||
service.removeTagsFromStream("my-stream", List.of("env"), REGION)),
|
||||
Arguments.of("TagResource", (Consumer<KinesisService>) service ->
|
||||
service.tagResource(arn, Map.of("env", "prod"), REGION)),
|
||||
Arguments.of("UntagResource", (Consumer<KinesisService>) service ->
|
||||
service.untagResource(arn, List.of("env"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listStreamDetails() {
|
||||
kinesisService.createStream("stream-b", 1, REGION);
|
||||
@@ -367,6 +434,37 @@ class KinesisServiceTest {
|
||||
assertEquals(parent.getHashKeyRange().endingHashKey(), child2.getHashKeyRange().endingHashKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitShardRejectsUpdatingStream() {
|
||||
KinesisStream stream = kinesisService.createStream("my-stream", 1, REGION);
|
||||
stream.setStreamStatus("UPDATING");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> kinesisService.splitShard("my-stream", stream.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION));
|
||||
|
||||
assertEquals("ResourceInUseException", error.getErrorCode());
|
||||
assertEquals(1, stream.getShards().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedSplitLeavesStreamActive() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
KinesisShard parent = stream.getShards().getFirst();
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.splitShard("my-stream", parent.getShardId(),
|
||||
parent.getHashKeyRange().startingHashKey(), REGION));
|
||||
|
||||
assertEquals("InvalidArgumentException", error.getErrorCode());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
assertEquals(1, stream.getShards().size());
|
||||
assertFalse(parent.isClosed());
|
||||
}
|
||||
|
||||
/**
|
||||
* A lock-free reader must never observe a half-published split: a closed parent with only one
|
||||
* of its two children. splitShard publishes both children in one atomic CopyOnWriteArrayList.addAll,
|
||||
@@ -490,6 +588,370 @@ class KinesisServiceTest {
|
||||
assertFalse(updated.getShards().get(2).isClosed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeShardsRejectsUpdatingStream() {
|
||||
KinesisStream stream = kinesisService.createStream("my-stream", 2, REGION);
|
||||
stream.setStreamStatus("UPDATING");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> kinesisService.mergeShards("my-stream", stream.getShards().get(0).getShardId(),
|
||||
stream.getShards().get(1).getShardId(), REGION));
|
||||
|
||||
assertEquals("ResourceInUseException", error.getErrorCode());
|
||||
assertEquals(2, stream.getShards().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedNonAdjacentMergeLeavesStreamActive() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 3, REGION);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.mergeShards("my-stream", stream.getShards().get(0).getShardId(),
|
||||
stream.getShards().get(2).getShardId(), REGION));
|
||||
|
||||
assertEquals("InvalidArgumentException", error.getErrorCode());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
assertEquals(3, stream.getShards().size());
|
||||
assertTrue(stream.getShards().stream().noneMatch(KinesisShard::isClosed));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configuredStatusWindowsExpireWithoutBackgroundWork() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 1_000, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
String parentId = stream.getShards().getFirst().getShardId();
|
||||
|
||||
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
|
||||
AwsException creating = assertThrows(AwsException.class,
|
||||
() -> service.splitShard("my-stream", parentId,
|
||||
"170141183460469231731687303715884105728", REGION));
|
||||
assertEquals("ResourceInUseException", creating.getErrorCode());
|
||||
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
service.splitShard("my-stream", parentId, "170141183460469231731687303715884105728", REGION);
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
assertNotNull(service.putRecord("my-stream", new byte[]{1}, "partition", REGION));
|
||||
|
||||
String leftId = stream.getShards().get(1).getShardId();
|
||||
String rightId = stream.getShards().get(2).getShardId();
|
||||
AwsException updating = assertThrows(AwsException.class,
|
||||
() -> service.mergeShards("my-stream", leftId, rightId, REGION));
|
||||
assertEquals("ResourceInUseException", updating.getErrorCode());
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.mergeShards("my-stream", leftId, rightId, REGION);
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creatingWindowStartsBeforeStreamPersistence() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 2_000, 0);
|
||||
store.advanceNextPut();
|
||||
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
|
||||
assertEquals(1, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamModeWindowStartsBeforeUpdatePersistence() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
store.advanceNextPut();
|
||||
|
||||
service.updateStreamMode("my-stream", "ON_DEMAND", REGION);
|
||||
|
||||
assertEquals(2, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitWindowStartsBeforeFinalPersistence() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
store.advanceNextPut();
|
||||
|
||||
service.splitShard("my-stream", stream.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION);
|
||||
|
||||
assertEquals(2, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeWindowStartsBeforeFinalPersistence() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 2, REGION);
|
||||
String first = stream.getShards().get(0).getShardId();
|
||||
String second = stream.getShards().get(1).getShardId();
|
||||
store.advanceNextPut();
|
||||
|
||||
service.mergeShards("my-stream", first, second, REGION);
|
||||
|
||||
assertEquals(2, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shardCountWindowStartsBeforeFinalPersistence() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
store.advanceNthPut(2);
|
||||
|
||||
service.updateShardCount("my-stream", 2, "UNIFORM_SCALING", REGION);
|
||||
|
||||
assertEquals(3, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroDelayControlPlaneChangesUseOneFinalWrite() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 0);
|
||||
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
assertEquals(1, store.putCount());
|
||||
service.splitShard("my-stream", stream.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION);
|
||||
assertEquals(2, store.putCount());
|
||||
service.mergeShards("my-stream", stream.getShards().get(1).getShardId(),
|
||||
stream.getShards().get(2).getShardId(), REGION);
|
||||
assertEquals(3, store.putCount());
|
||||
service.updateStreamMode("my-stream", "ON_DEMAND", REGION);
|
||||
assertEquals(4, store.putCount());
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPersistenceRetainsTheUpdateDeadline() {
|
||||
MutableClock clock = new MutableClock();
|
||||
AdvancingStore store = new AdvancingStore(clock);
|
||||
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
store.failNextPut();
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> service.splitShard("my-stream", stream.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION));
|
||||
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShardCountCompletesItsOwnSplitsAndMergesWithinOneWindow() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 2, REGION);
|
||||
|
||||
service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION);
|
||||
assertEquals(4, stream.getShards().stream().filter(shard -> !shard.isClosed()).count());
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
AwsException busy = assertThrows(AwsException.class,
|
||||
() -> service.updateShardCount("my-stream", 2, "UNIFORM_SCALING", REGION));
|
||||
assertEquals("ResourceInUseException", busy.getErrorCode());
|
||||
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.updateShardCount("my-stream", 2, "UNIFORM_SCALING", REGION);
|
||||
assertEquals(2, stream.getShards().stream().filter(shard -> !shard.isClosed()).count());
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitShardReportsUpdatingBeforeClosingItsParent() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 1, REGION);
|
||||
ParkOnCloseShard parent = new ParkOnCloseShard(stream.getShards().getFirst());
|
||||
stream.getShards().set(0, parent);
|
||||
ExecutorService pool = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<?> split = pool.submit(() -> service.splitShard("my-stream", parent.getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION));
|
||||
assertTrue(parent.parked.await(5, TimeUnit.SECONDS));
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
parent.release.countDown();
|
||||
split.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
parent.release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShardCountReportsUpdatingBeforeFirstSplit() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 2, REGION);
|
||||
ParkOnCloseShard parent = new ParkOnCloseShard(stream.getShards().getFirst());
|
||||
stream.getShards().set(0, parent);
|
||||
ExecutorService pool = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<?> scaling = pool.submit(() -> service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION));
|
||||
assertTrue(parent.parked.await(5, TimeUnit.SECONDS));
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
clock.advance(Duration.ofSeconds(3));
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
parent.release.countDown();
|
||||
scaling.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("ACTIVE", stream.getStreamStatus(clock.instant()));
|
||||
} finally {
|
||||
parent.release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"split", "merge", "scale"})
|
||||
void reshardReportsUpdatingBeforeLegacyRangeNormalization(String operation) throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream stream = service.createStream("my-stream", 2, REGION);
|
||||
KinesisShard.HashKeyRange legacyRange = new KinesisShard.HashKeyRange("0",
|
||||
"340282366920938463463374607431768211455");
|
||||
stream.getShards().forEach(shard -> shard.setHashKeyRange(legacyRange));
|
||||
ParkOnRangeNormalizationShard first = new ParkOnRangeNormalizationShard(stream.getShards().getFirst());
|
||||
stream.getShards().set(0, first);
|
||||
String secondId = stream.getShards().get(1).getShardId();
|
||||
|
||||
ExecutorService pool = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<?> reshard = pool.submit(() -> {
|
||||
switch (operation) {
|
||||
case "split" -> service.splitShard("my-stream", first.getShardId(), "1", REGION);
|
||||
case "merge" -> service.mergeShards("my-stream", first.getShardId(), secondId, REGION);
|
||||
case "scale" -> service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION);
|
||||
default -> throw new IllegalArgumentException(operation);
|
||||
}
|
||||
});
|
||||
assertTrue(first.parked.await(5, TimeUnit.SECONDS));
|
||||
assertEquals("UPDATING", stream.getStreamStatus(clock.instant()));
|
||||
first.release.countDown();
|
||||
reshard.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
first.release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusDeadlineSurvivesPersistentStorageReload() {
|
||||
Clock clock = Clock.systemUTC();
|
||||
Path path = tempDir.resolve("kinesis-streams.json");
|
||||
TypeReference<Map<String, KinesisStream>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, KinesisStream> original = new PersistentStorage<>(path, type);
|
||||
KinesisService writer = new KinesisService(original, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 60_000);
|
||||
writer.createStream("my-stream", 1, REGION);
|
||||
|
||||
PersistentStorage<String, KinesisStream> reloaded = new PersistentStorage<>(path, type);
|
||||
reloaded.load();
|
||||
KinesisService reader = new KinesisService(reloaded, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 60_000);
|
||||
KinesisStream stream = reader.describeStream("my-stream", REGION);
|
||||
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
|
||||
stream.setStatusTransitionDeadline(Instant.EPOCH);
|
||||
reader.splitShard("my-stream", stream.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION);
|
||||
|
||||
PersistentStorage<String, KinesisStream> updated = new PersistentStorage<>(path, type);
|
||||
updated.load();
|
||||
KinesisStream restored = updated.get(REGION + "::my-stream").orElseThrow();
|
||||
assertEquals("UPDATING", restored.getStreamStatus(clock.instant()));
|
||||
restored.setStatusTransitionDeadline(Instant.EPOCH);
|
||||
assertEquals("ACTIVE", restored.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creatingStatusUsesTheServiceClockAfterPersistentStorageReload() {
|
||||
MutableClock clock = new MutableClock();
|
||||
Path path = tempDir.resolve("kinesis-creating-status.json");
|
||||
TypeReference<Map<String, KinesisStream>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, KinesisStream> original = new PersistentStorage<>(path, type);
|
||||
KinesisService writer = new KinesisService(original, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 60_000, 0);
|
||||
writer.createStream("my-stream", 1, REGION);
|
||||
|
||||
PersistentStorage<String, KinesisStream> reloaded = new PersistentStorage<>(path, type);
|
||||
reloaded.load();
|
||||
KinesisStream restored = reloaded.get(REGION + "::my-stream").orElseThrow();
|
||||
assertEquals("CREATING", restored.getStreamStatus(clock.instant()));
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
assertEquals("ACTIVE", restored.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamModeDeadlineSurvivesPersistentStorageReload() {
|
||||
Clock clock = Clock.systemUTC();
|
||||
Path path = tempDir.resolve("kinesis-mode-status.json");
|
||||
TypeReference<Map<String, KinesisStream>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, KinesisStream> original = new PersistentStorage<>(path, type);
|
||||
KinesisService service = new KinesisService(original, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 60_000);
|
||||
service.createStream("my-stream", 1, REGION);
|
||||
service.updateStreamMode("my-stream", "ON_DEMAND", REGION);
|
||||
|
||||
PersistentStorage<String, KinesisStream> reloaded = new PersistentStorage<>(path, type);
|
||||
reloaded.load();
|
||||
KinesisStream restored = reloaded.get(REGION + "::my-stream").orElseThrow();
|
||||
assertEquals("ON_DEMAND", restored.getStreamMode());
|
||||
assertEquals("UPDATING", restored.getStreamStatus(clock.instant()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptionWindowBlocksAnotherControlPlaneChangeButNotOtherStreams() {
|
||||
MutableClock clock = new MutableClock();
|
||||
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), clock, 0, 2_000);
|
||||
KinesisStream first = service.createStream("first", 1, REGION);
|
||||
KinesisStream second = service.createStream("second", 1, REGION);
|
||||
|
||||
service.startStreamEncryption("first", "KMS", "alias/aws/kinesis", REGION);
|
||||
assertEquals("UPDATING", first.getStreamStatus(clock.instant()));
|
||||
assertEquals("ACTIVE", second.getStreamStatus(clock.instant()));
|
||||
AwsException busy = assertThrows(AwsException.class,
|
||||
() -> service.stopStreamEncryption("first", REGION));
|
||||
assertEquals("ResourceInUseException", busy.getErrorCode());
|
||||
service.splitShard("second", second.getShards().getFirst().getShardId(),
|
||||
"170141183460469231731687303715884105728", REGION);
|
||||
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.stopStreamEncryption("first", REGION);
|
||||
assertEquals("UPDATING", first.getStreamStatus(clock.instant()));
|
||||
assertEquals("NONE", first.getEncryptionType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShardCountScalesUpToDouble() {
|
||||
kinesisService.createStream("my-stream", 2, REGION);
|
||||
@@ -1122,6 +1584,50 @@ class KinesisServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
private abstract static class ParkedShard extends KinesisShard {
|
||||
final CountDownLatch parked = new CountDownLatch(1);
|
||||
final CountDownLatch release = new CountDownLatch(1);
|
||||
|
||||
ParkedShard(KinesisShard shard) {
|
||||
super(shard.getShardId(), shard.getHashKeyRange().startingHashKey(),
|
||||
shard.getHashKeyRange().endingHashKey(),
|
||||
shard.getSequenceNumberRange().startingSequenceNumber());
|
||||
}
|
||||
|
||||
final void parkAndWait() {
|
||||
parked.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ParkOnCloseShard extends ParkedShard {
|
||||
ParkOnCloseShard(KinesisShard shard) {
|
||||
super(shard);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setClosed(boolean closed) {
|
||||
parkAndWait();
|
||||
super.setClosed(closed);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ParkOnRangeNormalizationShard extends ParkedShard {
|
||||
ParkOnRangeNormalizationShard(KinesisShard shard) {
|
||||
super(shard);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHashKeyRange(HashKeyRange range) {
|
||||
parkAndWait();
|
||||
super.setHashKeyRange(range);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A store that parks the first {@code get} after {@link #arm()} until released.
|
||||
*
|
||||
@@ -1499,4 +2005,44 @@ class KinesisServiceTest {
|
||||
private static List<String> recordData(List<KinesisRecord> records) {
|
||||
return records.stream().map(r -> new String(r.getData(), StandardCharsets.UTF_8)).toList();
|
||||
}
|
||||
|
||||
private static final class AdvancingStore extends InMemoryStorage<String, KinesisStream> {
|
||||
private final MutableClock clock;
|
||||
private int putsUntilAdvance;
|
||||
private int putCount;
|
||||
private boolean failNextPut;
|
||||
|
||||
private AdvancingStore(MutableClock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
private void advanceNextPut() {
|
||||
advanceNthPut(1);
|
||||
}
|
||||
|
||||
private void advanceNthPut(int puts) {
|
||||
putsUntilAdvance = puts;
|
||||
}
|
||||
|
||||
private int putCount() {
|
||||
return putCount;
|
||||
}
|
||||
|
||||
private void failNextPut() {
|
||||
failNextPut = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void put(String key, KinesisStream stream) {
|
||||
super.put(key, stream);
|
||||
putCount++;
|
||||
if (failNextPut) {
|
||||
failNextPut = false;
|
||||
throw new IllegalStateException("simulated storage failure");
|
||||
}
|
||||
if (putsUntilAdvance > 0 && --putsUntilAdvance == 0) {
|
||||
clock.advance(Duration.ofSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package io.floci.aws.services.kinesis;
|
||||
|
||||
import io.floci.aws.services.kinesis.model.KinesisStream;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(KinesisStatusWindowIntegrationTest.WindowProfile.class)
|
||||
class KinesisStatusWindowIntegrationTest {
|
||||
|
||||
private static final String KINESIS_TARGET = "Kinesis_20131202";
|
||||
private static final String STREAM_NAME = "kinesis-status-window-test";
|
||||
|
||||
@Inject
|
||||
KinesisService service;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStreamReportsCreatingUntilItsConfiguredDeadline() {
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "CreateStream",
|
||||
"{\"StreamName\":\"" + STREAM_NAME + "\",\"ShardCount\":1}")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
cleanup.register(() -> RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DeleteStream",
|
||||
"{\"StreamName\":\"" + STREAM_NAME + "\"}")
|
||||
.then().statusCode(200));
|
||||
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DescribeStream",
|
||||
"{\"StreamName\":\"" + STREAM_NAME + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("StreamDescription.StreamStatus", equalTo("CREATING"));
|
||||
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DescribeStreamSummary",
|
||||
"{\"StreamName\":\"" + STREAM_NAME + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("StreamDescriptionSummary.StreamStatus", equalTo("CREATING"));
|
||||
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "SplitShard",
|
||||
"{\"StreamName\":\"" + STREAM_NAME
|
||||
+ "\",\"ShardToSplit\":\"shardId-000000000000\","
|
||||
+ "\"NewStartingHashKey\":\"170141183460469231731687303715884105728\"}")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ResourceInUseException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStreamModeReportsUpdatingThenActiveOnTheWire() {
|
||||
String name = STREAM_NAME + "-update";
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "CreateStream",
|
||||
"{\"StreamName\":\"" + name + "\",\"ShardCount\":1}")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
cleanup.register(() -> RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DeleteStream",
|
||||
"{\"StreamName\":\"" + name + "\"}")
|
||||
.then().statusCode(200));
|
||||
|
||||
KinesisStream stream = service.describeStream(name, "us-east-1");
|
||||
stream.setStatusTransitionDeadline(Instant.EPOCH);
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "UpdateStreamMode",
|
||||
"{\"StreamARN\":\"" + stream.getStreamArn()
|
||||
+ "\",\"StreamModeDetails\":{\"StreamMode\":\"ON_DEMAND\"}}")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DescribeStreamSummary",
|
||||
"{\"StreamName\":\"" + name + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("StreamDescriptionSummary.StreamStatus", equalTo("UPDATING"));
|
||||
|
||||
stream.setStatusTransitionDeadline(Instant.EPOCH);
|
||||
RestAssuredJsonUtils.awsAction(KINESIS_TARGET, "DescribeStream",
|
||||
"{\"StreamName\":\"" + name + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("StreamDescription.StreamStatus", equalTo("ACTIVE"));
|
||||
}
|
||||
|
||||
public static final class WindowProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.kinesis.creating-delay-millis", "60000",
|
||||
"floci.services.kinesis.updating-delay-millis", "60000");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user