fix(kinesis): make UpdateShardCount atomic (#8442)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-15 14:01:41 -04:00
1 parent 44dea210a6
commit 055ef5faca
2 files changed
+394 -109

No files matched your search

@@ -609,11 +609,6 @@ 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.
@@ -621,111 +616,125 @@ 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()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
if (parent.isClosed()) {
throw new AwsException("InvalidArgumentException", "Shard " + shardId + " is already closed", 400);
}
List<KinesisShard> 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);
}
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())));
// 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, leftEnd, String.valueOf(sequenceGenerator.get()));
child1.setParentShardId(shardId);
KinesisShard child2 = new KinesisShard(String.format("shardId-%012d", base + 1), newStartingHashKey, end, String.valueOf(sequenceGenerator.get()));
child2.setParentShardId(shardId);
stream.getShards().addAll(List.of(child1, child2));
requireActive(stream);
splitShardOnStream(stream, shardId, newStartingHashKey, () -> beginStatusUpdate(stream));
store.put(key, stream);
LOG.infov("Split shard {0} in stream {1}", shardId, streamName);
}
}
public void mergeShards(String streamName, String shardId, String adjacentShardId, String region) {
mergeShards(streamName, shardId, adjacentShardId, region, false);
private void splitShardOnStream(KinesisStream stream, String shardId, String newStartingHashKey) {
splitShardOnStream(stream, shardId, newStartingHashKey, () -> {});
}
private void mergeShards(String streamName, String shardId, String adjacentShardId,
String region, boolean fromShardCountUpdate) {
private void splitShardOnStream(KinesisStream stream, String shardId, String newStartingHashKey,
Runnable beforeMutation) {
KinesisShard parent = stream.getShards().stream()
.filter(s -> s.getShardId().equals(shardId))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
if (parent.isClosed()) {
throw new AwsException("InvalidArgumentException", "Shard " + shardId + " is already closed", 400);
}
List<KinesisShard> 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);
}
String start = parentRange.startingHashKey();
String end = parentRange.endingHashKey();
String leftEnd = subtractOne(newStartingHashKey);
beforeMutation.run();
normalizeOpenShardRanges(stream, legacyOpenShards);
parent.setClosed(true);
parent.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(
parent.getSequenceNumberRange().startingSequenceNumber(),
String.valueOf(sequenceGenerator.get())));
// 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.
int base = stream.getShards().size();
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()));
child2.setParentShardId(shardId);
stream.getShards().addAll(List.of(child1, child2));
}
public void mergeShards(String streamName, String shardId, String adjacentShardId, String region) {
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()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
KinesisShard shard2 = stream.getShards().stream()
.filter(s -> s.getShardId().equals(adjacentShardId))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + adjacentShardId + " not found", 400));
if (shard1.isClosed() || shard2.isClosed()) {
throw new AwsException("InvalidArgumentException", "One or both shards are already closed", 400);
}
List<KinesisShard> 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);
}
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));
KinesisShard child = new KinesisShard(nextShardId(stream), start, end, seq);
child.setParentShardId(shardId);
child.setAdjacentParentShardId(adjacentShardId);
stream.getShards().add(child);
requireActive(stream);
mergeShardsOnStream(stream, shardId, adjacentShardId, () -> beginStatusUpdate(stream));
store.put(key, stream);
LOG.infov("Merged shards {0} and {1} in stream {2}", shardId, adjacentShardId, streamName);
}
}
private void mergeShardsOnStream(KinesisStream stream, String shardId, String adjacentShardId) {
mergeShardsOnStream(stream, shardId, adjacentShardId, () -> {});
}
private void mergeShardsOnStream(KinesisStream stream, String shardId, String adjacentShardId,
Runnable beforeMutation) {
KinesisShard shard1 = stream.getShards().stream()
.filter(s -> s.getShardId().equals(shardId))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
KinesisShard shard2 = stream.getShards().stream()
.filter(s -> s.getShardId().equals(adjacentShardId))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + adjacentShardId + " not found", 400));
if (shard1.isClosed() || shard2.isClosed()) {
throw new AwsException("InvalidArgumentException", "One or both shards are already closed", 400);
}
List<KinesisShard> 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);
}
String start = start1.min(start2).toString();
String end = end1.max(end2).toString();
beforeMutation.run();
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));
KinesisShard child = new KinesisShard(nextShardId(stream), start, end, seq);
child.setParentShardId(shardId);
child.setAdjacentParentShardId(adjacentShardId);
stream.getShards().add(child);
}
private String nextShardId(KinesisStream stream) {
return String.format("shardId-%012d", stream.getShards().size());
}
@@ -739,10 +748,16 @@ public class KinesisService implements ResourceProvider {
/**
* Reshards a stream to {@code targetShardCount} open shards using uniform scaling: the only
* scaling type AWS documents. Internally this is expressed purely as a sequence of
* {@link #splitShard} and {@link #mergeShards} calls, exactly as real Kinesis performs
* UpdateShardCount as splits or merges on individual shards, so shard lineage
* (parent/adjacent-parent) comes out identical to calling those APIs by hand.
* scaling type AWS documents. The asynchronous status window begins before potentially
* blocking normalization so callers observe the same lifecycle as the individual reshard
* APIs; after normalization, the first persistence write records that status and rolling-window
* marker before topology staging. The topology changes are staged on a separate shard list and
* published with one final storage write after every split or merge validates. The staged list
* reuses existing shard instances, so this protects persisted writes and rollback rather than
* providing a lock-free snapshot to readers of mutable shard objects. The staged
* operations use the same lineage rules as {@link #splitShard} and {@link #mergeShards}, so
* parent and adjacent-parent relationships remain identical to calling those APIs by hand;
* a failed commit restores the original shard state and rolling-window history.
*/
public UpdateShardCountResult updateShardCount(String streamName, int targetShardCount, String scalingType, String region) {
if (!UNIFORM_SCALING.equals(scalingType)) {
@@ -769,16 +784,118 @@ public class KinesisService implements ResourceProvider {
currentOpenShardCount = (int) stream.getShards().stream().filter(s -> !s.isClosed()).count();
validateTargetShardCount(streamName, currentOpenShardCount, targetShardCount);
List<Instant> updateTimestamps = nextShardCountUpdateTimestamps(stream);
beginStatusUpdate(stream);
normalizeOpenShardRanges(stream);
stream.setShardCountUpdateTimestamps(updateTimestamps);
store.put(key, stream);
applyUniformScaling(streamName, stream, currentOpenShardCount, targetShardCount, region);
List<KinesisShard> originalShards = stream.getShards();
List<ShardState> originalShardStates = originalShards.stream()
.map(KinesisService::snapshotShardState)
.toList();
List<Instant> originalTimestamps = stream.getShardCountUpdateTimestamps();
String originalStreamStatus = stream.getStreamStatus(clock.instant());
Instant originalStatusTransitionDeadline = stream.getStatusTransitionDeadline();
boolean writeAttempted = false;
try {
// Publish the asynchronous status transition before the potentially blocking
// range normalization. This preserves the existing Kinesis lifecycle: callers can
// observe UPDATING while the first normalization/split is underway.
beginStatusUpdate(stream);
KinesisStream staged = copyStreamForReshard(stream);
normalizeOpenShardRanges(staged);
stream.setShardCountUpdateTimestamps(updateTimestamps);
staged.setShardCountUpdateTimestamps(updateTimestamps);
writeAttempted = true;
store.put(key, stream);
// Stage the topology on a separate shard-list while retaining the original shard
// instances. Retaining those instances preserves their lifecycle callbacks and
// lets a failed commit restore every mutable field in place for existing callers.
applyUniformScaling(staged, currentOpenShardCount, targetShardCount);
// Preserve the identity of the object returned by create/describe. Several callers
// retain that object and expect a successful reshard to update it in place. The
// stream's volatile shard-list reference is replaced only after staging is done.
copyReshardState(staged, stream);
writeAttempted = true;
store.put(key, stream);
} catch (RuntimeException | Error failure) {
// StorageBackend.put may publish the object before reporting a persistence error.
// Restore the same stream and shard instances so both in-memory callers and a
// backend that retained the reference see the original topology and rolling slot.
originalShardStates.forEach(KinesisService::restoreShardState);
stream.setShards(originalShards);
stream.setShardCountUpdateTimestamps(originalTimestamps);
stream.setStreamStatus(originalStreamStatus);
stream.setStatusTransitionDeadline(originalStatusTransitionDeadline);
openShardRangeIndexes.remove(stream);
if (writeAttempted) {
try {
// PersistentStorage writes through on every put; rewrite the restored value
// when the status or final topology write reached the backend before failing.
store.put(key, stream);
} catch (RuntimeException | Error rollbackFailure) {
failure.addSuppressed(rollbackFailure);
}
}
throw failure;
}
return new UpdateShardCountResult(streamName, stream.getStreamArn(), currentOpenShardCount, targetShardCount);
}
}
private KinesisStream copyStreamForReshard(KinesisStream source) {
KinesisStream copy = new KinesisStream();
copy.setStreamName(source.getStreamName());
copy.setStreamArn(source.getStreamArn());
copy.setAccountId(source.getAccountId());
copy.setStreamStatus(source.getStreamStatus(clock.instant()));
copy.setStatusTransitionDeadline(source.getStatusTransitionDeadline());
copy.setRetentionPeriodHours(source.getRetentionPeriodHours());
copy.setStreamCreationTimestamp(source.getStreamCreationTimestamp());
copy.setTags(source.getTags() == null ? new HashMap<>() : new HashMap<>(source.getTags()));
copy.setEncryptionType(source.getEncryptionType());
copy.setKeyId(source.getKeyId());
copy.setStreamMode(source.getStreamMode());
copy.setEnhancedMonitoringMetrics(source.getEnhancedMonitoringMetrics() == null
? new HashSet<>() : new HashSet<>(source.getEnhancedMonitoringMetrics()));
copy.setMaxRecordSizeInKiB(source.getMaxRecordSizeInKiB());
copy.setShardCountUpdateTimestamps(source.getShardCountUpdateTimestamps() == null
? new ArrayList<>() : new ArrayList<>(source.getShardCountUpdateTimestamps()));
// Keep the original shard instances so status-window and normalization callbacks remain
// observable while the staged stream owns an independent topology list.
copy.setShards(new ArrayList<>(source.getShards()));
return copy;
}
private record ShardState(KinesisShard shard, String parentShardId, String adjacentParentShardId,
KinesisShard.HashKeyRange hashKeyRange,
KinesisShard.SequenceNumberRange sequenceNumberRange, boolean closed,
Instant creationTimestamp) {}
private static ShardState snapshotShardState(KinesisShard shard) {
return new ShardState(shard, shard.getParentShardId(), shard.getAdjacentParentShardId(),
shard.getHashKeyRange(), shard.getSequenceNumberRange(), shard.isClosed(),
shard.getCreationTimestamp());
}
private static void restoreShardState(ShardState state) {
KinesisShard target = state.shard();
target.setParentShardId(state.parentShardId());
target.setAdjacentParentShardId(state.adjacentParentShardId());
target.setHashKeyRange(state.hashKeyRange());
target.setSequenceNumberRange(state.sequenceNumberRange());
target.setClosed(state.closed());
target.setCreationTimestamp(state.creationTimestamp());
}
private void copyReshardState(KinesisStream source, KinesisStream target) {
// The staged stream owns a separate shard-list. Reuse its already-prepared shard objects
// instead of cloning every retained record a second time during publication.
target.setShards(source.getShards());
openShardRangeIndexes.remove(target);
target.setStreamStatus(source.getStreamStatus(clock.instant()));
target.setStatusTransitionDeadline(source.getStatusTransitionDeadline());
target.setShardCountUpdateTimestamps(new ArrayList<>(source.getShardCountUpdateTimestamps()));
}
/**
* Enforces UpdateShardCount's documented default limits. The minimum bound rounds up for an
* odd current shard count ({@code (n + 1) / 2}), so current=5 accepts target=3 but rejects
@@ -814,7 +931,7 @@ public class KinesisService implements ResourceProvider {
/** Enforces the "no more than ten UpdateShardCount calls per rolling 24 hours" default limit. */
private List<Instant> nextShardCountUpdateTimestamps(KinesisStream stream) {
Instant now = Instant.now();
Instant now = clock.instant();
Instant windowStart = now.minus(SHARD_COUNT_UPDATE_WINDOW);
List<Instant> recent = new ArrayList<>(stream.getShardCountUpdateTimestamps().stream()
.filter(t -> t.isAfter(windowStart))
@@ -833,8 +950,7 @@ public class KinesisService implements ResourceProvider {
* or merging the narrowest disjoint adjacent pairs (scale down), so the resulting topology
* stays as close to equal-width as the existing shard layout allows.
*/
private void applyUniformScaling(String streamName, KinesisStream stream,
int currentOpenShardCount, int targetShardCount, String region) {
private void applyUniformScaling(KinesisStream stream, int currentOpenShardCount, int targetShardCount) {
if (targetShardCount > currentOpenShardCount) {
int splitsNeeded = targetShardCount - currentOpenShardCount;
List<KinesisShard> splitCandidates = stream.getShards().stream()
@@ -844,7 +960,7 @@ public class KinesisService implements ResourceProvider {
.limit(splitsNeeded)
.toList();
for (KinesisShard parent : splitCandidates) {
splitShard(streamName, parent.getShardId(), midpointHashKey(parent.getHashKeyRange()), region, true);
splitShardOnStream(stream, parent.getShardId(), midpointHashKey(parent.getHashKeyRange()));
}
} else if (targetShardCount < currentOpenShardCount) {
int mergesNeeded = currentOpenShardCount - targetShardCount;
@@ -858,7 +974,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, true);
mergeShardsOnStream(stream, shard1.getShardId(), shard2.getShardId());
}
}
}
@@ -1273,8 +1389,7 @@ public class KinesisService implements ResourceProvider {
return newest.stream()
.sorted(Comparator.comparing(peeked -> peeked.record().getApproximateArrivalTimestamp(),
Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
Comparator.nullsLast(Comparator.naturalOrder()))).toList();
}
/**
@@ -0,0 +1,170 @@
package io.floci.aws.services.kinesis;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.kinesis.model.KinesisRecord;
import io.floci.aws.services.kinesis.model.KinesisStream;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class KinesisUpdateShardCountAtomicityTest {
private static final String REGION = "us-east-1";
@Test
void updateShardCountFailureMustNotLeavePartialTopologyOrRollingCount() {
// UpdateShardCount first publishes the UPDATING status window, then commits the staged
// topology. Fail the final topology write (create=1, status=2, commit=3).
FailingPutStorage store = new FailingPutStorage(3);
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream original = service.createStream("my-stream", 2, REGION);
assertThrows(RuntimeException.class,
() -> service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION));
KinesisStream persisted = store.get(REGION + "::my-stream").orElseThrow();
long openShardCount = persisted.getShards().stream().filter(shard -> !shard.isClosed()).count();
assertEquals(2, persisted.getShards().size(), "failed update must not publish shard records");
assertEquals(2, openShardCount, "failed update must leave the original open topology");
assertEquals(0, persisted.getShardCountUpdateTimestamps().size(),
"failed update must not consume a rolling update slot");
assertSame(original, persisted, "a failed update must retain the stored stream identity");
}
@Test
void updateShardCountFailureRestoresStateWhenStoragePublishesBeforeThrowing() {
FailingPutStorage store = new FailingPutStorage(3, true);
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream original = service.createStream("my-stream", 2, REGION);
assertThrows(RuntimeException.class,
() -> service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION));
KinesisStream persisted = store.get(REGION + "::my-stream").orElseThrow();
assertEquals(2, persisted.getShards().size(), "rollback must restore the published shard list");
assertEquals(2, persisted.getShards().stream().filter(shard -> !shard.isClosed()).count(),
"rollback must restore the original open topology");
assertEquals(0, persisted.getShardCountUpdateTimestamps().size(),
"rollback must restore the original rolling update history");
assertSame(original, persisted, "rollback must retain the stored stream identity");
}
@Test
void updateShardCountFailureDoesNotReplaceRetainedRecords() {
FailingPutStorage store = new FailingPutStorage(4, true);
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream original = service.createStream("my-stream", 2, REGION);
service.putRecord("my-stream", new byte[]{1, 2, 3}, "partition", REGION);
KinesisRecord retained = original.getShards().getFirst().getRecords().getFirst();
assertThrows(RuntimeException.class,
() -> service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION));
assertSame(retained, original.getShards().getFirst().getRecords().getFirst(),
"rollback must preserve retained record identity");
}
@Test
void successfulUpdateKeepsReturnedStreamReferenceCurrent() {
StorageBackend<String, KinesisStream> store = new InMemoryStorage<>();
KinesisService service = new KinesisService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream original = service.createStream("my-stream", 2, REGION);
service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION);
assertSame(original, service.describeStream("my-stream", REGION));
assertEquals(4, original.getShards().stream().filter(shard -> !shard.isClosed()).count());
}
@Test
void updateShardCountUsesTheServiceClockForItsRollingWindow() {
Instant now = Instant.parse("2026-01-02T03:04:05Z");
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"), Clock.fixed(now, Clock.systemUTC().getZone()));
service.createStream("my-stream", 2, REGION);
service.updateShardCount("my-stream", 4, "UNIFORM_SCALING", REGION);
KinesisStream stream = service.describeStream("my-stream", REGION);
assertEquals(List.of(now), stream.getShardCountUpdateTimestamps());
}
private static final class FailingPutStorage implements StorageBackend<String, KinesisStream> {
private final StorageBackend<String, KinesisStream> delegate = new InMemoryStorage<>();
private final int failOnPut;
private final boolean publishBeforeFailure;
private int putCount;
private FailingPutStorage(int failOnPut) {
this(failOnPut, false);
}
private FailingPutStorage(int failOnPut, boolean publishBeforeFailure) {
this.failOnPut = failOnPut;
this.publishBeforeFailure = publishBeforeFailure;
}
@Override
public void put(String key, KinesisStream value) {
putCount++;
if (putCount == failOnPut) {
if (publishBeforeFailure) {
delegate.put(key, value);
}
throw new RuntimeException("injected store.put failure");
}
delegate.put(key, value);
}
@Override
public Optional<KinesisStream> get(String key) {
return delegate.get(key);
}
@Override
public void delete(String key) {
delegate.delete(key);
}
@Override
public List<KinesisStream> scan(Predicate<String> keyFilter) {
return new ArrayList<>(delegate.scan(keyFilter));
}
@Override
public Set<String> keys() {
return delegate.keys();
}
@Override
public void flush() {
delegate.flush();
}
@Override
public void load() {
delegate.load();
}
@Override
public void clear() {
delegate.clear();
}
}
}