diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 22e0f0f4b5..1f93c5e7f6 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -308,6 +308,8 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_KINESIS_ENABLED` | `true` | Enable the Kinesis Data Streams service | +| `FLOCI_SERVICES_KINESIS_CREATING_DELAY_MILLIS` | `0` | Optional `CREATING` status window after stream creation | +| `FLOCI_SERVICES_KINESIS_UPDATING_DELAY_MILLIS` | `0` | Optional `UPDATING` status window after a stream change | ### Firehose diff --git a/docs/services/kinesis.md b/docs/services/kinesis.md index f93a26caa0..351ee54c9f 100644 --- a/docs/services/kinesis.md +++ b/docs/services/kinesis.md @@ -117,6 +117,19 @@ child ranges or records. ## Shard Scaling (UpdateShardCount) +Stream creation and control-plane updates normally report `ACTIVE` immediately. Set +`FLOCI_SERVICES_KINESIS_CREATING_DELAY_MILLIS` or +`FLOCI_SERVICES_KINESIS_UPDATING_DELAY_MILLIS` to test clients that wait for a stream +to become active or retry a conflicting update. During a `CREATING` window, +`PutRecord` and `PutRecords` reject writes until the stream becomes active. During an +`UPDATING` window, reads and record writes remain available, but another split, +merge, scaling, mode, size, encryption, retention, or stream-tag change returns +`ResourceInUseException`. Tag and retention changes also reject a `CREATING` stream. +The window is evaluated on +read from a stored deadline set when the change begins, so a slow synchronous write +can consume some or all of a very small window before the call returns. Resharding +does not defer the shard change. + `UpdateShardCount` enforces the documented default limits: at most double the current open shard count per call, at most ten calls per rolling 24-hour period per stream, a 10000-shard ceiling, and the asymmetric rule that a stream already above 10000 shards can @@ -138,6 +151,8 @@ action, so that limit is intentionally unenforced here. | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_KINESIS_ENABLED` | `true` | Enable or disable the service | +| `FLOCI_SERVICES_KINESIS_CREATING_DELAY_MILLIS` | `0` | Optional `CREATING` status window after `CreateStream` | +| `FLOCI_SERVICES_KINESIS_UPDATING_DELAY_MILLIS` | `0` | Optional `UPDATING` status window after a stream change | | `FLOCI_SERVICES_KINESIS_LIST_SHARDS_NEXT_TOKEN_TTL_MILLIS` | `300000` | Lifetime of `ListShards` and `ListStreams` `NextToken` values in milliseconds. Lower it to exercise `ExpiredNextTokenException` without waiting | ## Enhanced Fan-Out (EFO) diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 42e5941ca6..405d70fdbc 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2290,6 +2290,12 @@ public interface EmulatorConfig { @WithDefault("true") boolean enabled(); + @WithDefault("0") + long creatingDelayMillis(); + + @WithDefault("0") + long updatingDelayMillis(); + /** * Lifetime of ListShards and ListStreams NextTokens, in milliseconds. Defaults to 300000; * lowering it lets tests exercise the expiry path without waiting. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisioner.java index a469bc2899..b19cc4f5d5 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisioner.java @@ -92,8 +92,15 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner { KinesisStream stream = sameNameExistingResource(priorPhysicalId, name, n -> kinesisService.describeStream(n, ctx.region())); if (stream != null) { - kinesisService.updateStreamMode(name, - streamMode != null ? streamMode : DEFAULT_STREAM_MODE, ctx.region()); + String desiredMode = streamMode != null ? streamMode : DEFAULT_STREAM_MODE; + KinesisService.validateStreamMode(desiredMode); + Map existingTags = kinesisService.listTagsForStream(name, ctx.region()); + List tagsToRemove = existingTags.keySet().stream() + .filter(key -> !tags.containsKey(key)) + .toList(); + Map remainingTags = new LinkedHashMap<>(existingTags); + tagsToRemove.forEach(remainingTags::remove); + KinesisService.validateTagCapacity(remainingTags, tags); if (retention != null) { if (retention > stream.getRetentionPeriodHours()) { kinesisService.increaseStreamRetentionPeriod(name, retention, ctx.region()); @@ -101,25 +108,18 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner { kinesisService.decreaseStreamRetentionPeriod(name, retention, ctx.region()); } } - Map existingTags = kinesisService.listTagsForStream(name, ctx.region()); - List tagsToRemove = existingTags.keySet().stream() - .filter(key -> !tags.containsKey(key)) - .toList(); if (!tagsToRemove.isEmpty()) { kinesisService.removeTagsFromStream(name, tagsToRemove, ctx.region()); } - if (!tags.isEmpty()) { + if (!tags.isEmpty() && !existingTags.equals(tags)) { kinesisService.addTagsToStream(name, tags, ctx.region()); } + if (!desiredMode.equals(stream.getStreamMode())) { + kinesisService.updateStreamMode(name, desiredMode, ctx.region()); + } stream = kinesisService.describeStream(name, ctx.region()); } else { - stream = kinesisService.createStream(name, shardCount, streamMode, ctx.region()); - if (retention != null) { - stream.setRetentionPeriodHours(retention); - } - if (!tags.isEmpty()) { - stream.getTags().putAll(tags); - } + stream = kinesisService.createStream(name, shardCount, streamMode, null, tags, retention, ctx.region()); deleteRenamedResource(priorPhysicalId, name, id -> kinesisService.deleteStream(id, ctx.region()), "Kinesis stream"); } diff --git a/src/main/java/io/floci/aws/services/kinesis/KinesisInspectionController.java b/src/main/java/io/floci/aws/services/kinesis/KinesisInspectionController.java index 48b1416118..bff0dc212d 100644 --- a/src/main/java/io/floci/aws/services/kinesis/KinesisInspectionController.java +++ b/src/main/java/io/floci/aws/services/kinesis/KinesisInspectionController.java @@ -91,7 +91,7 @@ public class KinesisInspectionController { ObjectNode node = objectMapper.createObjectNode(); node.put("StreamName", stream.getStreamName()); node.put("StreamARN", stream.getStreamArn()); - node.put("StreamStatus", stream.getStreamStatus()); + node.put("StreamStatus", kinesisService.streamStatus(stream)); node.put("StreamMode", stream.getStreamMode()); node.put("RetentionPeriodHours", stream.getRetentionPeriodHours()); node.put("EncryptionType", stream.getEncryptionType()); diff --git a/src/main/java/io/floci/aws/services/kinesis/KinesisJsonHandler.java b/src/main/java/io/floci/aws/services/kinesis/KinesisJsonHandler.java index 264ab48a0e..ea70f78b22 100644 --- a/src/main/java/io/floci/aws/services/kinesis/KinesisJsonHandler.java +++ b/src/main/java/io/floci/aws/services/kinesis/KinesisJsonHandler.java @@ -145,10 +145,7 @@ public class KinesisJsonHandler { // request instead of leaving an untagged stream behind. Map tags = parseTags(request); service.createStream(streamName, shardCount, streamMode, - optionalMaxRecordSize(request), region); - if (!tags.isEmpty()) { - service.addTagsToStream(streamName, tags, region); - } + optionalMaxRecordSize(request), tags, region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -240,7 +237,7 @@ public class KinesisJsonHandler { ObjectNode summary = summaries.addObject(); summary.put("StreamName", stream.getStreamName()); summary.put("StreamARN", stream.getStreamArn()); - summary.put("StreamStatus", stream.getStreamStatus()); + summary.put("StreamStatus", service.streamStatus(stream)); addStreamModeDetailsNode(summary, stream); summary.put("StreamCreationTimestamp", epochSeconds(stream.getStreamCreationTimestamp())); } @@ -275,7 +272,7 @@ public class KinesisJsonHandler { ObjectNode desc = response.putObject("StreamDescription"); desc.put("StreamName", stream.getStreamName()); desc.put("StreamARN", stream.getStreamArn()); - desc.put("StreamStatus", stream.getStreamStatus()); + desc.put("StreamStatus", service.streamStatus(stream)); desc.put("HasMoreShards", false); desc.put("RetentionPeriodHours", stream.getRetentionPeriodHours()); desc.put("StreamCreationTimestamp", epochSeconds(stream.getStreamCreationTimestamp())); @@ -317,7 +314,7 @@ public class KinesisJsonHandler { ObjectNode summary = response.putObject("StreamDescriptionSummary"); summary.put("StreamName", stream.getStreamName()); summary.put("StreamARN", stream.getStreamArn()); - summary.put("StreamStatus", stream.getStreamStatus()); + summary.put("StreamStatus", service.streamStatus(stream)); summary.put("RetentionPeriodHours", stream.getRetentionPeriodHours()); summary.put("StreamCreationTimestamp", epochSeconds(stream.getStreamCreationTimestamp())); summary.put("OpenShardCount", (int) stream.getShards().stream().filter(s -> !s.isClosed()).count()); @@ -609,6 +606,7 @@ public class KinesisJsonHandler { KinesisStream stream = service.describeStream(streamName, region); JsonNode recordsNode = request.path("Records"); service.validateRecordCount(recordsNode.size()); + service.requireWritableStream(stream); // An oversized record fails the whole request before anything is // written — per-record ErrorCode is reserved for throughput/internal diff --git a/src/main/java/io/floci/aws/services/kinesis/KinesisService.java b/src/main/java/io/floci/aws/services/kinesis/KinesisService.java index c6231e57a7..49882da9b7 100644 --- a/src/main/java/io/floci/aws/services/kinesis/KinesisService.java +++ b/src/main/java/io/floci/aws/services/kinesis/KinesisService.java @@ -1,6 +1,7 @@ package io.floci.aws.services.kinesis; import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Digests; @@ -77,6 +78,8 @@ public class KinesisService implements ResourceProvider { private final StorageBackend consumerStore; private final RegionResolver regionResolver; private final Clock clock; + private final long creatingDelayMillis; + private final long updatingDelayMillis; private final AtomicLong sequenceGenerator = new AtomicLong(System.currentTimeMillis()); // One monitor per stream key, handed out by lockFor. Serializes sequence allocation + shard // append + persist so the in-memory log, the assigned sequence order and the WAL write order @@ -95,6 +98,16 @@ public class KinesisService implements ResourceProvider { Runnable putRecordBeforeLockHook = () -> {}; @Inject + public KinesisService(StorageFactory factory, RegionResolver regionResolver, EmulatorConfig config) { + this(factory.create("kinesis", "kinesis-streams.json", + new TypeReference>() {}), + factory.create("kinesis", "kinesis-consumers.json", + new TypeReference>() {}), + regionResolver, Clock.systemUTC(), + config.services().kinesis().creatingDelayMillis(), + config.services().kinesis().updatingDelayMillis()); + } + public KinesisService(StorageFactory factory, RegionResolver regionResolver) { this(factory.create("kinesis", "kinesis-streams.json", new TypeReference>() {}), @@ -117,10 +130,54 @@ public class KinesisService implements ResourceProvider { KinesisService(StorageBackend store, StorageBackend consumerStore, RegionResolver regionResolver, Clock clock) { + this(store, consumerStore, regionResolver, clock, 0, 0); + } + + KinesisService(StorageBackend store, + StorageBackend consumerStore, + RegionResolver regionResolver, Clock clock, + long creatingDelayMillis, long updatingDelayMillis) { + if (creatingDelayMillis < 0 || updatingDelayMillis < 0) { + throw new IllegalArgumentException("Kinesis status delays must be non-negative"); + } this.store = store; this.consumerStore = consumerStore; this.regionResolver = regionResolver; this.clock = clock; + this.creatingDelayMillis = creatingDelayMillis; + this.updatingDelayMillis = updatingDelayMillis; + } + + private void requireActive(KinesisStream stream) { + String status = streamStatus(stream); + if (!"ACTIVE".equals(status)) { + throw new AwsException("ResourceInUseException", + "Stream " + stream.getStreamName() + " is not ACTIVE (current state: " + status + ")", 400); + } + } + + String streamStatus(KinesisStream stream) { + return stream.getStreamStatus(clock.instant()); + } + + void requireWritableStream(KinesisStream stream) { + String status = streamStatus(stream); + if (!"ACTIVE".equals(status) && !"UPDATING".equals(status)) { + throw new AwsException("ResourceNotFoundException", + "Stream " + stream.getStreamName() + " is not ready (current state: " + status + ")", 400); + } + } + + private void enterStatusWindow(KinesisStream stream, String status, long delayMillis) { + if (delayMillis == 0) { + stream.setStatusWindow("ACTIVE", null); + } else { + stream.setStatusWindow(status, clock.instant().plusMillis(delayMillis)); + } + } + + private void beginStatusUpdate(KinesisStream stream) { + enterStatusWindow(stream, "UPDATING", updatingDelayMillis); } public KinesisStream createStream(String streamName, int shardCount, String region) { @@ -138,24 +195,42 @@ public class KinesisService implements ResourceProvider { */ public KinesisStream createStream(String streamName, int shardCount, String streamMode, Integer maxRecordSizeInKiB, String region) { + return createStream(streamName, shardCount, streamMode, maxRecordSizeInKiB, Map.of(), region); + } + + public KinesisStream createStream(String streamName, int shardCount, String streamMode, + Integer maxRecordSizeInKiB, Map tags, String region) { + return createStream(streamName, shardCount, streamMode, maxRecordSizeInKiB, tags, null, region); + } + + public KinesisStream createStream(String streamName, int shardCount, String streamMode, + Integer maxRecordSizeInKiB, Map tags, + Integer retentionPeriodHours, String region) { String resolvedMode = streamMode != null ? streamMode : DEFAULT_STREAM_MODE; - if (!VALID_STREAM_MODES.contains(resolvedMode)) { - throw new AwsException("InvalidArgumentException", - "StreamMode must be PROVISIONED or ON_DEMAND, got: " + resolvedMode, 400); - } + validateStreamMode(resolvedMode); if (maxRecordSizeInKiB != null) { validateMaxRecordSize(maxRecordSizeInKiB, "InvalidArgumentException"); } + if (retentionPeriodHours != null && (retentionPeriodHours < 24 || retentionPeriodHours > 8760)) { + throw new AwsException("InvalidArgumentException", + "Retention period must be between 24 and 8760 hours", 400); + } String storageKey = regionKey(region, streamName); if (store.get(storageKey).isPresent()) { throw new AwsException("ResourceInUseException", "Stream already exists: " + streamName, 400); } + validateTagCapacity(Map.of(), tags); String arn = regionResolver.buildArn("kinesis", region, "stream/" + streamName); KinesisStream stream = new KinesisStream(streamName, arn); stream.setAccountId(regionResolver.getAccountId()); stream.setStreamMode(resolvedMode); + stream.getTags().putAll(tags); + if (retentionPeriodHours != null) { + stream.setRetentionPeriodHours(retentionPeriodHours); + } + enterStatusWindow(stream, "CREATING", creatingDelayMillis); if (maxRecordSizeInKiB != null) { stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB); } @@ -175,29 +250,31 @@ public class KinesisService implements ResourceProvider { } public void updateStreamMode(String streamName, String streamMode, String region) { - if (streamMode == null || !VALID_STREAM_MODES.contains(streamMode)) { - throw new AwsException("InvalidArgumentException", - "StreamMode must be PROVISIONED or ON_DEMAND, got: " + streamMode, 400); - } + validateStreamMode(streamMode); String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = resolveStream(streamName, region); - if (!"ACTIVE".equals(stream.getStreamStatus())) { - throw new AwsException("ResourceInUseException", - "Stream " + streamName + " is not ACTIVE (current state: " + stream.getStreamStatus() + ")", 400); - } + requireActive(stream); // Same-mode is a no-op. Mirrors the same-value behaviour in // increase/decreaseStreamRetentionPeriod (see #342). Avoids breaking // terraform-provider-aws which calls UpdateStreamMode on every refresh. if (streamMode.equals(stream.getStreamMode())) { return; } + beginStatusUpdate(stream); stream.setStreamMode(streamMode); store.put(key, stream); LOG.infov("Updated stream mode for {0} to {1}", streamName, streamMode); } } + public static void validateStreamMode(String streamMode) { + if (streamMode == null || !VALID_STREAM_MODES.contains(streamMode)) { + throw new AwsException("InvalidArgumentException", + "StreamMode must be PROVISIONED or ON_DEMAND, got: " + streamMode, 400); + } + } + public List listStreamDetails(String region) { String prefix = region + "::"; return store.scan(key -> key.startsWith(prefix)).stream() @@ -290,6 +367,7 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = resolveStream(streamName, region); + requireActive(stream); validateTagCapacity(stream.getTags(), tags); stream.getTags().putAll(tags); store.put(key, stream); @@ -300,6 +378,7 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = resolveStream(streamName, region); + requireActive(stream); tagKeys.forEach(stream.getTags()::remove); store.put(key, stream); } @@ -324,6 +403,7 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = describeStreamByArn(resourceArn, region); + requireActive(stream); validateResourceTagLimit(stream.getTags(), tags); stream.getTags().putAll(tags); store.put(key, stream); @@ -344,6 +424,7 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = describeStreamByArn(resourceArn, region); + requireActive(stream); tagKeys.forEach(stream.getTags()::remove); store.put(key, stream); } @@ -394,7 +475,7 @@ public class KinesisService implements ResourceProvider { validateTagCapacity(current, added); } - private static void validateTagCapacity(Map current, Map added) { + public static void validateTagCapacity(Map current, Map added) { Set keys = new HashSet<>(current.keySet()); keys.addAll(added.keySet()); if (keys.size() > 50 && added.keySet().stream().anyMatch(key -> !current.containsKey(key))) { @@ -406,6 +487,8 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = resolveStream(streamName, region); + requireActive(stream); + beginStatusUpdate(stream); stream.setEncryptionType(encryptionType); stream.setKeyId(keyId); store.put(key, stream); @@ -433,6 +516,7 @@ public class KinesisService implements ResourceProvider { if (retentionPeriodHours == stream.getRetentionPeriodHours()) { return; } + requireActive(stream); stream.setRetentionPeriodHours(retentionPeriodHours); store.put(key, stream); LOG.infov("Increased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours); @@ -457,6 +541,7 @@ public class KinesisService implements ResourceProvider { if (retentionPeriodHours == stream.getRetentionPeriodHours()) { return; } + requireActive(stream); stream.setRetentionPeriodHours(retentionPeriodHours); store.put(key, stream); LOG.infov("Decreased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours); @@ -513,6 +598,8 @@ public class KinesisService implements ResourceProvider { String key = regionKey(region, streamName); synchronized (lockFor(key)) { KinesisStream stream = resolveStream(streamName, region); + requireActive(stream); + beginStatusUpdate(stream); stream.setEncryptionType("NONE"); stream.setKeyId(null); store.put(key, stream); @@ -520,6 +607,11 @@ public class KinesisService implements ResourceProvider { } public void splitShard(String streamName, String shardId, String newStartingHashKey, String region) { + splitShard(streamName, shardId, newStartingHashKey, region, false); + } + + private void splitShard(String streamName, String shardId, String newStartingHashKey, + String region, boolean fromShardCountUpdate) { String key = regionKey(region, streamName); // Share the producer critical section so a split can't race an append: selectShard runs // under the same lock, so a producer never appends to a parent a completed split has closed. @@ -527,6 +619,9 @@ public class KinesisService implements ResourceProvider { // Resolve under the lock so a concurrent deleteStream (same monitor) cannot leave us // mutating and re-persisting a stale, deleted instance. KinesisStream stream = resolveStream(streamName, region); + if (!fromShardCountUpdate) { + requireActive(stream); + } KinesisShard parent = stream.getShards().stream() .filter(s -> s.getShardId().equals(shardId)) .findFirst() @@ -545,24 +640,21 @@ public class KinesisService implements ResourceProvider { throw new AwsException("InvalidArgumentException", "NewStartingHashKey must be inside the parent shard's hash range.", 400); } + String start = parentRange.startingHashKey(); + String end = parentRange.endingHashKey(); + String leftEnd = subtractOne(newStartingHashKey); + if (!fromShardCountUpdate) { + beginStatusUpdate(stream); + } normalizeOpenShardRanges(stream, legacyOpenShards); - parent.setClosed(true); parent.setSequenceNumberRange(new KinesisShard.SequenceNumberRange( parent.getSequenceNumberRange().startingSequenceNumber(), String.valueOf(sequenceGenerator.get()))); - String start = parent.getHashKeyRange().startingHashKey(); - String end = parent.getHashKeyRange().endingHashKey(); - - // Derive both child ids from the base size WITHOUT relying on the first add: nextShardId - // is size-based, so two sequential adds would either collide (both ids computed pre-add) - // or expose a half-published topology (child1 visible before child2). Compute base+0 and - // base+1 up front so the ids stay distinct, then publish BOTH children in one atomic - // CopyOnWriteArrayList.addAll, so a lock-free reader can never observe {parent, child1} - // without child2. + // Publish both children in one addAll, so lock-free readers never see only one. int base = stream.getShards().size(); - KinesisShard child1 = new KinesisShard(String.format("shardId-%012d", base), start, subtractOne(newStartingHashKey), String.valueOf(sequenceGenerator.get())); + KinesisShard child1 = new KinesisShard(String.format("shardId-%012d", base), start, leftEnd, String.valueOf(sequenceGenerator.get())); child1.setParentShardId(shardId); KinesisShard child2 = new KinesisShard(String.format("shardId-%012d", base + 1), newStartingHashKey, end, String.valueOf(sequenceGenerator.get())); @@ -575,11 +667,19 @@ public class KinesisService implements ResourceProvider { } public void mergeShards(String streamName, String shardId, String adjacentShardId, String region) { + mergeShards(streamName, shardId, adjacentShardId, region, false); + } + + private void mergeShards(String streamName, String shardId, String adjacentShardId, + String region, boolean fromShardCountUpdate) { String key = regionKey(region, streamName); synchronized (lockFor(key)) { // Resolve under the lock so a concurrent deleteStream (same monitor) cannot leave us // mutating and re-persisting a stale, deleted instance. KinesisStream stream = resolveStream(streamName, region); + if (!fromShardCountUpdate) { + requireActive(stream); + } KinesisShard shard1 = stream.getShards().stream() .filter(s -> s.getShardId().equals(shardId)) .findFirst() @@ -602,23 +702,18 @@ public class KinesisService implements ResourceProvider { if (!end1.add(BigInteger.ONE).equals(start2) && !end2.add(BigInteger.ONE).equals(start1)) { throw new AwsException("InvalidArgumentException", "Shards must have adjacent hash ranges.", 400); } + String start = start1.min(start2).toString(); + String end = end1.max(end2).toString(); + if (!fromShardCountUpdate) { + beginStatusUpdate(stream); + } normalizeOpenShardRanges(stream, legacyOpenShards); - shard1.setClosed(true); shard2.setClosed(true); String seq = String.valueOf(sequenceGenerator.get()); shard1.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard1.getSequenceNumberRange().startingSequenceNumber(), seq)); shard2.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard2.getSequenceNumberRange().startingSequenceNumber(), seq)); - // Combine the adjacent hash ranges. - BigInteger s1Start = new BigInteger(shard1.getHashKeyRange().startingHashKey()); - BigInteger s2Start = new BigInteger(shard2.getHashKeyRange().startingHashKey()); - - String start = s1Start.min(s2Start).toString(); - BigInteger s1End = new BigInteger(shard1.getHashKeyRange().endingHashKey()); - BigInteger s2End = new BigInteger(shard2.getHashKeyRange().endingHashKey()); - String end = s1End.max(s2End).toString(); - KinesisShard child = new KinesisShard(nextShardId(stream), start, end, seq); child.setParentShardId(shardId); child.setAdjacentParentShardId(adjacentShardId); @@ -667,18 +762,15 @@ public class KinesisService implements ResourceProvider { "UpdateShardCount is only supported for data streams with the provisioned capacity mode.", 400); } - if (!"ACTIVE".equals(stream.getStreamStatus())) { - throw new AwsException("ResourceInUseException", - "Stream " + streamName + " is not ACTIVE (current state: " + stream.getStreamStatus() + ")", 400); - } + requireActive(stream); currentOpenShardCount = (int) stream.getShards().stream().filter(s -> !s.isClosed()).count(); validateTargetShardCount(streamName, currentOpenShardCount, targetShardCount); List updateTimestamps = nextShardCountUpdateTimestamps(stream); + beginStatusUpdate(stream); normalizeOpenShardRanges(stream); stream.setShardCountUpdateTimestamps(updateTimestamps); store.put(key, stream); - applyUniformScaling(streamName, stream, currentOpenShardCount, targetShardCount, region); return new UpdateShardCountResult(streamName, stream.getStreamArn(), currentOpenShardCount, targetShardCount); @@ -750,7 +842,7 @@ public class KinesisService implements ResourceProvider { .limit(splitsNeeded) .toList(); for (KinesisShard parent : splitCandidates) { - splitShard(streamName, parent.getShardId(), midpointHashKey(parent.getHashKeyRange()), region); + splitShard(streamName, parent.getShardId(), midpointHashKey(parent.getHashKeyRange()), region, true); } } else if (targetShardCount < currentOpenShardCount) { int mergesNeeded = currentOpenShardCount - targetShardCount; @@ -764,7 +856,7 @@ public class KinesisService implements ResourceProvider { int[] pair = narrowestFirstDisjointPairs.get(i); KinesisShard shard1 = openByHashKey.get(pair[0]); KinesisShard shard2 = openByHashKey.get(pair[1]); - mergeShards(streamName, shard1.getShardId(), shard2.getShardId(), region); + mergeShards(streamName, shard1.getShardId(), shard2.getShardId(), region, true); } } } @@ -870,11 +962,8 @@ public class KinesisService implements ResourceProvider { "UpdateMaxRecordSize is only supported for data streams with the provisioned capacity mode.", 400); } - if (!"ACTIVE".equals(stream.getStreamStatus())) { - throw new AwsException("ResourceInUseException", - "Stream " + streamName + " is not ACTIVE (current state: " - + stream.getStreamStatus() + ")", 400); - } + requireActive(stream); + beginStatusUpdate(stream); stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB); store.put(key, stream); LOG.infov("Updated max record size for {0} to {1} KiB", streamName, maxRecordSizeInKiB); @@ -929,9 +1018,10 @@ public class KinesisService implements ResourceProvider { // deleted before we get here is absent and this fails like any other missing stream rather // than appending to a stale instance and resurrecting it. KinesisStream current = resolveStreamForAccountMigrating(accountId, streamName, region); - // Ordered exactly as before this moved under the monitor: a missing stream still reports - // ResourceNotFoundException ahead of an invalid ExplicitHashKey, and the size check runs - // against the same lock-protected instance that shard selection and the append use. + requireWritableStream(current); + // A missing or not-yet-active stream reports ResourceNotFoundException ahead of an + // invalid ExplicitHashKey. Size validation runs against the same lock-protected instance + // that shard selection and the append use. validateExplicitHashKey(explicitHashKey); validateRecordSize(current, data, partitionKey); KinesisShard shard = selectShard(current, partitionKey, explicitHashKey); diff --git a/src/main/java/io/floci/aws/services/kinesis/model/KinesisStream.java b/src/main/java/io/floci/aws/services/kinesis/model/KinesisStream.java index c7af5cb8cb..a0c6f9a93e 100644 --- a/src/main/java/io/floci/aws/services/kinesis/model/KinesisStream.java +++ b/src/main/java/io/floci/aws/services/kinesis/model/KinesisStream.java @@ -1,6 +1,8 @@ package io.floci.aws.services.kinesis.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; @@ -18,7 +20,9 @@ public class KinesisStream { private String streamName; private String streamArn; private String accountId; + @JsonProperty("streamStatus") private String streamStatus; + private Instant statusTransitionDeadline; private volatile List shards = new CopyOnWriteArrayList<>(); private int retentionPeriodHours = 24; private Instant streamCreationTimestamp; @@ -53,8 +57,23 @@ public class KinesisStream { public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } - public String getStreamStatus() { return streamStatus; } - public void setStreamStatus(String streamStatus) { this.streamStatus = streamStatus; } + @JsonIgnore + public String getStreamStatus() { return getStreamStatus(Instant.now()); } + public synchronized String getStreamStatus(Instant now) { + return statusTransitionDeadline != null && !now.isBefore(statusTransitionDeadline) + ? "ACTIVE" : streamStatus; + } + public synchronized void setStreamStatus(String streamStatus) { this.streamStatus = streamStatus; } + + public synchronized Instant getStatusTransitionDeadline() { return statusTransitionDeadline; } + public synchronized void setStatusTransitionDeadline(Instant statusTransitionDeadline) { + this.statusTransitionDeadline = statusTransitionDeadline; + } + + public synchronized void setStatusWindow(String status, Instant deadline) { + this.streamStatus = status; + this.statusTransitionDeadline = deadline; + } public List getShards() { return shards; } public void setShards(List shards) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index cde83b0c01..e6a51d8b29 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -663,6 +663,8 @@ floci: rotation-tick-seconds: 60 kinesis: enabled: true + creating-delay-millis: 0 + updating-delay-millis: 0 list-shards-next-token-ttl-millis: 300000 firehose: enabled: true diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java index d504aee290..fb674a7b4a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java @@ -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 existingTags = new LinkedHashMap<>(); + Map 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> 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()); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java index 3ace1997c1..8b770b0434 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisCfnServiceTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisCfnServiceTest.java new file mode 100644 index 0000000000..8f84c3a9e5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisCfnServiceTest.java @@ -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> type = new TypeReference<>() {}; + PersistentStorage 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 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)); + } +} diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java index 78e95dd4ee..e76c6fc095 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java @@ -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"); diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java index af2208567c..b4f617a8b5 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java @@ -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 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 streamTagMutations() { + String arn = "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream"; + return Stream.of( + Arguments.of("AddTagsToStream", (Consumer) service -> + service.addTagsToStream("my-stream", Map.of("env", "prod"), REGION)), + Arguments.of("RemoveTagsFromStream", (Consumer) service -> + service.removeTagsFromStream("my-stream", List.of("env"), REGION)), + Arguments.of("TagResource", (Consumer) service -> + service.tagResource(arn, Map.of("env", "prod"), REGION)), + Arguments.of("UntagResource", (Consumer) 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> type = new TypeReference<>() {}; + PersistentStorage 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 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 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> type = new TypeReference<>() {}; + PersistentStorage 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 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> type = new TypeReference<>() {}; + PersistentStorage 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 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 recordData(List records) { return records.stream().map(r -> new String(r.getData(), StandardCharsets.UTF_8)).toList(); } + + private static final class AdvancingStore extends InMemoryStorage { + 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)); + } + } + } } diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisStatusWindowIntegrationTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisStatusWindowIntegrationTest.java new file mode 100644 index 0000000000..089022a48d --- /dev/null +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisStatusWindowIntegrationTest.java @@ -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 getConfigOverrides() { + return Map.of("floci.services.kinesis.creating-delay-millis", "60000", + "floci.services.kinesis.updating-delay-millis", "60000"); + } + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index db6b11eabd..ad67c2284b 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -292,6 +292,8 @@ floci: default-recovery-window-days: 30 kinesis: enabled: true + creating-delay-millis: 0 + updating-delay-millis: 0 list-shards-next-token-ttl-millis: 300000 firehose: enabled: true