mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(kinesis): add PutRecords request caps and a per-stream max record size (#2438)
PutRecords enforced only the per-record limit. AWS also caps a request at 500 records and 10 MiB including partition keys; both are now whole-request rejections with InvalidArgumentException, since per-record ErrorCode only carries throughput and internal failures. 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. Undecodable or non-string Data counts toward the cap at the UTF-8 bytes the caller sent, so a batch of malformed records cannot slip past it. The per-record maximum becomes per-stream state defaulting to 1024 KiB, set by CreateStream's MaxRecordSizeInKiB or UpdateMaxRecordSize (1024-10240) and reported by DescribeStreamSummary. UpdateMaxRecordSize documents ValidationException for an out-of-range size. CreateStream doesn't, and reserves ValidationException for the on-demand case, so it answers InvalidArgumentException. Streams persisted before the field existed deserialize to the default.
This commit is contained in:
1 parent
ba97c084eb
commit
353d9c842f
5 files changed
+538
-18
No files matched your search
@@ -16,6 +16,7 @@ import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
@@ -66,6 +67,7 @@ public class KinesisJsonHandler {
|
||||
case "EnableEnhancedMonitoring" -> handleEnableEnhancedMonitoring(request, region);
|
||||
case "DisableEnhancedMonitoring" -> handleDisableEnhancedMonitoring(request, region);
|
||||
case "UpdateStreamMode" -> handleUpdateStreamMode(request, region);
|
||||
case "UpdateMaxRecordSize" -> handleUpdateMaxRecordSize(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
@@ -112,7 +114,8 @@ public class KinesisJsonHandler {
|
||||
streamMode = mode;
|
||||
}
|
||||
}
|
||||
service.createStream(streamName, shardCount, streamMode, region);
|
||||
service.createStream(streamName, shardCount, streamMode,
|
||||
optionalMaxRecordSize(request), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@@ -135,6 +138,36 @@ public class KinesisJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* MaxRecordSizeInKiB is modelled as an integer, so a float or a value outside int range is a
|
||||
* type error rather than something to truncate into the range check.
|
||||
*/
|
||||
private Integer optionalMaxRecordSize(JsonNode request) {
|
||||
JsonNode size = request.path("MaxRecordSizeInKiB");
|
||||
if (size.isMissingNode() || size.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!size.isIntegralNumber() || !size.canConvertToInt()) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"MaxRecordSizeInKiB must be an integer", 400);
|
||||
}
|
||||
return size.intValue();
|
||||
}
|
||||
|
||||
private Response handleUpdateMaxRecordSize(JsonNode request, String region) {
|
||||
// UpdateMaxRecordSize identifies the stream by StreamARN only per the AWS API; StreamName is not valid.
|
||||
String streamArn = request.path("StreamARN").asText(null);
|
||||
if (streamArn == null || streamArn.isBlank()) {
|
||||
throw new AwsException("InvalidArgumentException", "StreamARN is required", 400);
|
||||
}
|
||||
Integer size = optionalMaxRecordSize(request);
|
||||
if (size == null) {
|
||||
throw new AwsException("InvalidArgumentException", "MaxRecordSizeInKiB is required", 400);
|
||||
}
|
||||
service.updateMaxRecordSize(extractStreamNameFromArn(streamArn), size, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private String extractStreamNameFromArn(String streamArn) {
|
||||
String name = parseStreamNameFromArn(streamArn);
|
||||
if (name == null) {
|
||||
@@ -214,6 +247,7 @@ public class KinesisJsonHandler {
|
||||
summary.put("StreamCreationTimestamp", epochSeconds(stream.getStreamCreationTimestamp()));
|
||||
summary.put("OpenShardCount", (int) stream.getShards().stream().filter(s -> !s.isClosed()).count());
|
||||
summary.put("EncryptionType", stream.getEncryptionType());
|
||||
summary.put("MaxRecordSizeInKiB", stream.getMaxRecordSizeInKiB());
|
||||
if (stream.getKeyId() != null) {
|
||||
summary.put("KeyId", stream.getKeyId());
|
||||
}
|
||||
@@ -432,25 +466,43 @@ public class KinesisJsonHandler {
|
||||
|
||||
private Response handlePutRecords(JsonNode request, String region) {
|
||||
String streamName = resolveStreamName(request);
|
||||
service.describeStream(streamName, region);
|
||||
KinesisStream stream = service.describeStream(streamName, region);
|
||||
JsonNode recordsNode = request.path("Records");
|
||||
service.validateRecordCount(recordsNode.size());
|
||||
|
||||
// An oversized record fails the whole request before anything is
|
||||
// written — per-record ErrorCode is reserved for throughput/internal
|
||||
// failures. Successful decodes are kept for the write loop; malformed
|
||||
// Data is left null so it stays a per-record failure there.
|
||||
// Data is left null so it stays a per-record failure there. 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) {}
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
long totalBytes = 0;
|
||||
for (JsonNode node : recordsNode) {
|
||||
byte[] data;
|
||||
try {
|
||||
data = Base64.getDecoder().decode(node.path("Data").asText());
|
||||
} catch (IllegalArgumentException e) {
|
||||
data = null;
|
||||
JsonNode dataNode = node.path("Data");
|
||||
byte[] data = null;
|
||||
if (dataNode.isTextual()) {
|
||||
try {
|
||||
data = Base64.getDecoder().decode(dataNode.textValue());
|
||||
} catch (IllegalArgumentException e) {
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
String partitionKey = node.path("PartitionKey").asText();
|
||||
if (data != null) {
|
||||
service.validateRecordSize(data, node.path("PartitionKey").asText());
|
||||
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
|
||||
// of undecodable records could carry any payload past the limit. A non-string Data is
|
||||
// measured the same way, since it is not a blob AWS would have accepted either.
|
||||
totalBytes += KinesisService.recordSize(
|
||||
data != null ? data.length
|
||||
: dataNode.toString().getBytes(StandardCharsets.UTF_8).length,
|
||||
partitionKey);
|
||||
service.validateRequestSize(totalBytes);
|
||||
entries.add(new Entry(node, data));
|
||||
}
|
||||
|
||||
|
||||
@@ -30,10 +30,12 @@ public class KinesisService {
|
||||
private static final String DEFAULT_STREAM_MODE = "PROVISIONED";
|
||||
private static final int DEFAULT_INSPECTION_RECORD_LIMIT = 100;
|
||||
private static final int MAX_INSPECTION_RECORD_LIMIT = 1000;
|
||||
// AWS default per-stream maximum record size (data blob + partition key).
|
||||
// Raisable per stream via UpdateMaxRecordSize, which floci doesn't
|
||||
// implement, so every stream sits at the default.
|
||||
private static final int MAX_RECORD_SIZE_BYTES = 1_048_576;
|
||||
// MaxRecordSizeInKiB bounds, as AWS constrains them on CreateStream and
|
||||
// UpdateMaxRecordSize. The per-stream default lives on KinesisStream.
|
||||
private static final int MIN_RECORD_SIZE_KIB = 1024;
|
||||
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 final StorageBackend<String, KinesisStream> store;
|
||||
private final StorageBackend<String, KinesisConsumer> consumerStore;
|
||||
@@ -62,11 +64,24 @@ public class KinesisService {
|
||||
}
|
||||
|
||||
public KinesisStream createStream(String streamName, int shardCount, String streamMode, String region) {
|
||||
return createStream(streamName, shardCount, streamMode, null, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param maxRecordSizeInKiB CreateStream's optional MaxRecordSizeInKiB; null leaves the stream
|
||||
* at the AWS default. It is a distinct value from 0, which AWS
|
||||
* rejects as below the documented minimum.
|
||||
*/
|
||||
public KinesisStream createStream(String streamName, int shardCount, String streamMode,
|
||||
Integer maxRecordSizeInKiB, String region) {
|
||||
String resolvedMode = streamMode != null ? streamMode : DEFAULT_STREAM_MODE;
|
||||
if (!VALID_STREAM_MODES.contains(resolvedMode)) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"StreamMode must be PROVISIONED or ON_DEMAND, got: " + resolvedMode, 400);
|
||||
}
|
||||
if (maxRecordSizeInKiB != null) {
|
||||
validateMaxRecordSize(maxRecordSizeInKiB, "InvalidArgumentException");
|
||||
}
|
||||
|
||||
String storageKey = regionKey(region, streamName);
|
||||
if (store.get(storageKey).isPresent()) {
|
||||
@@ -77,6 +92,9 @@ public class KinesisService {
|
||||
KinesisStream stream = new KinesisStream(streamName, arn);
|
||||
stream.setAccountId(regionResolver.getAccountId());
|
||||
stream.setStreamMode(resolvedMode);
|
||||
if (maxRecordSizeInKiB != null) {
|
||||
stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB);
|
||||
}
|
||||
|
||||
for (int i = 0; i < shardCount; i++) {
|
||||
String shardId = String.format("shardId-%012d", i);
|
||||
@@ -372,19 +390,82 @@ public class KinesisService {
|
||||
return putRecordWithShardId(streamName, data, partitionKey, region).sequenceNumber();
|
||||
}
|
||||
|
||||
public void validateRecordSize(byte[] data, String partitionKey) {
|
||||
int size = (data != null ? data.length : 0)
|
||||
/** Record size as AWS measures it: the data blob plus the partition key. */
|
||||
static int recordSize(int dataBytes, String partitionKey) {
|
||||
return dataBytes
|
||||
+ (partitionKey != null ? partitionKey.getBytes(StandardCharsets.UTF_8).length : 0);
|
||||
if (size > MAX_RECORD_SIZE_BYTES) {
|
||||
}
|
||||
|
||||
public void validateRecordSize(KinesisStream stream, byte[] data, String partitionKey) {
|
||||
int size = recordSize(data != null ? data.length : 0, partitionKey);
|
||||
int max = stream.getMaxRecordSizeInKiB() * 1024;
|
||||
if (size > max) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Record size (data + partition key) of " + size + " bytes exceeds the maximum of "
|
||||
+ MAX_RECORD_SIZE_BYTES + " bytes.", 400);
|
||||
+ max + " bytes.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The request-wide PutRecords caps. Both reject the whole request rather than failing records
|
||||
* individually, because PutRecordsResultEntry.ErrorCode carries only throughput and internal
|
||||
* errors — the same reason the per-record size check aborts the batch.
|
||||
*/
|
||||
void validateRecordCount(int recordCount) {
|
||||
if (recordCount < 1) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"A PutRecords request requires at least one record.", 400);
|
||||
}
|
||||
if (recordCount > MAX_RECORDS_PER_REQUEST) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"A PutRecords request supports at most " + MAX_RECORDS_PER_REQUEST
|
||||
+ " records, got " + recordCount + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
void validateRequestSize(long totalBytes) {
|
||||
if (totalBytes > MAX_REQUEST_SIZE_BYTES) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"A PutRecords request (data + partition keys) is limited to " + MAX_REQUEST_SIZE_BYTES
|
||||
+ " bytes, got " + totalBytes + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bounds are the same on both actions but the code each publishes for a violation is not:
|
||||
* UpdateMaxRecordSize documents ValidationException for an out-of-range size, while CreateStream
|
||||
* reserves ValidationException for the on-demand case and describes InvalidArgumentException as
|
||||
* "a specified parameter exceeds its restrictions".
|
||||
*/
|
||||
private static void validateMaxRecordSize(int maxRecordSizeInKiB, String errorCode) {
|
||||
if (maxRecordSizeInKiB < MIN_RECORD_SIZE_KIB || maxRecordSizeInKiB > MAX_RECORD_SIZE_KIB) {
|
||||
throw new AwsException(errorCode,
|
||||
"MaxRecordSizeInKiB must be between " + MIN_RECORD_SIZE_KIB + " and "
|
||||
+ MAX_RECORD_SIZE_KIB + ", got " + maxRecordSizeInKiB + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public void updateMaxRecordSize(String streamName, int maxRecordSizeInKiB, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateMaxRecordSize(maxRecordSizeInKiB, "ValidationException");
|
||||
if ("ON_DEMAND".equals(stream.getStreamMode())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"UpdateMaxRecordSize is only supported for data streams with the provisioned capacity mode.",
|
||||
400);
|
||||
}
|
||||
if (!"ACTIVE".equals(stream.getStreamStatus())) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Stream " + streamName + " is not ACTIVE (current state: "
|
||||
+ stream.getStreamStatus() + ")", 400);
|
||||
}
|
||||
stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Updated max record size for {0} to {1} KiB", streamName, maxRecordSizeInKiB);
|
||||
}
|
||||
|
||||
public PutRecordResult putRecordWithShardId(String streamName, byte[] data, String partitionKey, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateRecordSize(data, partitionKey);
|
||||
validateRecordSize(stream, data, partitionKey);
|
||||
KinesisShard shard = selectShard(stream, partitionKey);
|
||||
|
||||
String sequenceNumber = String.valueOf(sequenceGenerator.incrementAndGet());
|
||||
|
||||
@@ -26,6 +26,8 @@ public class KinesisStream {
|
||||
private String keyId;
|
||||
private String streamMode = "PROVISIONED";
|
||||
private Set<String> enhancedMonitoringMetrics = new HashSet<>();
|
||||
// AWS's default; streams persisted before this field existed read as the default too.
|
||||
private int maxRecordSizeInKiB = 1024;
|
||||
|
||||
public KinesisStream() {}
|
||||
|
||||
@@ -69,6 +71,9 @@ public class KinesisStream {
|
||||
public String getStreamMode() { return streamMode; }
|
||||
public void setStreamMode(String streamMode) { this.streamMode = streamMode; }
|
||||
|
||||
public int getMaxRecordSizeInKiB() { return maxRecordSizeInKiB; }
|
||||
public void setMaxRecordSizeInKiB(int maxRecordSizeInKiB) { this.maxRecordSizeInKiB = maxRecordSizeInKiB; }
|
||||
|
||||
public Set<String> getEnhancedMonitoringMetrics() { return enhancedMonitoringMetrics; }
|
||||
public void setEnhancedMonitoringMetrics(Set<String> enhancedMonitoringMetrics) { this.enhancedMonitoringMetrics = enhancedMonitoringMetrics; }
|
||||
}
|
||||
Reference in new issue
Block a user