diff --git a/docs/services/kinesis.md b/docs/services/kinesis.md index 6a048d9ad7..f93a26caa0 100644 --- a/docs/services/kinesis.md +++ b/docs/services/kinesis.md @@ -107,13 +107,13 @@ A stream's retention period (default 24 hours, `IncreaseStreamRetentionPeriod`/` value must be a decimal integer in the Kinesis hash-key space, and records are written to the open shard whose `HashKeyRange` contains that value. -Without `ExplicitHashKey`, Floci uses the partition key's Java hash modulo the -number of stored shards, including closed shards. If this selects a closed -shard, it follows split and merge lineage through any closed intermediate shards -to the first open descendant in breadth-first, stored-shard order. Writes never -append to a closed shard or fall back to an unrelated open shard. A lineage with -no reachable open shard fails the write. This simplified ordinary-key placement -differs from AWS's MD5 hash-range routing. +Without `ExplicitHashKey`, Kinesis takes the MD5 digest of the partition key's +UTF-8 bytes as an unsigned 128-bit integer. Floci writes to the open shard whose +`HashKeyRange` contains that value, including after a split or merge. Closed +historical shards are never selected. Untouched legacy streams whose open root +shards all persisted the full hash span are repartitioned before selection. +Other overlapping stored ranges are rejected rather than rewriting existing +child ranges or records. ## Shard Scaling (UpdateShardCount) 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 47e6f53ce0..c6231e57a7 100644 --- a/src/main/java/io/floci/aws/services/kinesis/KinesisService.java +++ b/src/main/java/io/floci/aws/services/kinesis/KinesisService.java @@ -3,6 +3,7 @@ package io.floci.aws.services.kinesis; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; @@ -23,17 +24,17 @@ import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Base64; +import java.util.Collections; import java.util.Comparator; -import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; +import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; @@ -81,6 +82,9 @@ public class KinesisService implements ResourceProvider { // append + persist so the in-memory log, the assigned sequence order and the WAL write order // all agree, and serializes every other read-modify-write on a stream against deleteStream. private final ConcurrentHashMap streamAppendLocks = new ConcurrentHashMap<>(); + // Stream objects are replaced on reload; weak keys avoid retaining deleted streams. + private final Map> openShardRangeIndexes = + Collections.synchronizedMap(new WeakHashMap<>()); // Package-private test seam, run inside the append critical section after the sequence is // allocated and before the record is appended. Default no-op in production. Runnable putRecordAppendHook = () -> {}; @@ -532,6 +536,17 @@ public class KinesisService implements ResourceProvider { throw new AwsException("InvalidArgumentException", "Shard " + shardId + " is already closed", 400); } + List legacyOpenShards = legacyOpenShardsToNormalize(stream); + KinesisShard.HashKeyRange parentRange = effectiveOpenShardRange(parent, legacyOpenShards); + BigInteger splitPoint = new BigInteger(newStartingHashKey); + BigInteger parentStart = new BigInteger(parentRange.startingHashKey()); + BigInteger parentEnd = new BigInteger(parentRange.endingHashKey()); + if (splitPoint.compareTo(parentStart) <= 0 || splitPoint.compareTo(parentEnd) > 0) { + throw new AwsException("InvalidArgumentException", + "NewStartingHashKey must be inside the parent shard's hash range.", 400); + } + normalizeOpenShardRanges(stream, legacyOpenShards); + parent.setClosed(true); parent.setSequenceNumberRange(new KinesisShard.SequenceNumberRange( parent.getSequenceNumberRange().startingSequenceNumber(), @@ -577,6 +592,17 @@ public class KinesisService implements ResourceProvider { if (shard1.isClosed() || shard2.isClosed()) { throw new AwsException("InvalidArgumentException", "One or both shards are already closed", 400); } + List legacyOpenShards = legacyOpenShardsToNormalize(stream); + KinesisShard.HashKeyRange range1 = effectiveOpenShardRange(shard1, legacyOpenShards); + KinesisShard.HashKeyRange range2 = effectiveOpenShardRange(shard2, legacyOpenShards); + BigInteger start1 = new BigInteger(range1.startingHashKey()); + BigInteger end1 = new BigInteger(range1.endingHashKey()); + BigInteger start2 = new BigInteger(range2.startingHashKey()); + BigInteger end2 = new BigInteger(range2.endingHashKey()); + if (!end1.add(BigInteger.ONE).equals(start2) && !end2.add(BigInteger.ONE).equals(start1)) { + throw new AwsException("InvalidArgumentException", "Shards must have adjacent hash ranges.", 400); + } + normalizeOpenShardRanges(stream, legacyOpenShards); shard1.setClosed(true); shard2.setClosed(true); @@ -584,7 +610,7 @@ public class KinesisService implements ResourceProvider { shard1.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard1.getSequenceNumberRange().startingSequenceNumber(), seq)); shard2.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard2.getSequenceNumberRange().startingSequenceNumber(), seq)); - // Combine hash ranges (assuming they are adjacent) + // Combine the adjacent hash ranges. BigInteger s1Start = new BigInteger(shard1.getHashKeyRange().startingHashKey()); BigInteger s2Start = new BigInteger(shard2.getHashKeyRange().startingHashKey()); @@ -648,7 +674,10 @@ public class KinesisService implements ResourceProvider { currentOpenShardCount = (int) stream.getShards().stream().filter(s -> !s.isClosed()).count(); validateTargetShardCount(streamName, currentOpenShardCount, targetShardCount); - recordShardCountUpdate(stream, key); + List updateTimestamps = nextShardCountUpdateTimestamps(stream); + normalizeOpenShardRanges(stream); + stream.setShardCountUpdateTimestamps(updateTimestamps); + store.put(key, stream); applyUniformScaling(streamName, stream, currentOpenShardCount, targetShardCount, region); @@ -690,7 +719,7 @@ public class KinesisService implements ResourceProvider { } /** Enforces the "no more than ten UpdateShardCount calls per rolling 24 hours" default limit. */ - private void recordShardCountUpdate(KinesisStream stream, String storageKey) { + private List nextShardCountUpdateTimestamps(KinesisStream stream) { Instant now = Instant.now(); Instant windowStart = now.minus(SHARD_COUNT_UPDATE_WINDOW); List recent = new ArrayList<>(stream.getShardCountUpdateTimestamps().stream() @@ -702,8 +731,7 @@ public class KinesisService implements ResourceProvider { + MAX_SHARD_COUNT_UPDATES_PER_DAY + " times in the past 24 hours.", 400); } recent.add(now); - stream.setShardCountUpdateTimestamps(recent); - store.put(storageKey, stream); + return recent; } /** @@ -1340,85 +1368,88 @@ public class KinesisService implements ResourceProvider { } private KinesisShard selectShard(KinesisStream stream, String partitionKey, String explicitHashKey) { - if (explicitHashKey != null) { + List ranges = openShardRangeIndexes.get(stream); + if (ranges == null) { normalizeOpenShardRanges(stream); - return selectShardByExplicitHashKey(stream, explicitHashKey); + ranges = stream.getShards().stream() + .filter(shard -> !shard.isClosed()) + .map(shard -> new OpenShardRange(shard, + new BigInteger(shard.getHashKeyRange().startingHashKey()), + new BigInteger(shard.getHashKeyRange().endingHashKey()))) + .sorted(Comparator.comparing(OpenShardRange::start)) + .toList(); + openShardRangeIndexes.put(stream, ranges); } + BigInteger hashKey = explicitHashKey != null ? parseExplicitHashKey(explicitHashKey) + : new BigInteger(1, Digests.md5(partitionKey.getBytes(StandardCharsets.UTF_8))); + return selectShardByHashKey(ranges, hashKey); + } - // Preserve ordinary-key placement, then resolve historical parents to an open descendant. - // The producer holds the stream lock, shared with splitShard and mergeShards. - List shards = stream.getShards(); - int index = (int) (Math.abs((long) partitionKey.hashCode()) % shards.size()); - KinesisShard selected = shards.get(index); - if (!selected.isClosed()) { - return selected; - } - - List snapshot = List.copyOf(shards); - Map> children = new HashMap<>(); - for (KinesisShard shard : snapshot) { - if (shard.getParentShardId() != null) { - children.computeIfAbsent(shard.getParentShardId(), ignored -> new ArrayList<>()).add(shard); - } - if (shard.getAdjacentParentShardId() != null) { - children.computeIfAbsent(shard.getAdjacentParentShardId(), ignored -> new ArrayList<>()).add(shard); - } - } - Deque pending = new ArrayDeque<>(); - Set visited = new HashSet<>(); - pending.add(selected); - visited.add(selected.getShardId()); - while (!pending.isEmpty()) { - KinesisShard shard = pending.removeFirst(); - if (!shard.isClosed()) { - return shard; - } - for (KinesisShard child : children.getOrDefault(shard.getShardId(), List.of())) { - if (visited.add(child.getShardId())) { - pending.addLast(child); - } + private KinesisShard selectShardByHashKey(List ranges, BigInteger hashKey) { + int low = 0; + int high = ranges.size() - 1; + while (low <= high) { + int middle = (low + high) >>> 1; + OpenShardRange range = ranges.get(middle); + if (hashKey.compareTo(range.start()) < 0) { + high = middle - 1; + } else if (hashKey.compareTo(range.end()) > 0) { + low = middle + 1; + } else if (!range.shard().isClosed()) { + return range.shard(); + } else { + break; } } throw new AwsException("InvalidArgumentException", - "Selected shard " + selected.getShardId() + " has no open descendant.", 400); + "ExplicitHashKey does not map to an open shard.", 400); } - private KinesisShard selectShardByExplicitHashKey(KinesisStream stream, String explicitHashKey) { - BigInteger hashKey = parseExplicitHashKey(explicitHashKey); - return stream.getShards().stream() - .filter(shard -> !shard.isClosed()) - .filter(shard -> containsHashKey(shard, hashKey)) - .findFirst() - .orElseThrow(() -> new AwsException("InvalidArgumentException", - "ExplicitHashKey does not map to an open shard.", 400)); + private record OpenShardRange(KinesisShard shard, BigInteger start, BigInteger end) {} + + // Only untouched legacy streams can be evenly repartitioned. Repartitioning a stream that + // already has split/merge children would silently change those children's persisted ranges. + private void normalizeOpenShardRanges(KinesisStream stream) { + normalizeOpenShardRanges(stream, legacyOpenShardsToNormalize(stream)); } - private static boolean containsHashKey(KinesisShard shard, BigInteger hashKey) { - BigInteger start = new BigInteger(shard.getHashKeyRange().startingHashKey()); - BigInteger end = new BigInteger(shard.getHashKeyRange().endingHashKey()); - return hashKey.compareTo(start) >= 0 && hashKey.compareTo(end) <= 0; + private void normalizeOpenShardRanges(KinesisStream stream, List legacyOpenShards) { + openShardRangeIndexes.remove(stream); + int openShardCount = legacyOpenShards.size(); + for (int i = 0; i < openShardCount; i++) { + legacyOpenShards.get(i).setHashKeyRange(new KinesisShard.HashKeyRange( + shardStartingHashKey(i, openShardCount), + shardEndingHashKey(i, openShardCount))); + } } - // Streams created before explicit-hash routing persisted the same full-span range on every - // shard, so an explicit key matches all open shards and first-match routing collapses onto - // shardId-...000. Repartition those legacy overlapping open shards into the disjoint ranges a - // freshly created stream would have, ordered by shard id, so explicit routing is correct after - // an upgrade without recreating the stream. Already-disjoint open shards (new streams, split or - // merged streams) are left untouched. The caller persists the mutated stream under its lock. - private static void normalizeOpenShardRanges(KinesisStream stream) { + private static KinesisShard.HashKeyRange effectiveOpenShardRange( + KinesisShard shard, List legacyOpenShards) { + if (legacyOpenShards.isEmpty()) { + return shard.getHashKeyRange(); + } + int index = legacyOpenShards.indexOf(shard); + return new KinesisShard.HashKeyRange( + shardStartingHashKey(index, legacyOpenShards.size()), + shardEndingHashKey(index, legacyOpenShards.size())); + } + + private static List legacyOpenShardsToNormalize(KinesisStream stream) { List openShards = stream.getShards().stream() .filter(shard -> !shard.isClosed()) .sorted(Comparator.comparing(KinesisShard::getShardId)) .toList(); if (openShards.size() <= 1 || openShardRangesDisjoint(openShards)) { - return; + return List.of(); } - int openShardCount = openShards.size(); - for (int i = 0; i < openShardCount; i++) { - openShards.get(i).setHashKeyRange(new KinesisShard.HashKeyRange( - shardStartingHashKey(i, openShardCount), - shardEndingHashKey(i, openShardCount))); + if (openShards.stream().anyMatch(shard -> shard.getParentShardId() != null + || shard.getAdjacentParentShardId() != null + || !MIN_HASH_KEY_VALUE.equals(shard.getHashKeyRange().startingHashKey()) + || !MAX_HASH_KEY.toString().equals(shard.getHashKeyRange().endingHashKey()))) { + throw new AwsException("InvalidArgumentException", + "Overlapping open shard hash ranges cannot be normalized safely.", 400); } + return openShards; } private static boolean openShardRangesDisjoint(List openShards) { diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisClosedShardRoutingServiceTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisClosedShardRoutingServiceTest.java index 1b5d934a67..3d527fafdd 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisClosedShardRoutingServiceTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisClosedShardRoutingServiceTest.java @@ -12,6 +12,8 @@ import org.junit.jupiter.params.provider.ValueSource; import java.math.BigInteger; import java.time.Duration; +import java.time.Instant; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -33,7 +35,7 @@ class KinesisClosedShardRoutingServiceTest { } @Test - void putRecordFollowsAnOpenSplitChild() { + void putRecordSelectsAnOpenSplitChildByHash() { KinesisStream stream = service.createStream(STREAM, 1, REGION); service.putRecord(STREAM, DATA, "c", REGION); split(stream.getShards().getFirst()); @@ -42,55 +44,230 @@ class KinesisClosedShardRoutingServiceTest { } @Test - void putRecordTraversesClosedSplitChildren() { + void splitMigratesLegacyRangesBeforeDerivingChildRanges() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + BigInteger half = BigInteger.ONE.shiftLeft(127); + BigInteger quarter = BigInteger.ONE.shiftLeft(126); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + + service.splitShard(STREAM, stream.getShards().getFirst().getShardId(), quarter.toString(), REGION); + + assertEquals(new KinesisShard.HashKeyRange("0", half.subtract(BigInteger.ONE).toString()), + stream.getShards().get(0).getHashKeyRange()); + assertEquals(new KinesisShard.HashKeyRange(half.toString(), max), + stream.getShards().get(1).getHashKeyRange()); + assertEquals(new KinesisShard.HashKeyRange("0", quarter.subtract(BigInteger.ONE).toString()), + stream.getShards().get(2).getHashKeyRange()); + assertEquals(new KinesisShard.HashKeyRange(quarter.toString(), half.subtract(BigInteger.ONE).toString()), + stream.getShards().get(3).getHashKeyRange()); + assertOpenDestinationAndUnchangedClosedRecords(stream, "c", stream.getShards().get(3)); + } + + @Test + void invalidLegacySplitDoesNotChangeShardRanges() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + String outsideNormalizedParent = BigInteger.ONE.shiftLeft(127) + .add(BigInteger.ONE.shiftLeft(126)).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + + AwsException error = assertThrows(AwsException.class, + () -> service.splitShard(STREAM, stream.getShards().getFirst().getShardId(), + outsideNormalizedParent, REGION)); + + assertEquals("InvalidArgumentException", error.getErrorCode()); + assertEquals(2, stream.getShards().size()); + assertTrue(stream.getShards().stream().allMatch(shard -> + new KinesisShard.HashKeyRange("0", max).equals(shard.getHashKeyRange()))); + } + + @Test + void mergeMigratesLegacyRangesBeforeDerivingChildRange() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + BigInteger half = BigInteger.ONE.shiftLeft(127); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + + service.mergeShards(STREAM, stream.getShards().get(0).getShardId(), + stream.getShards().get(1).getShardId(), REGION); + + assertEquals(new KinesisShard.HashKeyRange("0", half.subtract(BigInteger.ONE).toString()), + stream.getShards().get(0).getHashKeyRange()); + assertEquals(new KinesisShard.HashKeyRange(half.toString(), max), + stream.getShards().get(1).getHashKeyRange()); + assertEquals(new KinesisShard.HashKeyRange("0", max), stream.getShards().get(2).getHashKeyRange()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void nonAdjacentMergeDoesNotChangeShardTopology(boolean legacyRanges) { + KinesisStream stream = service.createStream(STREAM, 3, REGION); + if (legacyRanges) { + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + } + List before = stream.getShards().stream() + .map(KinesisShard::getHashKeyRange).toList(); + + AwsException error = assertThrows(AwsException.class, + () -> service.mergeShards(STREAM, stream.getShards().get(0).getShardId(), + stream.getShards().get(2).getShardId(), REGION)); + + assertEquals("InvalidArgumentException", error.getErrorCode()); + assertEquals(3, stream.getShards().size()); + assertTrue(stream.getShards().stream().noneMatch(KinesisShard::isClosed)); + assertEquals(before, stream.getShards().stream().map(KinesisShard::getHashKeyRange).toList()); + service.putRecordWithShardId(STREAM, DATA, "c", REGION); + } + + @Test + void updateShardCountMigratesLegacyRangesBeforeChoosingSplits() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + + service.updateShardCount(STREAM, 4, "UNIFORM_SCALING", REGION); + + List open = stream.getShards().stream().filter(shard -> !shard.isClosed()) + .sorted((left, right) -> new BigInteger(left.getHashKeyRange().startingHashKey()) + .compareTo(new BigInteger(right.getHashKeyRange().startingHashKey()))) + .toList(); + assertEquals(4, open.size()); + assertEquals("0", open.getFirst().getHashKeyRange().startingHashKey()); + assertEquals(max, open.getLast().getHashKeyRange().endingHashKey()); + for (int i = 1; i < open.size(); i++) { + assertEquals(new BigInteger(open.get(i - 1).getHashKeyRange().endingHashKey()).add(BigInteger.ONE), + new BigInteger(open.get(i).getHashKeyRange().startingHashKey())); + } + } + + @Test + void updateShardCountLimitDoesNotNormalizeLegacyRanges() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().forEach(shard -> + shard.setHashKeyRange(new KinesisShard.HashKeyRange("0", max))); + List history = Collections.nCopies(10, Instant.now()); + stream.setShardCountUpdateTimestamps(history); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateShardCount(STREAM, 4, "UNIFORM_SCALING", REGION)); + + assertEquals("LimitExceededException", error.getErrorCode()); + assertTrue(stream.getShards().stream().allMatch(shard -> + new KinesisShard.HashKeyRange("0", max).equals(shard.getHashKeyRange()))); + assertEquals(history, stream.getShardCountUpdateTimestamps()); + } + + @Test + void alreadyReshardedLegacyOverlapDoesNotRewriteChildRanges() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + String quarter = BigInteger.ONE.shiftLeft(126).toString(); + service.splitShard(STREAM, stream.getShards().getFirst().getShardId(), quarter, REGION); + stream.getShards().get(0).setHashKeyRange(new KinesisShard.HashKeyRange("0", max)); + stream.getShards().get(1).setHashKeyRange(new KinesisShard.HashKeyRange("0", max)); + stream.getShards().get(3).setHashKeyRange(new KinesisShard.HashKeyRange(quarter, max)); + List before = stream.getShards().stream() + .map(KinesisShard::getHashKeyRange).toList(); + + AwsException error = assertThrows(AwsException.class, + () -> service.putRecordWithShardId(STREAM, DATA, "c", REGION)); + + assertEquals("InvalidArgumentException", error.getErrorCode()); + assertEquals(before, stream.getShards().stream().map(KinesisShard::getHashKeyRange).toList()); + assertTrue(stream.getShards().stream().allMatch(shard -> shard.recordCount() == 0)); + + AwsException scalingError = assertThrows(AwsException.class, + () -> service.updateShardCount(STREAM, 4, "UNIFORM_SCALING", REGION)); + assertEquals("InvalidArgumentException", scalingError.getErrorCode()); + assertTrue(stream.getShardCountUpdateTimestamps().isEmpty()); + } + + @Test + void partiallyOverlappingRootRangesAreNotRepartitioned() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + String max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).toString(); + stream.getShards().get(1).setHashKeyRange(new KinesisShard.HashKeyRange("0", max)); + List before = stream.getShards().stream() + .map(KinesisShard::getHashKeyRange).toList(); + + AwsException error = assertThrows(AwsException.class, + () -> service.putRecordWithShardId(STREAM, DATA, "c", REGION)); + + assertEquals("InvalidArgumentException", error.getErrorCode()); + assertEquals(before, stream.getShards().stream().map(KinesisShard::getHashKeyRange).toList()); + assertTrue(stream.getShards().stream().allMatch(shard -> shard.recordCount() == 0)); + } + + @Test + void putRecordRoutesToOpenRangeAfterRepeatedSplits() { KinesisStream stream = splitTwoGenerations(); - // "b" hashes to 98, selecting the original parent at index zero modulo seven. - assertOpenDestinationAndUnchangedClosedRecords(stream, "b", stream.getShards().get(3)); + assertOpenDestinationAndUnchangedClosedRecords(stream, "b", stream.getShards().get(5)); } @ParameterizedTest @ValueSource(ints = {1, 2}) - void putRecordPrefersAnOpenDirectChildOverADeeperDescendant(int closedChildIndex) { + void putRecordFindsHashRangeAcrossUnevenSplitDepth(int closedChildIndex) { KinesisStream stream = service.createStream(STREAM, 1, REGION); split(stream.getShards().getFirst()); split(stream.getShards().get(closedChildIndex)); - // "d" selects the root modulo five, with one direct child still open. - assertOpenDestinationAndUnchangedClosedRecords(stream, "d", stream.getShards().get(3 - closedChildIndex)); + KinesisShard expected = stream.getShards().get(closedChildIndex == 1 ? 2 : 3); + assertOpenDestinationAndUnchangedClosedRecords(stream, "d", expected); } @ParameterizedTest - @ValueSource(strings = {"d", "e"}) - void putRecordTraversesEitherMergeParentThenAClosedChild(String partitionKey) { + @ValueSource(strings = {"a", "b"}) + void putRecordRoutesAcrossMergedThenSplitRange(String partitionKey) { KinesisStream stream = service.createStream(STREAM, 2, REGION); service.mergeShards(STREAM, stream.getShards().get(0).getShardId(), stream.getShards().get(1).getShardId(), REGION); split(stream.getShards().get(2)); - // With five stored shards, these keys select each original merge parent. - assertOpenDestinationAndUnchangedClosedRecords(stream, partitionKey, stream.getShards().get(3)); + KinesisShard expected = stream.getShards().get("a".equals(partitionKey) ? 3 : 4); + assertOpenDestinationAndUnchangedClosedRecords(stream, partitionKey, expected); } @Test - void putRecordTraversesSplitThenMergeThenSplit() { + void cachedRoutingRebuildsAfterMerge() { + KinesisStream stream = service.createStream(STREAM, 2, REGION); + service.putRecordWithShardId(STREAM, DATA, "a", "0", REGION); + service.mergeShards(STREAM, stream.getShards().get(0).getShardId(), + stream.getShards().get(1).getShardId(), REGION); + + KinesisService.PutRecordResult result = service.putRecordWithShardId(STREAM, DATA, "b", "0", REGION); + + assertEquals(stream.getShards().get(2).getShardId(), result.shardId()); + assertEquals(1, stream.getShards().get(0).recordCount()); + assertEquals(1, stream.getShards().get(2).recordCount()); + } + + @Test + void putRecordRoutesAcrossSplitThenMergeThenSplit() { KinesisStream stream = service.createStream(STREAM, 1, REGION); split(stream.getShards().getFirst()); service.mergeShards(STREAM, stream.getShards().get(1).getShardId(), stream.getShards().get(2).getShardId(), REGION); split(stream.getShards().get(3)); - assertOpenDestinationAndUnchangedClosedRecords(stream, "f", stream.getShards().get(4)); + assertOpenDestinationAndUnchangedClosedRecords(stream, "f", stream.getShards().get(5)); } @Test - void putRecordUsesAReachableChildInsteadOfAnEarlierUnrelatedOpenShard() { + void putRecordSelectsSplitChildInsteadOfUnrelatedOpenShard() { KinesisStream stream = service.createStream(STREAM, 2, REGION); service.putRecordWithShardId(STREAM, DATA, "d", "0", REGION); split(stream.getShards().getFirst()); - // "d" selects the closed parent modulo four; shard one is unrelated and open. - assertOpenDestinationAndUnchangedClosedRecords(stream, "d", stream.getShards().get(2)); + assertOpenDestinationAndUnchangedClosedRecords(stream, "a", stream.getShards().get(2)); assertEquals(1, stream.getShards().get(0).recordCount()); assertEquals(0, stream.getShards().get(1).recordCount()); @@ -98,11 +275,11 @@ class KinesisClosedShardRoutingServiceTest { } @Test - void putRecordRejectsAClosedShardWithoutDescendants() { + void putRecordRejectsWhenNoOpenShardCoversHash() { KinesisStream stream = service.createStream(STREAM, 1, REGION); stream.getShards().getFirst().setClosed(true); - assertNoDestination(stream, "b"); + assertNoDestination(stream, "a"); } @Test @@ -110,11 +287,11 @@ class KinesisClosedShardRoutingServiceTest { KinesisStream stream = service.createStream(STREAM, 2, REGION); stream.getShards().getFirst().setClosed(true); - assertNoDestination(stream, "b"); + assertNoDestination(stream, "a"); } @Test - void putRecordRejectsACycleWithoutHangingOrAppending() { + void putRecordRejectsNoOpenShardDespiteLineageCycle() { KinesisStream stream = service.createStream(STREAM, 2, REGION); KinesisShard first = stream.getShards().get(0); KinesisShard second = stream.getShards().get(1); @@ -143,7 +320,7 @@ class KinesisClosedShardRoutingServiceTest { } @Test - void explicitAccountProducerAlsoTraversesClosedDescendants() { + void explicitAccountProducerAlsoRoutesToAnOpenHashRange() { KinesisStream stream = splitTwoGenerations(); String sequence = service.putRecordForAccount("000000000000", STREAM, DATA, "b", REGION); diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisIntegrationTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisIntegrationTest.java index 10902bd38a..33835083e9 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisIntegrationTest.java @@ -671,7 +671,7 @@ class KinesisIntegrationTest { .when().post("/").then().statusCode(200); Set reported = new HashSet<>(); - // Probe enough partition keys that hash(pk) % 2 hits both shards. With 50 keys the + // Probe enough partition-key MD5 values to cover both shard ranges. With 50 keys the // odds of single-shard routing are ~1 in 2^49, so this is effectively deterministic. for (int i = 0; i < 50 && reported.size() < 2; i++) { String pk = "pk-" + i; @@ -863,7 +863,7 @@ class KinesisIntegrationTest { @Test @Order(46) - void putRecordPreservesShardForNegativeHashCode() { + void putRecordUsesMd5RangeForPreviouslyNegativeJavaHashCode() { given() .header("X-Amz-Target", "Kinesis_20131202.CreateStream") .contentType(KINESIS_CONTENT_TYPE) @@ -882,7 +882,7 @@ class KinesisIntegrationTest { .post("/") .then() .statusCode(200) - .body("ShardId", equalTo("shardId-000000000002")); + .body("ShardId", equalTo("shardId-000000000001")); } // --- AT_TIMESTAMP iterator coverage --- 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 fead0018fa..78e95dd4ee 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisJsonHandlerTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; @@ -28,6 +29,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; @@ -406,7 +408,7 @@ class KinesisJsonHandlerTest { @ParameterizedTest @ValueSource(strings = {"PutRecord", "PutRecords"}) - void writesReportAnOpenDescendantAfterRepeatedSplits(String action) { + void writesReportTheOpenHashRangeAfterRepeatedSplits(String action) { createStream("test-stream"); KinesisStream stream = service.describeStream("test-stream", REGION); service.splitShard("test-stream", FIRST_SHARD_ID, @@ -422,19 +424,19 @@ class KinesisJsonHandlerTest { ObjectNode response = responseEntity(handler.handle(action, request, REGION)); JsonNode result = "PutRecords".equals(action) ? response.path("Records").get(0) : response; - assertEquals(stream.getShards().get(3).getShardId(), result.path("ShardId").asText()); + assertEquals(stream.getShards().get(5).getShardId(), result.path("ShardId").asText()); assertFalse(result.path("SequenceNumber").asText().isEmpty()); if ("PutRecords".equals(action)) { assertEquals(0, response.path("FailedRecordCount").asInt()); } - assertEquals(1, stream.getShards().get(3).recordCount()); + assertEquals(1, stream.getShards().get(5).recordCount()); assertTrue(stream.getShards().stream().filter(KinesisShard::isClosed) .allMatch(shard -> shard.recordCount() == 0)); } @ParameterizedTest @ValueSource(strings = {"PutRecord", "PutRecords"}) - void writesFailWithoutAppendingWhenNoOpenDescendantExists(String action) { + void writesFailWithoutAppendingWhenNoOpenShardCoversHash(String action) { createStream("test-stream"); KinesisShard shard = service.describeStream("test-stream", REGION).getShards().getFirst(); shard.setClosed(true); @@ -1010,6 +1012,94 @@ class KinesisJsonHandlerTest { assertEquals(FIRST_SHARD_ID, respMin.get("ShardId").asText()); } + @Test + void ordinaryPartitionKeysUseMd5HashRangesReportedByListShards() { + createStream("md5-routing", TWO_SHARDS); + ObjectNode list = MAPPER.createObjectNode().put("StreamName", "md5-routing"); + ArrayNode shards = (ArrayNode) responseEntity(handler.handle("ListShards", list, REGION)).get("Shards"); + + ObjectNode put = MAPPER.createObjectNode() + .put("StreamName", "md5-routing") + .put("Data", "dGVzdA==") + .put("PartitionKey", "pk-0"); + String singleShard = responseEntity(handler.handle("PutRecord", put, REGION)).get("ShardId").asText(); + assertEquals(shardForMd5Hash(shards, "EFFC8E8920E4EE5505B7F963C5D72F6D"), singleShard); + + ObjectNode batch = MAPPER.createObjectNode().put("StreamName", "md5-routing"); + ArrayNode records = batch.putArray("Records"); + records.addObject().put("Data", "dGVzdA==").put("PartitionKey", "a"); + records.addObject().put("Data", "dGVzdA==").put("PartitionKey", "b"); + records.addObject().put("Data", "dGVzdA==").put("PartitionKey", "é-0"); + ArrayNode results = (ArrayNode) responseEntity(handler.handle("PutRecords", batch, REGION)).get("Records"); + assertEquals(shardForMd5Hash(shards, "0CC175B9C0F1B6A831C399E269772661"), + results.get(0).get("ShardId").asText()); + assertEquals(shardForMd5Hash(shards, "92EB5FFEE6AE2FEC3AD71C777531578F"), + results.get(1).get("ShardId").asText()); + assertEquals(shardForMd5Hash(shards, "2F6923E2AAC1CFC8729E5C892BBE2244"), + results.get(2).get("ShardId").asText()); + } + + @Test + void ordinaryPartitionKeyNormalizesLegacyOverlappingShardRanges() { + createStream("legacy-md5-routing", TWO_SHARDS); + KinesisStream stream = service.describeStream("legacy-md5-routing", REGION); + for (KinesisShard shard : stream.getShards()) { + shard.setHashKeyRange(new KinesisShard.HashKeyRange(MIN_HASH_KEY, MAX_HASH_KEY)); + } + + ObjectNode put = MAPPER.createObjectNode() + .put("StreamName", "legacy-md5-routing") + .put("Data", "dGVzdA==") + .put("PartitionKey", "pk-0"); + assertEquals(SECOND_SHARD_ID, + responseEntity(handler.handle("PutRecord", put, REGION)).get("ShardId").asText()); + assertEquals(MIN_HASH_KEY, stream.getShards().getFirst().getHashKeyRange().startingHashKey()); + assertEquals(MAX_HASH_KEY, stream.getShards().get(1).getHashKeyRange().endingHashKey()); + } + + @Test + void putRecordsDoesNotRescanEveryShardForEachEntry() { + KinesisStream stream = service.createStream("indexed-routing", 256, REGION); + AtomicInteger rangeReads = new AtomicInteger(); + List counted = new ArrayList<>(); + for (KinesisShard shard : stream.getShards()) { + counted.add(new KinesisShard(shard.getShardId(), + shard.getHashKeyRange().startingHashKey(), shard.getHashKeyRange().endingHashKey(), + shard.getSequenceNumberRange().startingSequenceNumber()) { + @Override + public HashKeyRange getHashKeyRange() { + rangeReads.incrementAndGet(); + return super.getHashKeyRange(); + } + }); + } + stream.setShards(counted); + + ObjectNode batch = MAPPER.createObjectNode().put("StreamName", "indexed-routing"); + ArrayNode records = batch.putArray("Records"); + for (int i = 0; i < 100; i++) { + records.addObject().put("Data", "dGVzdA==").put("PartitionKey", "pk-" + i); + } + + ObjectNode result = responseEntity(handler.handle("PutRecords", batch, REGION)); + + assertEquals(0, result.path("FailedRecordCount").asInt()); + assertEquals(100, result.path("Records").size()); + assertTrue(rangeReads.get() < 8_000, () -> "Shard range reads: " + rangeReads.get()); + } + + private static String shardForMd5Hash(ArrayNode shards, String md5Hex) { + BigInteger hash = new BigInteger(md5Hex, 16); + for (JsonNode shard : shards) { + BigInteger start = new BigInteger(shard.path("HashKeyRange").path("StartingHashKey").asText()); + BigInteger end = new BigInteger(shard.path("HashKeyRange").path("EndingHashKey").asText()); + if (hash.compareTo(start) >= 0 && hash.compareTo(end) <= 0) { + return shard.path("ShardId").asText(); + } + } + throw new AssertionError("No shard covers MD5 hash " + md5Hex); + } + @Test void putRecordAcceptsRecordAtSizeLimit() { createStream("test-stream"); diff --git a/src/test/java/io/floci/aws/services/kinesis/KinesisListShardsConcurrencyTest.java b/src/test/java/io/floci/aws/services/kinesis/KinesisListShardsConcurrencyTest.java index ea2507a3f8..322070c982 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisListShardsConcurrencyTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisListShardsConcurrencyTest.java @@ -7,6 +7,7 @@ import io.floci.aws.services.kinesis.model.KinesisStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.math.BigInteger; import java.util.List; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -53,8 +54,12 @@ class KinesisListShardsConcurrencyTest { // A concurrent split closes the parent and atomically appends two children, mutating the // live backing list the pre-fix sub-list page still points at. String firstShardId = stream.getShards().getFirst().getShardId(); + KinesisShard.HashKeyRange firstRange = stream.getShards().getFirst().getHashKeyRange(); + String splitPoint = new BigInteger(firstRange.startingHashKey()) + .add(new BigInteger(firstRange.endingHashKey())).add(BigInteger.ONE) + .divide(BigInteger.TWO).toString(); service.splitShard("reshard-stream", firstShardId, - "170141183460469231731687303715884105728", REGION); + splitPoint, REGION); // Pre-fix: iterating/sizing the live sub-list here throws ConcurrentModificationException. assertDoesNotThrow(() -> { 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 12824662c5..af2208567c 100644 --- a/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java +++ b/src/test/java/io/floci/aws/services/kinesis/KinesisServiceTest.java @@ -451,7 +451,11 @@ class KinesisServiceTest { Iterator reader = stream.getShards().iterator(); reader.next(); - kinesisService.splitShard("my-stream", shardId, "170141183460469231731687303715884105728", REGION); + KinesisShard.HashKeyRange firstRange = stream.getShards().getFirst().getHashKeyRange(); + String splitPoint = new BigInteger(firstRange.startingHashKey()) + .add(new BigInteger(firstRange.endingHashKey())).add(BigInteger.ONE) + .divide(BigInteger.TWO).toString(); + kinesisService.splitShard("my-stream", shardId, splitPoint, REGION); // A plain ArrayList iterator throws ConcurrentModificationException here; COWAL keeps reading // its fixed pre-split snapshot.