feat(firehose): validate and persist DataFormatConversionConfiguration (#3236)

* feat(firehose): validate and persist DataFormatConversionConfiguration

Accept, validate, store, and echo the extended S3 destination's
DataFormatConversionConfiguration instead of silently ignoring it.
Validation messages and precedence follow probed AWS behavior: Smithy
ParquetSerDe bounds first, then compression, buffering floor, and
member checks in AWS order, identical on CreateDeliveryStream and
UpdateDestination, which now merges the configuration member-wise and
validates the merged effective state. OrcSerDe is rejected as a
documented deviation (the planned DuckDB engine cannot write ORC).
Conversion itself is not applied yet: delivery logs a warning and
ships records unconverted.

* docs(firehose): match the conversion helpers' wording to what they do

The legacy-shape helper clears DataFormatConversionConfiguration alone, not
every extended-only member, and the create/update warning fires on each call
that leaves conversion enabled rather than once. Rename the first and reword
both so the contract a reader infers is the one the code keeps.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-08 09:01:31 -04:00
1 parent af42564cb3
commit 8a122d2b8c
10 files changed
+2267 -21

No files matched your search

@@ -0,0 +1,108 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.DataFormatConversionConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Deserializer;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.SchemaConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Serializer;
/**
* Validates a destination whose data format conversion is enabled, with the
* messages and precedence captured from real AWS (probe 2026-09-07, both
* CreateDeliveryStream and UpdateDestination): compression format first, then
* the buffering size floor, then the three member null checks in
* Input/Output/Schema order, then the members inside them. On
* UpdateDestination real AWS validates the merged effective state, which is
* why this runs against a merged view rather than the update shape.
*
* All checks are skipped when conversion is absent or explicitly disabled; an
* omitted Enabled counts as enabled. The buffering floor applies only to an
* explicitly specified SizeInMBs: AWS accepts a destination with no
* BufferingHints at all (probe: it proceeds to role validation).
*
* The OrcSerDe rejection is Floci's own: real AWS accepts it, but Floci's
* conversion engine (DuckDB) cannot write ORC, and refusing at create time
* beats accepting a configuration that could never deliver.
*/
final class DataFormatConversionValidator {
private static final int MIN_BUFFERING_SIZE_MBS = 64;
private DataFormatConversionValidator() {}
static void validateEffective(S3Destination config) {
if (config == null || !config.isDataFormatConversionEnabled()) {
return;
}
if (config.getCompressionFormat() != null && !"UNCOMPRESSED".equals(config.getCompressionFormat())) {
throw invalidArgument("The S3 destination's compression format must be set to UNCOMPRESSED"
+ " when data format conversion is enabled. To enable compression within the converted"
+ " output format, set the appropriate serialization option in the output format configuration.");
}
if (config.getBufferingHints() != null && config.getBufferingHints().getSizeInMBs() != null
&& config.getBufferingHints().getSizeInMBs() < MIN_BUFFERING_SIZE_MBS) {
throw invalidArgument("BufferingHints.SizeInMBs must be at least " + MIN_BUFFERING_SIZE_MBS
+ " when data format conversion is enabled.");
}
DataFormatConversionConfiguration conversion = config.getDataFormatConversionConfiguration();
if (conversion.getInputFormatConfiguration() == null) {
throw invalidArgument("InputFormatConfiguration must not be null");
}
if (conversion.getOutputFormatConfiguration() == null) {
throw invalidArgument("OutputFormatConfiguration must not be null");
}
if (conversion.getSchemaConfiguration() == null) {
throw invalidArgument("SchemaConfiguration must not be null");
}
validateDeserializer(conversion.getInputFormatConfiguration().getDeserializer());
validateSerializer(conversion.getOutputFormatConfiguration().getSerializer());
validateSchema(conversion.getSchemaConfiguration());
}
/** An empty Deserializer object reports the same error as an absent one (probe a9). */
private static void validateDeserializer(Deserializer deserializer) {
int specified = deserializer == null ? 0
: (deserializer.getOpenXJsonSerDe() != null ? 1 : 0)
+ (deserializer.getHiveJsonSerDe() != null ? 1 : 0);
if (specified == 0) {
throw invalidArgument("Deserializer must not be null");
}
if (specified > 1) {
throw invalidArgument("More than one deserializer specified. Only one may be chosen.");
}
}
private static void validateSerializer(Serializer serializer) {
int specified = serializer == null ? 0
: (serializer.getParquetSerDe() != null ? 1 : 0)
+ (serializer.getOrcSerDe() != null ? 1 : 0);
if (specified == 0) {
throw invalidArgument("Serializer must not be null");
}
if (specified > 1) {
throw invalidArgument("More than one serializer specified. Only one may be chosen.");
}
if (serializer.getOrcSerDe() != null) {
throw invalidArgument("OrcSerDe is not supported. Floci supports only ParquetSerDe"
+ " for data format conversion.");
}
}
/** AWS's message spells the member RoleArn even though the wire member is RoleARN. */
private static void validateSchema(SchemaConfiguration schema) {
requireSchemaMember(schema.getRoleArn(), "RoleArn");
requireSchemaMember(schema.getDatabaseName(), "DatabaseName");
requireSchemaMember(schema.getTableName(), "TableName");
}
private static void requireSchemaMember(String value, String member) {
if (value == null || value.isEmpty()) {
throw invalidArgument("SchemaConfiguration." + member + " must not be null or empty");
}
}
private static AwsException invalidArgument(String message) {
return new AwsException("InvalidArgumentException", message, 400);
}
}
@@ -46,6 +46,7 @@ public class FirehoseJsonHandler {
S3Destination s3 = null;
if (request.has("S3DestinationConfiguration")) {
s3 = mapper.treeToValue(request.get("S3DestinationConfiguration"), S3Destination.class);
dropConversionFromLegacyShape(s3);
S3DestinationValidator.validateWireShape(s3, "s3DestinationConfiguration");
} else if (request.has("ExtendedS3DestinationConfiguration")) {
s3 = mapper.treeToValue(request.get("ExtendedS3DestinationConfiguration"), S3Destination.class);
@@ -81,6 +82,7 @@ public class FirehoseJsonHandler {
S3DestinationValidator.validateWireShape(update, "extendedS3DestinationUpdate");
} else if (request.has("S3DestinationUpdate")) {
update = mapper.treeToValue(request.get("S3DestinationUpdate"), S3Destination.class);
dropConversionFromLegacyShape(update);
S3DestinationValidator.validateWireShape(update, "s3DestinationUpdate");
}
firehoseService.updateDestination(name, currentVersionId, destinationId, update);
@@ -195,6 +197,28 @@ public class FirehoseJsonHandler {
};
}
/**
* Clears {@code DataFormatConversionConfiguration} from a legacy
* {@code S3DestinationConfiguration} or {@code S3DestinationUpdate}, which AWS
* models only on the extended shapes. The two share one class here, which would
* otherwise let a legacy request store a member its contract does not define.
*
* Dropped rather than rejected: AWS's JSON protocol ignores a member the shape does
* not model, so a request carrying one succeeds with the member disregarded. The
* SDKs cannot even send it, since it is absent from the legacy shape's model.
*
* Only this member is cleared. {@code FileExtension}, {@code CustomTimeZone} and
* {@code S3BackupMode} are extended-only too and reach the legacy shapes the same
* way, a deviation that predates this change and is recorded in
* docs/services/firehose.md; widening the clearing would change behavior those
* members already have.
*/
private static void dropConversionFromLegacyShape(S3Destination s3) {
if (s3 != null) {
s3.setDataFormatConversionConfiguration(null);
}
}
/** DeliveryStreamType values the 2015-08-04 model enumerates. */
private static final java.util.Set<String> DELIVERY_STREAM_TYPES = java.util.Set.of(
"DirectPut", "KinesisStreamAsSource", "MSKAsSource", "DatabaseAsSource");
@@ -219,6 +219,7 @@ public class FirehoseService implements ResourceProvider {
}
validateBufferingHints(s3Config);
DataFormatConversionValidator.validateEffective(s3Config);
String arn = AwsArnUtils.Arn.of("firehose", region, regionResolver.getAccountId(),
"deliverystream/" + name).toString();
// CreateDeliveryStream's KinesisStreamSourceConfiguration carries only the ARN and
@@ -239,6 +240,7 @@ public class FirehoseService implements ResourceProvider {
streamStore.put(name, description);
buffers.put(name, Collections.synchronizedList(new ArrayList<>()));
LOG.infov("Created Firehose delivery stream: {0}", name);
warnIfConversionEnabled(name, s3Config);
return arn;
}
@@ -263,15 +265,42 @@ public class FirehoseService implements ResourceProvider {
validateBufferingHints(update);
S3Destination current = destination.getExtendedS3DestinationDescription();
if (current == null) {
DataFormatConversionValidator.validateEffective(update);
update.applyDefaults();
destination.setExtendedS3DestinationDescription(update);
} else {
// AWS validates the merged effective state, not the update shape: enabling
// conversion is rejected while a stored GZIP is in effect, and re-enabling
// with only {"Enabled": true} succeeds on the stored schema (probe u5/u6).
// Validating a merged view first also keeps a failed update from leaving a
// half-merged destination behind in the memory backend.
DataFormatConversionValidator.validateEffective(mergedView(current, update));
mergeDestination(current, update);
}
stream.setVersionId(String.valueOf(parseVersionId(stream.getVersionId()) + 1));
stream.setLastUpdateTimestamp(java.time.Instant.now());
streamStore.put(name, stream);
LOG.infov("Updated destination {0} of Firehose delivery stream {1}", destinationId, name);
warnIfConversionEnabled(name, stream.s3Destination());
}
/**
* Says, where the configuration is set, that conversion will not be applied. Fires
* on every create and on every update that leaves conversion enabled, including an
* update about something else, so a caller who keeps changing the destination keeps
* being told.
*
* Deliberately not in the flush path: that runs on every buffered delivery and on
* every retry after a failed write, so warning there floods the log and needs a
* per-stream marker whose lifetime has to track creates and deletes. Create and
* update are caller-driven and rare by comparison, and they are the moments a
* caller can act on the warning anyway.
*/
private static void warnIfConversionEnabled(String name, S3Destination s3) {
if (s3 != null && s3.isDataFormatConversionEnabled()) {
LOG.warnv("Delivery stream {0} enables data format conversion, which Floci does not"
+ " apply yet; its records will be delivered unconverted", name);
}
}
public void startDeliveryStreamEncryption(String name, String keyType, String keyArn) {
@@ -354,6 +383,79 @@ public class FirehoseService implements ResourceProvider {
if (update.getBufferingHints() != null) current.setBufferingHints(update.getBufferingHints());
if (update.getEncryptionConfiguration() != null) current.setEncryptionConfiguration(update.getEncryptionConfiguration());
if (update.getS3BackupMode() != null) current.setS3BackupMode(update.getS3BackupMode());
if (update.getDataFormatConversionConfiguration() != null) {
current.setDataFormatConversionConfiguration(mergeConversion(
current.getDataFormatConversionConfiguration(), update.getDataFormatConversionConfiguration()));
}
}
/**
* Unlike the whole-object replacement above, DataFormatConversionConfiguration
* merges member-wise: real AWS keeps the stored Schema/Input/Output when an update
* carries only {"Enabled": false} (probe u2). Where there is anything to merge the
* result is a new object, so a validation pass over a {@link #mergedView} never
* mutates the stored configuration; with nothing stored yet the update is returned
* as it stands, since there is no stored state for a caller to reach through it.
*/
private static DeliveryStreamDescription.DataFormatConversionConfiguration mergeConversion(
DeliveryStreamDescription.DataFormatConversionConfiguration current,
DeliveryStreamDescription.DataFormatConversionConfiguration update) {
if (current == null) {
return update;
}
DeliveryStreamDescription.DataFormatConversionConfiguration merged =
new DeliveryStreamDescription.DataFormatConversionConfiguration();
merged.setEnabled(update.getEnabled() != null ? update.getEnabled() : current.getEnabled());
merged.setSchemaConfiguration(mergeSchema(
current.getSchemaConfiguration(), update.getSchemaConfiguration()));
merged.setInputFormatConfiguration(update.getInputFormatConfiguration() != null
? update.getInputFormatConfiguration() : current.getInputFormatConfiguration());
merged.setOutputFormatConfiguration(update.getOutputFormatConfiguration() != null
? update.getOutputFormatConfiguration() : current.getOutputFormatConfiguration());
return merged;
}
/**
* SchemaConfiguration merges a member at a time as well, so an update naming only
* a new TableName keeps the stored role, database and region (probed). Replacing
* it wholesale would drop those and then fail the required-member checks.
*/
private static DeliveryStreamDescription.SchemaConfiguration mergeSchema(
DeliveryStreamDescription.SchemaConfiguration current,
DeliveryStreamDescription.SchemaConfiguration update) {
if (update == null) {
return current;
}
if (current == null) {
return update;
}
DeliveryStreamDescription.SchemaConfiguration merged =
new DeliveryStreamDescription.SchemaConfiguration();
merged.setRoleArn(update.getRoleArn() != null ? update.getRoleArn() : current.getRoleArn());
merged.setCatalogId(update.getCatalogId() != null ? update.getCatalogId() : current.getCatalogId());
merged.setDatabaseName(update.getDatabaseName() != null
? update.getDatabaseName() : current.getDatabaseName());
merged.setTableName(update.getTableName() != null ? update.getTableName() : current.getTableName());
merged.setRegion(update.getRegion() != null ? update.getRegion() : current.getRegion());
merged.setVersionId(update.getVersionId() != null ? update.getVersionId() : current.getVersionId());
return merged;
}
private static S3Destination mergedView(S3Destination current, S3Destination update) {
S3Destination view = new S3Destination();
view.setRoleArn(current.getRoleArn());
view.setBucketArn(current.getBucketArn());
view.setPrefix(current.getPrefix());
view.setErrorOutputPrefix(current.getErrorOutputPrefix());
view.setCompressionFormat(current.getCompressionFormat());
view.setFileExtension(current.getFileExtension());
view.setCustomTimeZone(current.getCustomTimeZone());
view.setBufferingHints(current.getBufferingHints());
view.setEncryptionConfiguration(current.getEncryptionConfiguration());
view.setS3BackupMode(current.getS3BackupMode());
view.setDataFormatConversionConfiguration(current.getDataFormatConversionConfiguration());
mergeDestination(view, update);
return view;
}
public void tagDeliveryStream(String name, List<DeliveryStreamDescription.Tag> tagsToTag) {
@@ -1,8 +1,16 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OpenXJsonSerDe;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OrcSerDe;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ParquetSerDe;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.SchemaConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Serializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
@@ -17,44 +25,301 @@ import java.util.regex.Pattern;
* {@code extendedS3DestinationUpdate.compressionFormat} depending on the shape
* it arrived in. That is why the shape name is a parameter and validation runs
* from the handler, the layer that knows which shape was used.
*
* Multiple violations in one request are joined into a single
* "N validation errors detected" message separated by "; ", as real AWS's
* Smithy layer does (probe 2026-09-07: both ParquetSerDe bounds violated at
* once report "2 validation errors detected: ...; ...").
*/
final class S3DestinationValidator {
/** Listed in the order AWS prints it, which is neither declaration order nor alphabetical. */
private static final String ENUM_VALUE_SET = "[ZIP, HADOOP_SNAPPY, Snappy, GZIP, UNCOMPRESSED]";
private static final List<String> PARQUET_COMPRESSIONS = List.of("SNAPPY", "GZIP", "UNCOMPRESSED");
private static final String PARQUET_COMPRESSION_VALUE_SET = "[SNAPPY, GZIP, UNCOMPRESSED]";
private static final List<String> PARQUET_WRITER_VERSIONS = List.of("V1", "V2");
private static final String PARQUET_WRITER_VERSION_VALUE_SET = "[V1, V2]";
private static final String FILE_EXTENSION_REGEX = "^(|\\.[0-9a-z!\\-_.*'()]+)$";
private static final Pattern FILE_EXTENSION = Pattern.compile(FILE_EXTENSION_REGEX);
private static final int FILE_EXTENSION_MAX_LENGTH = 128;
private static final long PARQUET_MIN_BLOCK_SIZE_BYTES = 67108864;
private static final long PARQUET_MIN_PAGE_SIZE_BYTES = 65536;
private static final long PARQUET_MIN_MAX_PADDING_BYTES = 0;
private static final String SERIALIZER_PATH =
"dataFormatConversionConfiguration.outputFormatConfiguration.serializer";
private static final List<String> ORC_COMPRESSIONS = List.of("ZLIB", "SNAPPY", "NONE");
private static final String ORC_COMPRESSION_VALUE_SET = "[ZLIB, SNAPPY, NONE]";
private static final List<String> ORC_FORMAT_VERSIONS = List.of("V0_11", "V0_12");
private static final String ORC_FORMAT_VERSION_VALUE_SET = "[V0_11, V0_12]";
private static final long ORC_MIN_BLOCK_SIZE_BYTES = 67108864;
private static final long ORC_MIN_STRIPE_SIZE_BYTES = 8388608;
private static final int ORC_MIN_ROW_INDEX_STRIDE = 1000;
private static final double ORC_MIN_PROBABILITY = 0;
private static final double ORC_MAX_PROBABILITY = 1;
private static final int MAPPING_MAX_LENGTH = 1024;
private static final String NO_WHITESPACE_PATTERN = "^\\S+$";
private static final Pattern NO_WHITESPACE = Pattern.compile(NO_WHITESPACE_PATTERN);
// Applied as written rather than approximated with String.isBlank(): the two
// disagree in both directions, and AWS follows the pattern (probed). isBlank()
// would reject an ideographic space the pattern accepts, since \s here is ASCII
// only, and would accept a value holding a line break that "." cannot match.
private static final String NOT_BLANK_PATTERN = "^(?!\\s*$).+";
private static final Pattern NOT_BLANK = Pattern.compile(NOT_BLANK_PATTERN);
private S3DestinationValidator() {}
static void validateWireShape(S3Destination config, String shapeName) {
if (config == null) {
return;
}
List<String> violations = new ArrayList<>();
String compressionFormat = config.getCompressionFormat();
if (compressionFormat != null && FirehoseCompression.fromWireValue(compressionFormat).isEmpty()) {
throw constraintViolation(shapeName, "compressionFormat",
"Member must satisfy enum value set: " + ENUM_VALUE_SET);
violations.add(violation(shapeName, "compressionFormat",
"Member must satisfy enum value set: " + ENUM_VALUE_SET));
}
String fileExtension = config.getFileExtension();
if (fileExtension == null) {
return;
if (fileExtension != null) {
if (fileExtension.length() > FILE_EXTENSION_MAX_LENGTH) {
violations.add(violation(shapeName, "fileExtension",
"Member must have length less than or equal to " + FILE_EXTENSION_MAX_LENGTH));
} else if (!FILE_EXTENSION.matcher(fileExtension).matches()) {
violations.add(violation(shapeName, "fileExtension",
"Member must satisfy regular expression pattern: " + FILE_EXTENSION_REGEX));
}
}
if (fileExtension.length() > FILE_EXTENSION_MAX_LENGTH) {
throw constraintViolation(shapeName, "fileExtension",
"Member must have length less than or equal to " + FILE_EXTENSION_MAX_LENGTH);
Serializer serializer = serializer(config);
if (serializer != null) {
// Parquet first, then ORC, the order AWS prints when both carry a
// violation (they can only both be present on a request the semantic
// "more than one serializer" check rejects afterwards).
collectParquetSerDeViolations(serializer.getParquetSerDe(), shapeName, violations);
collectOrcSerDeViolations(serializer.getOrcSerDe(), shapeName, violations);
}
if (!FILE_EXTENSION.matcher(fileExtension).matches()) {
throw constraintViolation(shapeName, "fileExtension",
"Member must satisfy regular expression pattern: " + FILE_EXTENSION_REGEX);
// Serializer, then deserializer, then schema: the order AWS prints when
// violations sit in more than one of them.
collectOpenXMappingViolations(config, shapeName, violations);
collectSchemaViolations(config, shapeName, violations);
if (!violations.isEmpty()) {
throw constraintViolations(violations);
}
}
private static AwsException constraintViolation(String shapeName, String member, String constraint) {
return new AwsException("ValidationException",
"1 validation error detected: Value at '" + shapeName + "." + member
+ "' failed to satisfy constraint: " + constraint, 400);
/**
* Every SchemaConfiguration string is a 1 to 1024 character value without
* whitespace, and unlike the collection members each broken rule is its own
* violation rather than one bracketed set. Member order is AWS's (probed), as is
* the {@code roleARN} spelling, which keeps ARN capitalised where the semantic
* message for the same member spells it RoleArn.
*
* A malformed but non-empty role ARN never reaches these rules on AWS: an
* InvalidParameterValueException ("Invalid role ARN.") preempts them. Floci
* validates no ARNs, so it answers only the length and pattern rules here, which
* is what an empty role ARN trips on AWS too.
*/
private static void collectSchemaViolations(S3Destination config, String shapeName,
List<String> violations) {
var conversion = config.getDataFormatConversionConfiguration();
if (conversion == null || conversion.getSchemaConfiguration() == null) {
return;
}
SchemaConfiguration schema = conversion.getSchemaConfiguration();
String path = "dataFormatConversionConfiguration.schemaConfiguration";
collectSchemaMember(schema.getVersionId(), shapeName, path + ".versionId", violations);
collectSchemaMember(schema.getCatalogId(), shapeName, path + ".catalogId", violations);
collectSchemaMember(schema.getDatabaseName(), shapeName, path + ".databaseName", violations);
collectSchemaMember(schema.getRoleArn(), shapeName, path + ".roleARN", violations);
collectSchemaMember(schema.getRegion(), shapeName, path + ".region", violations);
collectSchemaMember(schema.getTableName(), shapeName, path + ".tableName", violations);
}
private static void collectSchemaMember(String value, String shapeName, String member,
List<String> violations) {
if (value == null) {
return;
}
if (value.isEmpty()) {
violations.add(violation(shapeName, member, "Member must have length greater than or equal to 1"));
} else if (value.length() > MAPPING_MAX_LENGTH) {
violations.add(violation(shapeName, member,
"Member must have length less than or equal to " + MAPPING_MAX_LENGTH));
}
if (!NO_WHITESPACE.matcher(value).matches()) {
violations.add(violation(shapeName, member,
"Member must satisfy regular expression pattern: " + NO_WHITESPACE_PATTERN));
}
}
/**
* The only collection member whose element constraints Floci enforces; the ones
* on OrcSerDe.BloomFilterColumns and HiveJsonSerDe.TimestampFormats are a
* documented gap. AWS reports the whole constraint set whichever part failed, at
* most once for the keys and once for the values, and applies a different pattern
* to each: keys may hold no whitespace at all, values merely may not be blank.
*/
private static void collectOpenXMappingViolations(S3Destination config, String shapeName,
List<String> violations) {
var conversion = config.getDataFormatConversionConfiguration();
if (conversion == null || conversion.getInputFormatConfiguration() == null
|| conversion.getInputFormatConfiguration().getDeserializer() == null) {
return;
}
OpenXJsonSerDe openX = conversion.getInputFormatConfiguration().getDeserializer().getOpenXJsonSerDe();
if (openX == null || openX.getColumnToJsonKeyMappings() == null) {
return;
}
String member = "dataFormatConversionConfiguration.inputFormatConfiguration.deserializer"
+ ".openXJsonSerDe.columnToJsonKeyMappings";
boolean keyViolation = false;
boolean valueViolation = false;
for (Map.Entry<String, String> mapping : openX.getColumnToJsonKeyMappings().entrySet()) {
keyViolation |= !isMappingKeyValid(mapping.getKey());
valueViolation |= !isMappingValueValid(mapping.getValue());
}
if (keyViolation) {
violations.add(violation(shapeName, member,
"Map keys must satisfy constraint: " + constraintSet(NO_WHITESPACE_PATTERN)));
}
if (valueViolation) {
violations.add(violation(shapeName, member,
"Map value must satisfy constraint: " + constraintSet(NOT_BLANK_PATTERN)));
}
}
private static boolean isMappingKeyValid(String key) {
return key != null && lengthInRange(key) && NO_WHITESPACE.matcher(key).matches();
}
private static boolean isMappingValueValid(String value) {
return value != null && lengthInRange(value) && NOT_BLANK.matcher(value).matches();
}
private static boolean lengthInRange(String value) {
return !value.isEmpty() && value.length() <= MAPPING_MAX_LENGTH;
}
private static String constraintSet(String pattern) {
return "[Member must have length less than or equal to " + MAPPING_MAX_LENGTH
+ ", Member must have length greater than or equal to 1"
+ ", Member must satisfy regular expression pattern: " + pattern + "]";
}
private static Serializer serializer(S3Destination config) {
var conversion = config.getDataFormatConversionConfiguration();
if (conversion == null || conversion.getOutputFormatConfiguration() == null) {
return null;
}
return conversion.getOutputFormatConfiguration().getSerializer();
}
/**
* Smithy-level bounds on ParquetSerDe, enforced whenever the member is present,
* even on a disabled conversion configuration: they are model constraints, not
* the semantic checks {@link DataFormatConversionValidator} gates on Enabled.
*/
private static void collectParquetSerDeViolations(ParquetSerDe parquet, String shapeName,
List<String> violations) {
if (parquet == null) {
return;
}
String parquetPath = SERIALIZER_PATH + ".parquetSerDe";
// Member order follows the one AWS prints when several constraints fail at
// once, which is neither declaration order nor alphabetical (probed with all
// five violated in a single request).
if (parquet.getMaxPaddingBytes() != null && parquet.getMaxPaddingBytes() < PARQUET_MIN_MAX_PADDING_BYTES) {
violations.add(violation(shapeName, parquetPath + ".maxPaddingBytes",
"Member must have value greater than or equal to " + PARQUET_MIN_MAX_PADDING_BYTES));
}
if (parquet.getBlockSizeBytes() != null && parquet.getBlockSizeBytes() < PARQUET_MIN_BLOCK_SIZE_BYTES) {
violations.add(violation(shapeName, parquetPath + ".blockSizeBytes",
"Member must have value greater than or equal to " + PARQUET_MIN_BLOCK_SIZE_BYTES));
}
if (parquet.getPageSizeBytes() != null && parquet.getPageSizeBytes() < PARQUET_MIN_PAGE_SIZE_BYTES) {
violations.add(violation(shapeName, parquetPath + ".pageSizeBytes",
"Member must have value greater than or equal to " + PARQUET_MIN_PAGE_SIZE_BYTES));
}
if (parquet.getCompression() != null && !PARQUET_COMPRESSIONS.contains(parquet.getCompression())) {
violations.add(violation(shapeName, parquetPath + ".compression",
"Member must satisfy enum value set: " + PARQUET_COMPRESSION_VALUE_SET));
}
if (parquet.getWriterVersion() != null && !PARQUET_WRITER_VERSIONS.contains(parquet.getWriterVersion())) {
violations.add(violation(shapeName, parquetPath + ".writerVersion",
"Member must satisfy enum value set: " + PARQUET_WRITER_VERSION_VALUE_SET));
}
}
/**
* The ORC counterpart. Floci rejects an enabled OrcSerDe semantically, but these
* are model constraints: they apply to a disabled configuration too, and AWS
* reports them before any semantic error. Member order and the enum spellings
* (note {@code [ZLIB, SNAPPY, NONE]}) were probed with all eight violated at once.
*/
private static void collectOrcSerDeViolations(OrcSerDe orc, String shapeName, List<String> violations) {
if (orc == null) {
return;
}
String orcPath = SERIALIZER_PATH + ".orcSerDe";
collectRange(orc.getDictionaryKeyThreshold(), shapeName, orcPath + ".dictionaryKeyThreshold",
ORC_MIN_PROBABILITY, ORC_MAX_PROBABILITY, violations);
if (orc.getBlockSizeBytes() != null && orc.getBlockSizeBytes() < ORC_MIN_BLOCK_SIZE_BYTES) {
violations.add(violation(shapeName, orcPath + ".blockSizeBytes",
"Member must have value greater than or equal to " + ORC_MIN_BLOCK_SIZE_BYTES));
}
if (orc.getRowIndexStride() != null && orc.getRowIndexStride() < ORC_MIN_ROW_INDEX_STRIDE) {
violations.add(violation(shapeName, orcPath + ".rowIndexStride",
"Member must have value greater than or equal to " + ORC_MIN_ROW_INDEX_STRIDE));
}
collectRange(orc.getPaddingTolerance(), shapeName, orcPath + ".paddingTolerance",
ORC_MIN_PROBABILITY, ORC_MAX_PROBABILITY, violations);
if (orc.getStripeSizeBytes() != null && orc.getStripeSizeBytes() < ORC_MIN_STRIPE_SIZE_BYTES) {
violations.add(violation(shapeName, orcPath + ".stripeSizeBytes",
"Member must have value greater than or equal to " + ORC_MIN_STRIPE_SIZE_BYTES));
}
if (orc.getCompression() != null && !ORC_COMPRESSIONS.contains(orc.getCompression())) {
violations.add(violation(shapeName, orcPath + ".compression",
"Member must satisfy enum value set: " + ORC_COMPRESSION_VALUE_SET));
}
if (orc.getFormatVersion() != null && !ORC_FORMAT_VERSIONS.contains(orc.getFormatVersion())) {
violations.add(violation(shapeName, orcPath + ".formatVersion",
"Member must satisfy enum value set: " + ORC_FORMAT_VERSION_VALUE_SET));
}
collectRange(orc.getBloomFilterFalsePositiveProbability(), shapeName,
orcPath + ".bloomFilterFalsePositiveProbability",
ORC_MIN_PROBABILITY, ORC_MAX_PROBABILITY, violations);
}
/** AWS reports only the bound that was crossed, never both. */
private static void collectRange(Double value, String shapeName, String member,
double min, double max, List<String> violations) {
if (value == null) {
return;
}
// NaN satisfies neither comparison, so it would slip through a plain
// greater/less pair. AWS reports both bounds for it, the upper one first,
// and one bound for each infinity (probed).
boolean notANumber = Double.isNaN(value);
if (notANumber || value > max) {
violations.add(violation(shapeName, member,
"Member must have value less than or equal to " + (long) max));
}
if (notANumber || value < min) {
violations.add(violation(shapeName, member,
"Member must have value greater than or equal to " + (long) min));
}
}
private static String violation(String shapeName, String member, String constraint) {
return "Value at '" + shapeName + "." + member + "' failed to satisfy constraint: " + constraint;
}
private static AwsException constraintViolations(List<String> violations) {
String header = violations.size() == 1
? "1 validation error detected: "
: violations.size() + " validation errors detected: ";
return new AwsException("ValidationException", header + String.join("; ", violations), 400);
}
}
@@ -1,12 +1,14 @@
package io.github.hectorvent.floci.services.firehose.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
@RegisterForReflection
@@ -214,6 +216,8 @@ public class DeliveryStreamDescription {
private EncryptionConfiguration encryptionConfiguration;
@JsonProperty("S3BackupMode")
private String s3BackupMode;
@JsonProperty("DataFormatConversionConfiguration")
private DataFormatConversionConfiguration dataFormatConversionConfiguration;
public S3Destination() {}
public String getRoleArn() { return roleArn; }
@@ -236,6 +240,27 @@ public class DeliveryStreamDescription {
public void setEncryptionConfiguration(EncryptionConfiguration encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; }
public String getS3BackupMode() { return s3BackupMode; }
public void setS3BackupMode(String s3BackupMode) { this.s3BackupMode = s3BackupMode; }
public DataFormatConversionConfiguration getDataFormatConversionConfiguration() {
return dataFormatConversionConfiguration;
}
public void setDataFormatConversionConfiguration(DataFormatConversionConfiguration configuration) {
this.dataFormatConversionConfiguration = configuration;
}
/**
* True when data format conversion applies to deliveries: the configuration is
* present and not explicitly disabled. AWS treats an omitted Enabled as enabled
* (probe: a config without Enabled is validated exactly like an enabled one).
*
* Ignored for serialization: an {@code is...} accessor with no backing field of
* that name is a property to Jackson, which would put a non-AWS
* {@code dataFormatConversionEnabled} member in every destination it renders.
*/
@JsonIgnore
public boolean isDataFormatConversionEnabled() {
return dataFormatConversionConfiguration != null
&& !Boolean.FALSE.equals(dataFormatConversionConfiguration.getEnabled());
}
/**
* Fills the members the wire contract marks required with the AWS defaults.
@@ -252,16 +277,24 @@ public class DeliveryStreamDescription {
if (encryptionConfiguration == null) {
encryptionConfiguration = EncryptionConfiguration.noEncryption();
}
// A conversion-enabled destination that specified no hints gets AWS's
// larger default size, verified against the service: the stored hints
// come back as 128 MiB, not the ordinary 5 MiB, while the interval
// default is unchanged. Filling in 5 here would report a size AWS never
// uses and would then fail the 64 MiB floor on the stream's next update.
int defaultSizeInMBs = isDataFormatConversionEnabled()
? BufferingHints.CONVERSION_DEFAULT_SIZE_MBS
: BufferingHints.DEFAULT_SIZE_MBS;
if (bufferingHints == null) {
bufferingHints = BufferingHints.defaults();
bufferingHints = BufferingHints.defaults(defaultSizeInMBs);
} else {
// Self-heal legacy persisted state; validation keeps partial
// hints out of the create/update paths.
if (bufferingHints.getSizeInMBs() == null) {
bufferingHints.setSizeInMBs(5);
bufferingHints.setSizeInMBs(defaultSizeInMBs);
}
if (bufferingHints.getIntervalInSeconds() == null) {
bufferingHints.setIntervalInSeconds(300);
bufferingHints.setIntervalInSeconds(BufferingHints.DEFAULT_INTERVAL_SECONDS);
}
}
}
@@ -292,6 +325,270 @@ public class DeliveryStreamDescription {
}
}
/**
* Members stay null-honest, mirroring real AWS: DescribeDeliveryStream echoes the
* configuration exactly as it was given (an empty ParquetSerDe stays {}, CatalogId
* and VersionId are not materialized), and UpdateDestination merges member-wise, so
* "not specified" must remain distinguishable from a value.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class DataFormatConversionConfiguration {
@JsonProperty("Enabled")
private Boolean enabled;
@JsonProperty("SchemaConfiguration")
private SchemaConfiguration schemaConfiguration;
@JsonProperty("InputFormatConfiguration")
private InputFormatConfiguration inputFormatConfiguration;
@JsonProperty("OutputFormatConfiguration")
private OutputFormatConfiguration outputFormatConfiguration;
public DataFormatConversionConfiguration() {}
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public SchemaConfiguration getSchemaConfiguration() { return schemaConfiguration; }
public void setSchemaConfiguration(SchemaConfiguration schemaConfiguration) {
this.schemaConfiguration = schemaConfiguration;
}
public InputFormatConfiguration getInputFormatConfiguration() { return inputFormatConfiguration; }
public void setInputFormatConfiguration(InputFormatConfiguration inputFormatConfiguration) {
this.inputFormatConfiguration = inputFormatConfiguration;
}
public OutputFormatConfiguration getOutputFormatConfiguration() { return outputFormatConfiguration; }
public void setOutputFormatConfiguration(OutputFormatConfiguration outputFormatConfiguration) {
this.outputFormatConfiguration = outputFormatConfiguration;
}
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class SchemaConfiguration {
@JsonProperty("RoleARN")
private String roleArn;
@JsonProperty("CatalogId")
private String catalogId;
@JsonProperty("DatabaseName")
private String databaseName;
@JsonProperty("TableName")
private String tableName;
@JsonProperty("Region")
private String region;
@JsonProperty("VersionId")
private String versionId;
public SchemaConfiguration() {}
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public String getCatalogId() { return catalogId; }
public void setCatalogId(String catalogId) { this.catalogId = catalogId; }
public String getDatabaseName() { return databaseName; }
public void setDatabaseName(String databaseName) { this.databaseName = databaseName; }
public String getTableName() { return tableName; }
public void setTableName(String tableName) { this.tableName = tableName; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getVersionId() { return versionId; }
public void setVersionId(String versionId) { this.versionId = versionId; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class InputFormatConfiguration {
@JsonProperty("Deserializer")
private Deserializer deserializer;
public InputFormatConfiguration() {}
public Deserializer getDeserializer() { return deserializer; }
public void setDeserializer(Deserializer deserializer) { this.deserializer = deserializer; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Deserializer {
@JsonProperty("OpenXJsonSerDe")
private OpenXJsonSerDe openXJsonSerDe;
@JsonProperty("HiveJsonSerDe")
private HiveJsonSerDe hiveJsonSerDe;
public Deserializer() {}
public OpenXJsonSerDe getOpenXJsonSerDe() { return openXJsonSerDe; }
public void setOpenXJsonSerDe(OpenXJsonSerDe openXJsonSerDe) { this.openXJsonSerDe = openXJsonSerDe; }
public HiveJsonSerDe getHiveJsonSerDe() { return hiveJsonSerDe; }
public void setHiveJsonSerDe(HiveJsonSerDe hiveJsonSerDe) { this.hiveJsonSerDe = hiveJsonSerDe; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class OpenXJsonSerDe {
@JsonProperty("ConvertDotsInJsonKeysToUnderscores")
private Boolean convertDotsInJsonKeysToUnderscores;
@JsonProperty("CaseInsensitive")
private Boolean caseInsensitive;
@JsonProperty("ColumnToJsonKeyMappings")
private Map<String, String> columnToJsonKeyMappings;
public OpenXJsonSerDe() {}
public Boolean getConvertDotsInJsonKeysToUnderscores() { return convertDotsInJsonKeysToUnderscores; }
public void setConvertDotsInJsonKeysToUnderscores(Boolean convertDotsInJsonKeysToUnderscores) {
this.convertDotsInJsonKeysToUnderscores = convertDotsInJsonKeysToUnderscores;
}
public Boolean getCaseInsensitive() { return caseInsensitive; }
public void setCaseInsensitive(Boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; }
public Map<String, String> getColumnToJsonKeyMappings() { return columnToJsonKeyMappings; }
public void setColumnToJsonKeyMappings(Map<String, String> columnToJsonKeyMappings) {
this.columnToJsonKeyMappings = columnToJsonKeyMappings;
}
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class HiveJsonSerDe {
@JsonProperty("TimestampFormats")
private List<String> timestampFormats;
public HiveJsonSerDe() {}
public List<String> getTimestampFormats() { return timestampFormats; }
public void setTimestampFormats(List<String> timestampFormats) { this.timestampFormats = timestampFormats; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class OutputFormatConfiguration {
@JsonProperty("Serializer")
private Serializer serializer;
public OutputFormatConfiguration() {}
public Serializer getSerializer() { return serializer; }
public void setSerializer(Serializer serializer) { this.serializer = serializer; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Serializer {
@JsonProperty("ParquetSerDe")
private ParquetSerDe parquetSerDe;
@JsonProperty("OrcSerDe")
private OrcSerDe orcSerDe;
public Serializer() {}
public ParquetSerDe getParquetSerDe() { return parquetSerDe; }
public void setParquetSerDe(ParquetSerDe parquetSerDe) { this.parquetSerDe = parquetSerDe; }
public OrcSerDe getOrcSerDe() { return orcSerDe; }
public void setOrcSerDe(OrcSerDe orcSerDe) { this.orcSerDe = orcSerDe; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class ParquetSerDe {
@JsonProperty("BlockSizeBytes")
private Long blockSizeBytes;
@JsonProperty("PageSizeBytes")
private Long pageSizeBytes;
@JsonProperty("Compression")
private String compression;
@JsonProperty("EnableDictionaryCompression")
private Boolean enableDictionaryCompression;
@JsonProperty("MaxPaddingBytes")
private Long maxPaddingBytes;
@JsonProperty("WriterVersion")
private String writerVersion;
public ParquetSerDe() {}
public Long getBlockSizeBytes() { return blockSizeBytes; }
public void setBlockSizeBytes(Long blockSizeBytes) { this.blockSizeBytes = blockSizeBytes; }
public Long getPageSizeBytes() { return pageSizeBytes; }
public void setPageSizeBytes(Long pageSizeBytes) { this.pageSizeBytes = pageSizeBytes; }
public String getCompression() { return compression; }
public void setCompression(String compression) { this.compression = compression; }
public Boolean getEnableDictionaryCompression() { return enableDictionaryCompression; }
public void setEnableDictionaryCompression(Boolean enableDictionaryCompression) {
this.enableDictionaryCompression = enableDictionaryCompression;
}
public Long getMaxPaddingBytes() { return maxPaddingBytes; }
public void setMaxPaddingBytes(Long maxPaddingBytes) { this.maxPaddingBytes = maxPaddingBytes; }
public String getWriterVersion() { return writerVersion; }
public void setWriterVersion(String writerVersion) { this.writerVersion = writerVersion; }
}
/**
* Floci rejects an <em>enabled</em> OrcSerDe configuration (DuckDB cannot write
* ORC), but a disabled one is stored like any other, so the members are mapped:
* a marker class would silently drop them through {@code ignoreUnknown} and
* DescribeDeliveryStream could no longer echo the configuration as supplied.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class OrcSerDe {
@JsonProperty("StripeSizeBytes")
private Long stripeSizeBytes;
@JsonProperty("BlockSizeBytes")
private Long blockSizeBytes;
@JsonProperty("RowIndexStride")
private Integer rowIndexStride;
@JsonProperty("EnablePadding")
private Boolean enablePadding;
@JsonProperty("PaddingTolerance")
private Double paddingTolerance;
@JsonProperty("Compression")
private String compression;
@JsonProperty("BloomFilterColumns")
private List<String> bloomFilterColumns;
@JsonProperty("BloomFilterFalsePositiveProbability")
private Double bloomFilterFalsePositiveProbability;
@JsonProperty("DictionaryKeyThreshold")
private Double dictionaryKeyThreshold;
@JsonProperty("FormatVersion")
private String formatVersion;
public OrcSerDe() {}
public Long getStripeSizeBytes() { return stripeSizeBytes; }
public void setStripeSizeBytes(Long stripeSizeBytes) { this.stripeSizeBytes = stripeSizeBytes; }
public Long getBlockSizeBytes() { return blockSizeBytes; }
public void setBlockSizeBytes(Long blockSizeBytes) { this.blockSizeBytes = blockSizeBytes; }
public Integer getRowIndexStride() { return rowIndexStride; }
public void setRowIndexStride(Integer rowIndexStride) { this.rowIndexStride = rowIndexStride; }
public Boolean getEnablePadding() { return enablePadding; }
public void setEnablePadding(Boolean enablePadding) { this.enablePadding = enablePadding; }
public Double getPaddingTolerance() { return paddingTolerance; }
public void setPaddingTolerance(Double paddingTolerance) { this.paddingTolerance = paddingTolerance; }
public String getCompression() { return compression; }
public void setCompression(String compression) { this.compression = compression; }
public List<String> getBloomFilterColumns() { return bloomFilterColumns; }
public void setBloomFilterColumns(List<String> bloomFilterColumns) {
this.bloomFilterColumns = bloomFilterColumns;
}
public Double getBloomFilterFalsePositiveProbability() { return bloomFilterFalsePositiveProbability; }
public void setBloomFilterFalsePositiveProbability(Double bloomFilterFalsePositiveProbability) {
this.bloomFilterFalsePositiveProbability = bloomFilterFalsePositiveProbability;
}
public Double getDictionaryKeyThreshold() { return dictionaryKeyThreshold; }
public void setDictionaryKeyThreshold(Double dictionaryKeyThreshold) {
this.dictionaryKeyThreshold = dictionaryKeyThreshold;
}
public String getFormatVersion() { return formatVersion; }
public void setFormatVersion(String formatVersion) { this.formatVersion = formatVersion; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@@ -329,12 +626,17 @@ public class DeliveryStreamDescription {
/**
* Members stay boxed and null-honest so validation can tell "not specified"
* from a value: AWS requires SizeInMBs and IntervalInSeconds to be specified
* together, and the defaults (5 MiB / 300 s) apply only when the whole
* object is absent.
* together, and the defaults apply only when the whole object is absent. The
* size default depends on the destination (see
* {@link S3Destination#applyDefaults()}); the interval default does not.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class BufferingHints {
static final int DEFAULT_SIZE_MBS = 5;
static final int CONVERSION_DEFAULT_SIZE_MBS = 128;
static final int DEFAULT_INTERVAL_SECONDS = 300;
@JsonProperty("SizeInMBs")
private Integer sizeInMBs;
@JsonProperty("IntervalInSeconds")
@@ -343,9 +645,13 @@ public class DeliveryStreamDescription {
public BufferingHints() {}
public static BufferingHints defaults() {
return defaults(DEFAULT_SIZE_MBS);
}
static BufferingHints defaults(int sizeInMBs) {
BufferingHints hints = new BufferingHints();
hints.sizeInMBs = 5;
hints.intervalInSeconds = 300;
hints.sizeInMBs = sizeInMBs;
hints.intervalInSeconds = DEFAULT_INTERVAL_SECONDS;
return hints;
}