mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 14:30:28 -05:00
feat(firehose): honor CompressionFormat and FileExtension on S3 delivery (#2410)
Firehose accepted CompressionFormat on the control plane and echoed it back on DescribeDeliveryStream, but the delivery path never read it: every delivered object held the raw record bytes, with no compression extension in the key and no Content-Encoding. The divergence was silent, since only a consumer reading the delivered objects (Athena over .gz, Spark reading Snappy, anything that decompresses by extension or encoding) ever saw the wrong bytes. Deliveries are now compressed the way real AWS compresses them: UNCOMPRESSED (no extension) (no Content-Encoding) GZIP .gz gzip ZIP .zip zip single deflated entry, UUID name Snappy .snappy snappy-java xerial stream format HADOOP_SNAPPY .snappy hadoop-snappy Hadoop block framing Snappy is the xerial snappy-java stream format, not the official Snappy framing format, so a consumer must use snappy-java's own reader; HADOOP_SNAPPY is the block framing Hadoop and Spark consumers read. Both are reproduced byte for byte against real AWS. HADOOP_SNAPPY deliberately carries .snappy rather than the .hsnappy the S3 object name documentation tables: the service delivers .snappy, reproduced on two separate dates, and only Content-Encoding tells the two variants apart. Content-Type is now application/octet-stream for every format, including UNCOMPRESSED, matching AWS instead of the previous application/x-ndjson. Buffered records are concatenated as bytes rather than through a String. Record payloads are arbitrary bytes, and compression makes the corruption of anything that is not valid UTF-8 observable. FileExtension is implemented alongside it, since it governs the same part of the key: it replaces the extension the compression format contributes instead of being appended to it, the empty string means "not specified", and it changes only the key, never the body or its Content-Encoding. Building the extension into the key belongs to S3ObjectKeyResolver, which already owns the key format, so the resolver now takes the destination and resolves prefix, time zone and extension together. Both members are validated, with the code and message shape captured from real AWS's raw HTTP responses rather than from an SDK's rendering of them. Unsupported values answer ValidationException naming the shape that carried them, so the same bad value reports extendedS3DestinationConfiguration.compressionFormat, s3DestinationConfiguration.compressionFormat or extendedS3DestinationUpdate.compressionFormat, which is why the wire-shape check runs from the handler. snappy-java becomes a direct dependency: it is the only Java library that writes the xerial stream format, it already shipped as a runtime-scope transitive of kafka-clients, and its version comes from the Quarkus BOM. For the GraalVM native image the loader needs run-time initialization; left to build-time initialization the image still builds and then dies with UnsatisfiedLinkError on the first compression. Snappy and SnappyLoader are the only classes on the compression path with a static initializer, which jdeps and a set of Mandrel 25.0.4 builds confirm is the whole requirement. Two deviations from AWS are documented rather than changed, both newly verified while testing this: Floci appends a newline after records that lack one where AWS inserts no separator at all, and Floci accepts streams with no destination configuration where AWS requires exactly one complete destination. Closes #2328 Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
This commit is contained in:
1 parent
29b0d600c6
commit
bba5ffb644
18 files changed
+1422
-53
No files matched your search
@@ -0,0 +1,133 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.xerial.snappy.SnappyHadoopCompatibleOutputStream;
|
||||
import org.xerial.snappy.SnappyOutputStream;
|
||||
|
||||
/**
|
||||
* The {@code CompressionFormat} values Firehose applies when it delivers to S3,
|
||||
* each paired with the object-key extension and {@code Content-Encoding} AWS
|
||||
* uses for it (verified against objects delivered by real AWS, see
|
||||
* https://github.com/floci-io/floci/issues/2328). The two Snappy variants come
|
||||
* out byte-identical to AWS's; gzip and zip match in container format but not
|
||||
* byte for byte, since deflate output and the zip entry name are not reproducible.
|
||||
*
|
||||
* Both Snappy variants are container formats around the same Snappy algorithm:
|
||||
* {@code Snappy} is the xerial snappy-java stream format (magic
|
||||
* {@code 0x82 "SNAPPY" 0x00}), <em>not</em> the official framing format, and
|
||||
* {@code HADOOP_SNAPPY} is Hadoop's block framing. snappy-java is the only Java
|
||||
* library that writes the former, which is why it is a direct dependency.
|
||||
*
|
||||
* {@code HADOOP_SNAPPY} deliberately carries {@code .snappy} even though the S3
|
||||
* object name documentation tables it as {@code .hsnappy}: the service delivers
|
||||
* {@code .snappy}, reproduced on two separate dates, and only the
|
||||
* {@code Content-Encoding} tells the two variants apart. Follow the service.
|
||||
*/
|
||||
enum FirehoseCompression {
|
||||
|
||||
UNCOMPRESSED("UNCOMPRESSED", "", null),
|
||||
GZIP("GZIP", ".gz", "gzip"),
|
||||
ZIP("ZIP", ".zip", "zip"),
|
||||
SNAPPY("Snappy", ".snappy", "snappy-java"),
|
||||
HADOOP_SNAPPY("HADOOP_SNAPPY", ".snappy", "hadoop-snappy");
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FirehoseCompression.class);
|
||||
|
||||
private final String wireValue;
|
||||
private final String extension;
|
||||
private final String contentEncoding;
|
||||
|
||||
FirehoseCompression(String wireValue, String extension, String contentEncoding) {
|
||||
this.wireValue = wireValue;
|
||||
this.extension = extension;
|
||||
this.contentEncoding = contentEncoding;
|
||||
}
|
||||
|
||||
String wireValue() {
|
||||
return wireValue;
|
||||
}
|
||||
|
||||
/** Key suffix AWS appends for this format, empty for {@code UNCOMPRESSED}. */
|
||||
String extension() {
|
||||
return extension;
|
||||
}
|
||||
|
||||
/** {@code Content-Encoding} AWS sets on the delivered object, null for {@code UNCOMPRESSED}. */
|
||||
String contentEncoding() {
|
||||
return contentEncoding;
|
||||
}
|
||||
|
||||
/** Exact-case lookup, the way AWS matches the enum ({@code SNAPPY} is not {@code Snappy}). */
|
||||
static Optional<FirehoseCompression> fromWireValue(String value) {
|
||||
for (FirehoseCompression format : values()) {
|
||||
if (format.wireValue.equals(value)) {
|
||||
return Optional.of(format);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the format for a delivery, never failing: a stream persisted
|
||||
* before this validation existed can still hold a value create-time
|
||||
* validation would reject today, and dropping records over it would be
|
||||
* worse than delivering them uncompressed.
|
||||
*/
|
||||
static FirehoseCompression forDelivery(String value) {
|
||||
if (value == null) {
|
||||
return UNCOMPRESSED;
|
||||
}
|
||||
return fromWireValue(value).orElseGet(() -> {
|
||||
LOG.warnv("Unsupported Firehose CompressionFormat {0}, delivering uncompressed", value);
|
||||
return UNCOMPRESSED;
|
||||
});
|
||||
}
|
||||
|
||||
byte[] compress(byte[] payload) throws IOException {
|
||||
return switch (this) {
|
||||
case UNCOMPRESSED -> payload;
|
||||
case GZIP -> encode(payload, GZIPOutputStream::new);
|
||||
case ZIP -> zip(payload);
|
||||
case SNAPPY -> encode(payload, SnappyOutputStream::new);
|
||||
case HADOOP_SNAPPY -> encode(payload, SnappyHadoopCompatibleOutputStream::new);
|
||||
};
|
||||
}
|
||||
|
||||
private static byte[] encode(byte[] payload, StreamFactory factory) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(estimatedSize(payload));
|
||||
try (OutputStream compressor = factory.wrap(out)) {
|
||||
compressor.write(payload);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** AWS delivers a single deflated entry whose name is a UUID unrelated to the object key. */
|
||||
private static byte[] zip(byte[] payload) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(estimatedSize(payload));
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
zip.putNextEntry(new ZipEntry(UUID.randomUUID().toString()));
|
||||
zip.write(payload);
|
||||
zip.closeEntry();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static int estimatedSize(byte[] payload) {
|
||||
return Math.max(64, payload.length / 4);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface StreamFactory {
|
||||
OutputStream wrap(OutputStream out) throws IOException;
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,10 @@ public class FirehoseJsonHandler {
|
||||
S3Destination s3 = null;
|
||||
if (request.has("S3DestinationConfiguration")) {
|
||||
s3 = mapper.treeToValue(request.get("S3DestinationConfiguration"), S3Destination.class);
|
||||
S3DestinationValidator.validateWireShape(s3, "s3DestinationConfiguration");
|
||||
} else if (request.has("ExtendedS3DestinationConfiguration")) {
|
||||
s3 = mapper.treeToValue(request.get("ExtendedS3DestinationConfiguration"), S3Destination.class);
|
||||
S3DestinationValidator.validateWireShape(s3, "extendedS3DestinationConfiguration");
|
||||
}
|
||||
List<io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Tag> tags = new ArrayList<>();
|
||||
if (request.has("Tags")) {
|
||||
@@ -70,8 +72,10 @@ public class FirehoseJsonHandler {
|
||||
S3Destination update = null;
|
||||
if (request.has("ExtendedS3DestinationUpdate")) {
|
||||
update = mapper.treeToValue(request.get("ExtendedS3DestinationUpdate"), S3Destination.class);
|
||||
S3DestinationValidator.validateWireShape(update, "extendedS3DestinationUpdate");
|
||||
} else if (request.has("S3DestinationUpdate")) {
|
||||
update = mapper.treeToValue(request.get("S3DestinationUpdate"), S3Destination.class);
|
||||
S3DestinationValidator.validateWireShape(update, "s3DestinationUpdate");
|
||||
}
|
||||
firehoseService.updateDestination(name, currentVersionId, destinationId, update);
|
||||
yield Response.ok(Map.of()).build();
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
import io.github.hectorvent.floci.services.firehose.model.Record;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
|
||||
import io.quarkus.runtime.ShutdownDelayInitiatedEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -19,10 +20,9 @@ import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -229,6 +229,7 @@ public class FirehoseService {
|
||||
if (update.getPrefix() != null) current.setPrefix(update.getPrefix());
|
||||
if (update.getErrorOutputPrefix() != null) current.setErrorOutputPrefix(update.getErrorOutputPrefix());
|
||||
if (update.getCompressionFormat() != null) current.setCompressionFormat(update.getCompressionFormat());
|
||||
if (update.getFileExtension() != null) current.setFileExtension(update.getFileExtension());
|
||||
if (update.getCustomTimeZone() != null) current.setCustomTimeZone(update.getCustomTimeZone());
|
||||
if (update.getBufferingHints() != null) current.setBufferingHints(update.getBufferingHints());
|
||||
if (update.getEncryptionConfiguration() != null) current.setEncryptionConfiguration(update.getEncryptionConfiguration());
|
||||
@@ -370,24 +371,32 @@ public class FirehoseService {
|
||||
try {
|
||||
String bucket = resolveBucket(stream);
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
ZoneId zone = S3ObjectKeyResolver.resolveZone(s3 != null ? s3.getCustomTimeZone() : null);
|
||||
String key = S3ObjectKeyResolver.resolveKey(s3 != null ? s3.getPrefix() : null,
|
||||
stream.getDeliveryStreamName(), stream.getVersionId(), clock.instant(), zone);
|
||||
FirehoseCompression compression =
|
||||
FirehoseCompression.forDelivery(s3 == null ? null : s3.getCompressionFormat());
|
||||
String key = S3ObjectKeyResolver.resolveKey(s3, stream.getDeliveryStreamName(),
|
||||
stream.getVersionId(), clock.instant(), compression);
|
||||
|
||||
ensureBucket(bucket);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// Records are arbitrary bytes, so they are concatenated as bytes: routing
|
||||
// them through a String would corrupt any payload that is not valid UTF-8.
|
||||
// The appended newline is a deliberate deviation kept from before this
|
||||
// method compressed anything: real AWS inserts no separator at all
|
||||
// (verified: three "abc" records arrive as the 9 bytes "abcabcabc").
|
||||
// See the deviation noted in docs/services/firehose.md.
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
for (byte[] data : toFlush) {
|
||||
sb.append(new String(data, StandardCharsets.UTF_8));
|
||||
if (!sb.isEmpty() && sb.charAt(sb.length() - 1) != '\n') {
|
||||
sb.append('\n');
|
||||
payload.writeBytes(data);
|
||||
if (data.length > 0 && data[data.length - 1] != '\n') {
|
||||
payload.write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
byte[] body = sb.toString().getBytes(StandardCharsets.UTF_8);
|
||||
s3Service.putObject(bucket, key, body, "application/x-ndjson", Map.of());
|
||||
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3}",
|
||||
toFlush.size(), streamName, bucket, key);
|
||||
byte[] body = compression.compress(payload.toByteArray());
|
||||
s3Service.putObject(bucket, key, body, "application/octet-stream", Map.of(),
|
||||
new PutObjectOptions().withContentEncoding(compression.contentEncoding()));
|
||||
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3} ({4})",
|
||||
toFlush.size(), streamName, bucket, key, compression.wireValue());
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Failed to flush Firehose stream {0}: {1}", streamName, e.getMessage());
|
||||
}
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rejects S3 destination members AWS refuses, with the error code and message
|
||||
* shape captured from real AWS's raw wire responses (see
|
||||
* https://github.com/floci-io/floci/issues/2328).
|
||||
*
|
||||
* AWS names the member that carried the offending value, so the same bad
|
||||
* {@code CompressionFormat} reports
|
||||
* {@code extendedS3DestinationConfiguration.compressionFormat},
|
||||
* {@code s3DestinationConfiguration.compressionFormat} or
|
||||
* {@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.
|
||||
*/
|
||||
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 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 S3DestinationValidator() {}
|
||||
|
||||
static void validateWireShape(S3Destination config, String shapeName) {
|
||||
if (config == null) {
|
||||
return;
|
||||
}
|
||||
String compressionFormat = config.getCompressionFormat();
|
||||
if (compressionFormat != null && FirehoseCompression.fromWireValue(compressionFormat).isEmpty()) {
|
||||
throw constraintViolation(shapeName, "compressionFormat",
|
||||
"Member must satisfy enum value set: " + ENUM_VALUE_SET);
|
||||
}
|
||||
String fileExtension = config.getFileExtension();
|
||||
if (fileExtension == null) {
|
||||
return;
|
||||
}
|
||||
if (fileExtension.length() > FILE_EXTENSION_MAX_LENGTH) {
|
||||
throw constraintViolation(shapeName, "fileExtension",
|
||||
"Member must have length less than or equal to " + FILE_EXTENSION_MAX_LENGTH);
|
||||
}
|
||||
if (!FILE_EXTENSION.matcher(fileExtension).matches()) {
|
||||
throw constraintViolation(shapeName, "fileExtension",
|
||||
"Member must satisfy regular expression pattern: " + FILE_EXTENSION_REGEX);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+24
-7
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -20,9 +22,10 @@ import java.util.regex.Pattern;
|
||||
* {@code !{timestamp:<DateTimeFormatter pattern>}} and
|
||||
* {@code !{firehose:random-string}} expressions, {@code yyyy/MM/dd/HH/} is
|
||||
* appended by literal concatenation when the prefix holds no expression at all
|
||||
* (including the null/empty prefix), and the suffix is
|
||||
* {@code <streamName>-<versionId>-<yyyy-MM-dd-HH-mm-ss>-<uuid>} with no file
|
||||
* extension.
|
||||
* (including the null/empty prefix), the suffix is
|
||||
* {@code <streamName>-<versionId>-<yyyy-MM-dd-HH-mm-ss>-<uuid>}, and the file
|
||||
* extension comes from the destination's {@code FileExtension} or, failing that,
|
||||
* from its {@code CompressionFormat} (see {@link FirehoseCompression}).
|
||||
*
|
||||
* Known deviations from AWS: timestamps are evaluated at delivery time instead
|
||||
* of the oldest buffered record's arrival time, and expressions AWS would
|
||||
@@ -43,10 +46,24 @@ final class S3ObjectKeyResolver {
|
||||
|
||||
private S3ObjectKeyResolver() {}
|
||||
|
||||
static String resolveKey(String prefix, String streamName, String versionId,
|
||||
Instant deliveryTime, ZoneId zone) {
|
||||
ZonedDateTime time = ZonedDateTime.ofInstant(deliveryTime, zone);
|
||||
return evaluatePrefix(prefix, time) + objectNameSuffix(streamName, versionId, time);
|
||||
static String resolveKey(S3Destination s3, String streamName, String versionId,
|
||||
Instant deliveryTime, FirehoseCompression compression) {
|
||||
ZonedDateTime time = ZonedDateTime.ofInstant(
|
||||
deliveryTime, resolveZone(s3 == null ? null : s3.getCustomTimeZone()));
|
||||
return evaluatePrefix(s3 == null ? null : s3.getPrefix(), time)
|
||||
+ objectNameSuffix(streamName, versionId, time)
|
||||
+ fileExtension(s3, compression);
|
||||
}
|
||||
|
||||
/**
|
||||
* An explicit {@code FileExtension} replaces the extension the compression
|
||||
* format would contribute instead of being appended to it, and the empty string
|
||||
* means "not specified" (both verified against real AWS). It changes only the
|
||||
* key, never how the body is compressed.
|
||||
*/
|
||||
private static String fileExtension(S3Destination s3, FirehoseCompression compression) {
|
||||
String fileExtension = s3 == null ? null : s3.getFileExtension();
|
||||
return fileExtension == null || fileExtension.isEmpty() ? compression.extension() : fileExtension;
|
||||
}
|
||||
|
||||
static String evaluatePrefix(String prefix, ZonedDateTime time) {
|
||||
|
||||
+4
@@ -184,6 +184,8 @@ public class DeliveryStreamDescription {
|
||||
private String errorOutputPrefix;
|
||||
@JsonProperty("CompressionFormat")
|
||||
private String compressionFormat;
|
||||
@JsonProperty("FileExtension")
|
||||
private String fileExtension;
|
||||
@JsonProperty("CustomTimeZone")
|
||||
private String customTimeZone;
|
||||
@JsonProperty("BufferingHints")
|
||||
@@ -202,6 +204,8 @@ public class DeliveryStreamDescription {
|
||||
public void setErrorOutputPrefix(String errorOutputPrefix) { this.errorOutputPrefix = errorOutputPrefix; }
|
||||
public String getCompressionFormat() { return compressionFormat; }
|
||||
public void setCompressionFormat(String compressionFormat) { this.compressionFormat = compressionFormat; }
|
||||
public String getFileExtension() { return fileExtension; }
|
||||
public void setFileExtension(String fileExtension) { this.fileExtension = fileExtension; }
|
||||
public String getCustomTimeZone() { return customTimeZone; }
|
||||
public void setCustomTimeZone(String customTimeZone) { this.customTimeZone = customTimeZone; }
|
||||
public BufferingHints getBufferingHints() { return bufferingHints; }
|
||||
|
||||
Reference in new issue
Block a user