mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix: honor Kinesis ExplicitHashKey routing (#3069)
* fix: honor kinesis explicit hash keys * fix(kinesis): reject numeric ExplicitHashKey and migrate legacy shard ranges (#3069) Address the two review findings on explicit-hash-key routing: - Reject a non-string ExplicitHashKey JSON node with SerializationException in PutRecord and PutRecords, instead of letting asText coerce a JSON number into an accepted decimal string, preserving AWS wire-protocol fidelity. - Repartition legacy multi-shard streams whose open shards still carry the old full-span hash range into disjoint contiguous ranges before explicit-hash routing, so an explicit key no longer collapses onto the first shard after an upgrade. Already-disjoint (new/split/merged) streams are left untouched. RED -> GREEN: 3 new tests failed on the prior HEAD (putRecordRejectsNumericExplicitHashKey, putRecordsRejectNumericExplicitHashKey, putRecordMigratesLegacyOverlappingShardRangesForExplicitHashKey), all green after the fix. Kinesis suite: 118 run, 0 failures. --------- Co-authored-by: Ben Younes <2910651+ousamabenyounes@users.noreply.github.com>
This commit is contained in:
1 parent
b6489ac933
commit
a006b27694
5 files changed
+327
-13
No files matched your search
@@ -66,7 +66,11 @@ aws kinesis describe-stream --stream-arn arn:aws:kinesis:us-east-1:000000000000:
|
||||
|
||||
`GetShardIterator` supports all five iterator types: `TRIM_HORIZON`, `LATEST`, `AT_SEQUENCE_NUMBER`, `AFTER_SEQUENCE_NUMBER`, `AT_TIMESTAMP`.
|
||||
|
||||
A `LATEST` iterator is positioned at the shard tip at the moment the iterator is created, matching AWS: records written after the iterator was obtained are returned, records written before are not. This supports the standard tailing pattern — obtain a `LATEST` iterator, trigger the action that produces the record, then poll `GetRecords` following `NextShardIterator`.
|
||||
A `LATEST` iterator is positioned at the shard tip at the moment the iterator is created, matching AWS: records written after the iterator was obtained are returned, records written before are not. This supports the standard tailing pattern: obtain a `LATEST` iterator, trigger the action that produces the record, then poll `GetRecords` following `NextShardIterator`.
|
||||
|
||||
## Record Routing
|
||||
|
||||
`PutRecord` and `PutRecords` honor `ExplicitHashKey` when it is provided. The 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 keeps using the partition key to choose a shard.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -29,6 +29,10 @@ import java.util.Set;
|
||||
@ApplicationScoped
|
||||
public class KinesisJsonHandler {
|
||||
|
||||
private static final String EXPLICIT_HASH_KEY_FIELD = "ExplicitHashKey";
|
||||
private static final String EXPLICIT_HASH_KEY_NOT_STRING_MESSAGE =
|
||||
"ExplicitHashKey must be a string.";
|
||||
|
||||
private final KinesisService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -463,6 +467,21 @@ public class KinesisJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
// ExplicitHashKey is a string-shaped field in the AWS Kinesis JSON protocol. A JSON number
|
||||
// such as 12345 is malformed input the real service rejects, so reject non-string nodes here
|
||||
// rather than letting asText coerce them into an accepted decimal string. A missing or null
|
||||
// node means the caller omitted the field and partition-key routing applies.
|
||||
private String readExplicitHashKey(JsonNode record) {
|
||||
JsonNode explicitHashKeyNode = record.path(EXPLICIT_HASH_KEY_FIELD);
|
||||
if (explicitHashKeyNode.isMissingNode() || explicitHashKeyNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!explicitHashKeyNode.isTextual()) {
|
||||
throw new AwsException("SerializationException", EXPLICIT_HASH_KEY_NOT_STRING_MESSAGE, 400);
|
||||
}
|
||||
return explicitHashKeyNode.asText();
|
||||
}
|
||||
|
||||
private Response handlePutRecord(JsonNode request, String region) {
|
||||
String streamName = resolveStreamName(request);
|
||||
JsonNode dataNode = request.path("Data");
|
||||
@@ -478,8 +497,10 @@ public class KinesisJsonHandler {
|
||||
throw new AwsException("SerializationException", "Data is not valid base64.", 400);
|
||||
}
|
||||
String partitionKey = request.path("PartitionKey").asText();
|
||||
String explicitHashKey = readExplicitHashKey(request);
|
||||
|
||||
KinesisService.PutRecordResult result = service.putRecordWithShardId(streamName, data, partitionKey, region);
|
||||
KinesisService.PutRecordResult result = service.putRecordWithShardId(
|
||||
streamName, data, partitionKey, explicitHashKey, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("SequenceNumber", result.sequenceNumber());
|
||||
@@ -501,7 +522,7 @@ public class KinesisJsonHandler {
|
||||
// check. The count cap is checked upfront and the byte cap as the
|
||||
// loop goes, so neither an over-long batch nor an oversized one is
|
||||
// fully decoded before it is rejected.
|
||||
record Entry(JsonNode node, byte[] data) {}
|
||||
record Entry(JsonNode node, byte[] data, String explicitHashKey) {}
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
long totalBytes = 0;
|
||||
for (JsonNode node : recordsNode) {
|
||||
@@ -515,6 +536,8 @@ public class KinesisJsonHandler {
|
||||
}
|
||||
}
|
||||
String partitionKey = node.path("PartitionKey").asText();
|
||||
String explicitHashKey = readExplicitHashKey(node);
|
||||
service.validateExplicitHashKey(explicitHashKey);
|
||||
service.validateRecordSize(stream, data, partitionKey);
|
||||
// Data that did not decode still travelled in the request, so it counts toward the
|
||||
// request cap at the bytes the caller sent rather than as nothing — otherwise a batch
|
||||
@@ -526,7 +549,7 @@ public class KinesisJsonHandler {
|
||||
: dataNode.toString().getBytes(StandardCharsets.UTF_8).length,
|
||||
partitionKey);
|
||||
service.validateRequestSize(totalBytes);
|
||||
entries.add(new Entry(node, data));
|
||||
entries.add(new Entry(node, data, explicitHashKey));
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
@@ -544,7 +567,8 @@ public class KinesisJsonHandler {
|
||||
data = Base64.getDecoder().decode(dataNode.asText());
|
||||
}
|
||||
String partitionKey = entry.node().path("PartitionKey").asText();
|
||||
KinesisService.PutRecordResult result = service.putRecordWithShardId(streamName, data, partitionKey, region);
|
||||
KinesisService.PutRecordResult result = service.putRecordWithShardId(
|
||||
streamName, data, partitionKey, entry.explicitHashKey(), region);
|
||||
results.addObject()
|
||||
.put("SequenceNumber", result.sequenceNumber())
|
||||
.put("ShardId", result.shardId());
|
||||
|
||||
@@ -14,6 +14,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
@@ -43,6 +44,12 @@ public class KinesisService implements ResourceProvider {
|
||||
private static final int MAX_RECORD_SIZE_KIB = 10240;
|
||||
private static final int MAX_RECORDS_PER_REQUEST = 500;
|
||||
private static final int MAX_REQUEST_SIZE_BYTES = 10 * 1024 * 1024;
|
||||
private static final String MIN_HASH_KEY_VALUE = "0";
|
||||
private static final String INITIAL_SEQUENCE_NUMBER = "0";
|
||||
private static final BigInteger MIN_HASH_KEY = BigInteger.ZERO;
|
||||
private static final BigInteger MAX_HASH_KEY =
|
||||
new BigInteger("340282366920938463463374607431768211455");
|
||||
private static final BigInteger HASH_KEY_SPACE_SIZE = MAX_HASH_KEY.add(BigInteger.ONE);
|
||||
|
||||
private final StorageBackend<String, KinesisStream> store;
|
||||
private final StorageBackend<String, KinesisConsumer> consumerStore;
|
||||
@@ -117,7 +124,10 @@ public class KinesisService implements ResourceProvider {
|
||||
|
||||
for (int i = 0; i < shardCount; i++) {
|
||||
String shardId = String.format("shardId-%012d", i);
|
||||
stream.getShards().add(new KinesisShard(shardId, "0", "340282366920938463463374607431768211455", "0"));
|
||||
stream.getShards().add(new KinesisShard(shardId,
|
||||
shardStartingHashKey(i, shardCount),
|
||||
shardEndingHashKey(i, shardCount),
|
||||
INITIAL_SEQUENCE_NUMBER));
|
||||
}
|
||||
|
||||
store.put(storageKey, stream);
|
||||
@@ -450,7 +460,7 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private String subtractOne(String val) {
|
||||
return new java.math.BigInteger(val).subtract(java.math.BigInteger.ONE).toString();
|
||||
return new BigInteger(val).subtract(BigInteger.ONE).toString();
|
||||
}
|
||||
|
||||
public record PutRecordResult(String sequenceNumber, String shardId) {}
|
||||
@@ -535,9 +545,21 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
void validateExplicitHashKey(String explicitHashKey) {
|
||||
if (explicitHashKey != null) {
|
||||
parseExplicitHashKey(explicitHashKey);
|
||||
}
|
||||
}
|
||||
|
||||
public PutRecordResult putRecordWithShardId(String streamName, byte[] data, String partitionKey, String region) {
|
||||
return putRecordWithShardId(streamName, data, partitionKey, null, region);
|
||||
}
|
||||
|
||||
public PutRecordResult putRecordWithShardId(String streamName, byte[] data, String partitionKey,
|
||||
String explicitHashKey, String region) {
|
||||
String key = regionKey(region, streamName);
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateExplicitHashKey(explicitHashKey);
|
||||
validateRecordSize(stream, data, partitionKey);
|
||||
putRecordBeforeLockHook.run();
|
||||
|
||||
@@ -550,7 +572,7 @@ public class KinesisService implements ResourceProvider {
|
||||
// persisting the stale pre-delete instance would resurrect a deleted stream, so bind to
|
||||
// the instance currently in the store and fail like any missing stream if it is gone.
|
||||
KinesisStream current = resolveStream(streamName, region);
|
||||
KinesisShard shard = selectShard(current, partitionKey);
|
||||
KinesisShard shard = selectShard(current, partitionKey, explicitHashKey);
|
||||
String sequenceNumber = String.valueOf(sequenceGenerator.incrementAndGet());
|
||||
putRecordAppendHook.run();
|
||||
KinesisRecord record = new KinesisRecord(data, partitionKey, sequenceNumber, Instant.now());
|
||||
@@ -841,11 +863,16 @@ public class KinesisService implements ResourceProvider {
|
||||
return response;
|
||||
}
|
||||
|
||||
private KinesisShard selectShard(KinesisStream stream, String partitionKey) {
|
||||
private KinesisShard selectShard(KinesisStream stream, String partitionKey, String explicitHashKey) {
|
||||
if (explicitHashKey != null) {
|
||||
normalizeOpenShardRanges(stream);
|
||||
return selectShardByExplicitHashKey(stream, explicitHashKey);
|
||||
}
|
||||
|
||||
// Simple hash-based shard selection among ALL shards, then resolve to open one
|
||||
int index = (int) (Math.abs((long) partitionKey.hashCode()) % stream.getShards().size());
|
||||
KinesisShard shard = stream.getShards().get(index);
|
||||
|
||||
|
||||
// If closed, find the first open child (simplified)
|
||||
while (shard.isClosed()) {
|
||||
KinesisShard finalShard = shard;
|
||||
@@ -859,6 +886,96 @@ public class KinesisService implements ResourceProvider {
|
||||
return shard;
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
List<KinesisShard> openShards = stream.getShards().stream()
|
||||
.filter(shard -> !shard.isClosed())
|
||||
.sorted(Comparator.comparing(KinesisShard::getShardId))
|
||||
.toList();
|
||||
if (openShards.size() <= 1 || openShardRangesDisjoint(openShards)) {
|
||||
return;
|
||||
}
|
||||
int openShardCount = openShards.size();
|
||||
for (int i = 0; i < openShardCount; i++) {
|
||||
openShards.get(i).setHashKeyRange(new KinesisShard.HashKeyRange(
|
||||
shardStartingHashKey(i, openShardCount),
|
||||
shardEndingHashKey(i, openShardCount)));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean openShardRangesDisjoint(List<KinesisShard> openShards) {
|
||||
List<KinesisShard> byStartingHashKey = openShards.stream()
|
||||
.sorted(Comparator.comparing(shard -> new BigInteger(shard.getHashKeyRange().startingHashKey())))
|
||||
.toList();
|
||||
for (int i = 1; i < byStartingHashKey.size(); i++) {
|
||||
BigInteger previousEnd =
|
||||
new BigInteger(byStartingHashKey.get(i - 1).getHashKeyRange().endingHashKey());
|
||||
BigInteger currentStart =
|
||||
new BigInteger(byStartingHashKey.get(i).getHashKeyRange().startingHashKey());
|
||||
if (currentStart.compareTo(previousEnd) <= 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static BigInteger parseExplicitHashKey(String explicitHashKey) {
|
||||
if (explicitHashKey.isBlank()
|
||||
|| !explicitHashKey.chars().allMatch(c -> c >= '0' && c <= '9')) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"ExplicitHashKey must be a decimal integer.", 400);
|
||||
}
|
||||
|
||||
if (!MIN_HASH_KEY_VALUE.equals(explicitHashKey) && explicitHashKey.startsWith(MIN_HASH_KEY_VALUE)) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"ExplicitHashKey must not contain leading zeroes.", 400);
|
||||
}
|
||||
|
||||
BigInteger hashKey = new BigInteger(explicitHashKey);
|
||||
if (hashKey.compareTo(MIN_HASH_KEY) < 0 || hashKey.compareTo(MAX_HASH_KEY) > 0) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"ExplicitHashKey must be between " + MIN_HASH_KEY + " and " + MAX_HASH_KEY + ".", 400);
|
||||
}
|
||||
return hashKey;
|
||||
}
|
||||
|
||||
private static String shardStartingHashKey(int shardIndex, int shardCount) {
|
||||
return HASH_KEY_SPACE_SIZE
|
||||
.multiply(BigInteger.valueOf(shardIndex))
|
||||
.divide(BigInteger.valueOf(shardCount))
|
||||
.toString();
|
||||
}
|
||||
|
||||
private static String shardEndingHashKey(int shardIndex, int shardCount) {
|
||||
if (shardIndex == shardCount - 1) {
|
||||
return MAX_HASH_KEY.toString();
|
||||
}
|
||||
return new BigInteger(shardStartingHashKey(shardIndex + 1, shardCount))
|
||||
.subtract(BigInteger.ONE)
|
||||
.toString();
|
||||
}
|
||||
|
||||
private String regionKey(String region, String name) {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
+66
-2
@@ -23,6 +23,10 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
class KinesisIntegrationTest {
|
||||
|
||||
private static final String KINESIS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String MIN_HASH_KEY = "0";
|
||||
private static final String FIRST_SHARD_ENDING_HASH_KEY = "170141183460469231731687303715884105727";
|
||||
private static final String SECOND_SHARD_STARTING_HASH_KEY = "170141183460469231731687303715884105728";
|
||||
private static final String MAX_HASH_KEY = "340282366920938463463374607431768211455";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Pattern CREATION_TIMESTAMP_PATTERN = Pattern.compile(
|
||||
"\\\"StreamCreationTimestamp\\\"\\s*:\\s*(-?\\d+(?:\\.\\d+)?)(?=\\s*[,}])");
|
||||
@@ -64,7 +68,9 @@ class KinesisIntegrationTest {
|
||||
.body("Shards[0].ShardId", equalTo("shardId-000000000000"))
|
||||
.body("Shards[1].ShardId", equalTo("shardId-000000000001"))
|
||||
.body("Shards[0].HashKeyRange.StartingHashKey", notNullValue())
|
||||
.body("Shards[0].HashKeyRange.EndingHashKey", equalTo("340282366920938463463374607431768211455"))
|
||||
.body("Shards[0].HashKeyRange.EndingHashKey", equalTo(FIRST_SHARD_ENDING_HASH_KEY))
|
||||
.body("Shards[1].HashKeyRange.StartingHashKey", equalTo(SECOND_SHARD_STARTING_HASH_KEY))
|
||||
.body("Shards[1].HashKeyRange.EndingHashKey", equalTo(MAX_HASH_KEY))
|
||||
.body("Shards[0].SequenceNumberRange.StartingSequenceNumber", notNullValue());
|
||||
}
|
||||
|
||||
@@ -254,7 +260,7 @@ class KinesisIntegrationTest {
|
||||
{
|
||||
"StreamName": "list-shards-test",
|
||||
"ShardToSplit": "shardId-000000000000",
|
||||
"NewStartingHashKey": "170141183460469231731687303715884105728"
|
||||
"NewStartingHashKey": "85070591730234615865843651857942052864"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
@@ -790,6 +796,64 @@ class KinesisIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(44)
|
||||
void putRecordHonorsExplicitHashKey() {
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.CreateStream")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"StreamName": "explicit-hash-put-test", "ShardCount": 2}
|
||||
""")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.PutRecord")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body("{\"StreamName\": \"explicit-hash-put-test\", \"Data\": \"dGVzdA==\","
|
||||
+ "\"PartitionKey\": \"same-key\", \"ExplicitHashKey\": \"" + MIN_HASH_KEY + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ShardId", equalTo("shardId-000000000000"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.PutRecord")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body("{\"StreamName\": \"explicit-hash-put-test\", \"Data\": \"dGVzdA==\","
|
||||
+ "\"PartitionKey\": \"same-key\", \"ExplicitHashKey\": \"" + MAX_HASH_KEY + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("ShardId", equalTo("shardId-000000000001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(45)
|
||||
void putRecordsHonorsExplicitHashKeyPerEntry() {
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.CreateStream")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"StreamName": "explicit-hash-putrecords-test", "ShardCount": 2}
|
||||
""")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.PutRecords")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body("{\"StreamName\": \"explicit-hash-putrecords-test\","
|
||||
+ "\"Records\": ["
|
||||
+ "{\"Data\": \"dGVzdA==\", \"PartitionKey\": \"same-key\", \"ExplicitHashKey\": \""
|
||||
+ MIN_HASH_KEY + "\"},"
|
||||
+ "{\"Data\": \"dGVzdA==\", \"PartitionKey\": \"same-key\", \"ExplicitHashKey\": \""
|
||||
+ MAX_HASH_KEY + "\"}"
|
||||
+ "]}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("FailedRecordCount", equalTo(0))
|
||||
.body("Records[0].ShardId", equalTo("shardId-000000000000"))
|
||||
.body("Records[1].ShardId", equalTo("shardId-000000000001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(46)
|
||||
void putRecordPreservesShardForNegativeHashCode() {
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.CreateStream")
|
||||
|
||||
+106
-1
@@ -7,6 +7,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -29,6 +31,14 @@ class KinesisJsonHandlerTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:123456789012:stream/test-stream";
|
||||
private static final String MAX_HASH_KEY_PLUS_ONE = "340282366920938463463374607431768211456";
|
||||
private static final String NON_DECIMAL_HASH_KEY = "1.5";
|
||||
private static final long NUMERIC_EXPLICIT_HASH_KEY = 12345L;
|
||||
private static final String MIN_HASH_KEY = "0";
|
||||
private static final String MAX_HASH_KEY = "340282366920938463463374607431768211455";
|
||||
private static final int TWO_SHARDS = 2;
|
||||
private static final String FIRST_SHARD_ID = "shardId-000000000000";
|
||||
private static final String SECOND_SHARD_ID = "shardId-000000000001";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private KinesisService service;
|
||||
@@ -45,9 +55,13 @@ class KinesisJsonHandlerTest {
|
||||
}
|
||||
|
||||
private void createStream(String name) {
|
||||
createStream(name, 1);
|
||||
}
|
||||
|
||||
private void createStream(String name, int shardCount) {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", name);
|
||||
req.put("ShardCount", 1);
|
||||
req.put("ShardCount", shardCount);
|
||||
assertThat(handler.handle("CreateStream", req, REGION).getStatus(), is(200));
|
||||
}
|
||||
|
||||
@@ -421,6 +435,97 @@ class KinesisJsonHandlerTest {
|
||||
assertEquals("InvalidArgumentException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordRejectsExplicitHashKeyOutsideHashKeySpace() {
|
||||
createStream("test-stream");
|
||||
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", "test-stream");
|
||||
req.put("Data", "dGVzdA==");
|
||||
req.put("PartitionKey", "pk1");
|
||||
req.put("ExplicitHashKey", MAX_HASH_KEY_PLUS_ONE);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecord", req, REGION));
|
||||
assertEquals("InvalidArgumentException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordsRejectsNonDecimalExplicitHashKey() {
|
||||
createStream("test-stream");
|
||||
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", "test-stream");
|
||||
ArrayNode records = req.putArray("Records");
|
||||
records.addObject()
|
||||
.put("Data", "dGVzdA==")
|
||||
.put("PartitionKey", "pk1")
|
||||
.put("ExplicitHashKey", NON_DECIMAL_HASH_KEY);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecords", req, REGION));
|
||||
assertEquals("InvalidArgumentException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordRejectsNumericExplicitHashKey() {
|
||||
createStream("test-stream");
|
||||
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", "test-stream");
|
||||
req.put("Data", "dGVzdA==");
|
||||
req.put("PartitionKey", "pk1");
|
||||
// A JSON number is not the string-shaped field AWS accepts; asText coercion must not
|
||||
// silently turn it into a valid decimal hash key.
|
||||
req.put("ExplicitHashKey", NUMERIC_EXPLICIT_HASH_KEY);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecord", req, REGION));
|
||||
assertEquals("SerializationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordsRejectNumericExplicitHashKey() {
|
||||
createStream("test-stream");
|
||||
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", "test-stream");
|
||||
ArrayNode records = req.putArray("Records");
|
||||
records.addObject()
|
||||
.put("Data", "dGVzdA==")
|
||||
.put("PartitionKey", "pk1")
|
||||
.put("ExplicitHashKey", NUMERIC_EXPLICIT_HASH_KEY);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecords", req, REGION));
|
||||
assertEquals("SerializationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordMigratesLegacyOverlappingShardRangesForExplicitHashKey() {
|
||||
// A multi-shard stream persisted before disjoint ranges existed carries the full 128-bit
|
||||
// span on every open shard, so an explicit key matches all of them. Naive first-match
|
||||
// routing would then collapse every explicit key onto the first shard.
|
||||
createStream("legacy-stream", TWO_SHARDS);
|
||||
KinesisStream stream = service.describeStream("legacy-stream", REGION);
|
||||
for (KinesisShard shard : stream.getShards()) {
|
||||
shard.setHashKeyRange(new KinesisShard.HashKeyRange(MIN_HASH_KEY, MAX_HASH_KEY));
|
||||
}
|
||||
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("StreamName", "legacy-stream");
|
||||
req.put("Data", "dGVzdA==");
|
||||
req.put("PartitionKey", "pk1");
|
||||
req.put("ExplicitHashKey", MAX_HASH_KEY);
|
||||
|
||||
ObjectNode resp = responseEntity(handler.handle("PutRecord", req, REGION));
|
||||
assertEquals(SECOND_SHARD_ID, resp.get("ShardId").asText());
|
||||
|
||||
req.put("ExplicitHashKey", MIN_HASH_KEY);
|
||||
ObjectNode respMin = responseEntity(handler.handle("PutRecord", req, REGION));
|
||||
assertEquals(FIRST_SHARD_ID, respMin.get("ShardId").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordAcceptsRecordAtSizeLimit() {
|
||||
createStream("test-stream");
|
||||
|
||||
Reference in new issue
Block a user