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:
Mihai BlidaruandMihai Blidaru authored and GitHub committed 2026-08-19 16:44:01 -04:00
1 parent 29b0d600c6
commit bba5ffb644
18 files changed
+1422 -53

No files matched your search

@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.services.firehose;
import org.xerial.snappy.Snappy;
import org.xerial.snappy.SnappyInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Reads back what Firehose delivered, so tests assert on the decoded payload
* rather than on opaque compressed bytes. Each format is decoded by the reader a
* real consumer would use, which is what makes the assertions meaningful:
* {@code Snappy} only decodes with snappy-java's own stream reader, and
* {@code HADOOP_SNAPPY} has no reader at all in the library, so its block
* framing is unpacked here the way Hadoop's {@code SnappyCodec} does.
*/
final class FirehoseCompressionDecoder {
private FirehoseCompressionDecoder() {}
static byte[] decompress(FirehoseCompression format, byte[] body) throws IOException {
return switch (format) {
case UNCOMPRESSED -> body;
case GZIP -> readAll(new GZIPInputStream(new ByteArrayInputStream(body)));
case ZIP -> singleZipEntry(body).content();
case SNAPPY -> readAll(new SnappyInputStream(new ByteArrayInputStream(body)));
case HADOOP_SNAPPY -> hadoopSnappy(body);
};
}
record ZipEntryContent(String name, byte[] content) {}
/** Fails when the archive does not hold exactly one entry, which is what AWS writes. */
static ZipEntryContent singleZipEntry(byte[] body) throws IOException {
List<ZipEntryContent> entries = new java.util.ArrayList<>();
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(body))) {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
entries.add(new ZipEntryContent(entry.getName(), zip.readAllBytes()));
}
}
if (entries.size() != 1) {
throw new IOException("expected exactly one zip entry, found " + entries.size());
}
return entries.get(0);
}
/**
* Hadoop's block framing, which snappy-java writes but cannot read back: per
* block, a big-endian uncompressed block length followed by one or more chunks
* of a big-endian compressed length and a raw Snappy block. The leading length
* belongs to the first block, not to the whole payload, so anything above the
* 32 KiB block size carries several blocks and must be looped over.
*/
static byte[] hadoopSnappy(byte[] body) throws IOException {
ByteBuffer in = ByteBuffer.wrap(body);
ByteArrayOutputStream out = new ByteArrayOutputStream(body.length);
while (in.remaining() > 0) {
int blockLength = in.getInt();
int produced = 0;
while (produced < blockLength) {
byte[] chunk = new byte[in.getInt()];
in.get(chunk);
byte[] plain = Snappy.uncompress(chunk);
out.writeBytes(plain);
produced += plain.length;
}
if (produced != blockLength) {
throw new IOException("block declared " + blockLength + " bytes, decoded " + produced);
}
}
return out.toByteArray();
}
private static byte[] readAll(InputStream in) throws IOException {
try (in) {
return in.readAllBytes();
}
}
}
@@ -0,0 +1,293 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.DecoderConfig;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end coverage of the CompressionFormat and FileExtension delivery
* contract over the wire, asserted on the bytes and headers a consumer reading
* the delivered object actually sees. Expectations come from real AWS, see
* https://github.com/floci-io/floci/issues/2328.
*/
@QuarkusTest
class FirehoseCompressionIntegrationTest {
@Inject
FirehoseService firehoseService;
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "Firehose_20150804.";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/firehose-delivery-role";
private static final String RECORD = "{\"id\": 1}";
private static final String EXPECTED_PAYLOAD = (RECORD + "\n").repeat(5);
private static final String ENUM_SET = "[ZIP, HADOOP_SNAPPY, Snappy, GZIP, UNCOMPRESSED]";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@EnumSource(FirehoseCompression.class)
void deliveredObjectCarriesTheFormatsFramingExtensionAndHeaders(FirehoseCompression format)
throws IOException {
String slug = format.name().toLowerCase(Locale.ROOT);
String stream = "compression-" + slug + "-stream";
String bucket = "firehose-compression-" + slug;
createDeliveryStream(stream, bucket, "\"CompressionFormat\": \"" + format.wireValue() + "\"");
putFiveRecordsAndFlush(stream);
String key = firstDeliveredKey(bucket);
assertTrue(key.endsWith(format.extension()), key);
Response object = getObject(bucket, key);
assertEquals("application/octet-stream", object.getHeader("Content-Type"));
assertEquals(format.contentEncoding(), object.getHeader("Content-Encoding"));
assertEquals(EXPECTED_PAYLOAD, new String(
FirehoseCompressionDecoder.decompress(format, object.getBody().asByteArray()),
StandardCharsets.UTF_8));
}
@Test
void fileExtensionReplacesTheCompressionExtensionWithoutChangingTheBody() throws IOException {
String stream = "compression-fileext-stream";
String bucket = "firehose-compression-fileext";
createDeliveryStream(stream, bucket,
"\"CompressionFormat\": \"GZIP\", \"FileExtension\": \".custom.log\"");
putFiveRecordsAndFlush(stream);
String key = firstDeliveredKey(bucket);
assertTrue(key.endsWith(".custom.log"), key);
assertFalse(key.contains(".gz"), key);
Response object = getObject(bucket, key);
assertEquals("gzip", object.getHeader("Content-Encoding"));
assertEquals(EXPECTED_PAYLOAD, new String(
FirehoseCompressionDecoder.decompress(FirehoseCompression.GZIP, object.getBody().asByteArray()),
StandardCharsets.UTF_8));
}
@Test
void fileExtensionIsEchoedAndMergedByUpdateDestination() {
String stream = "compression-fileext-echo-stream";
createDeliveryStream(stream, "firehose-compression-fileext-echo",
"\"CompressionFormat\": \"GZIP\", \"FileExtension\": \".custom.log\"");
describe(stream)
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.FileExtension",
equalTo(".custom.log"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "UpdateDestination")
.body("""
{
"DeliveryStreamName": "%s",
"CurrentDeliveryStreamVersionId": "1",
"DestinationId": "destinationId-000000000001",
"ExtendedS3DestinationUpdate": { "FileExtension": ".other.log" }
}
""".formatted(stream))
.when()
.post("/")
.then()
.statusCode(200);
describe(stream)
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.FileExtension",
equalTo(".other.log"))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CompressionFormat",
equalTo("GZIP"));
}
/** A stream without FileExtension must not grow the member in its description. */
@Test
void fileExtensionIsAbsentFromTheDescriptionWhenNotSpecified() {
String stream = "compression-no-fileext-stream";
createDeliveryStream(stream, "firehose-compression-no-fileext", "\"CompressionFormat\": \"GZIP\"");
describe(stream)
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.FileExtension",
equalTo(null));
}
@Test
void createRejectsCompressionFormatOutsideTheEnum() {
createDeliveryStreamExpecting("compression-bad-enum-stream", "firehose-compression-bad-enum",
"\"CompressionFormat\": \"BROTLI\"")
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'extendedS3DestinationConfiguration.compressionFormat' failed to satisfy constraint: "
+ "Member must satisfy enum value set: " + ENUM_SET));
}
/** Wrong case is a different value: AWS's enum has Snappy, not SNAPPY. */
@Test
void createRejectsMiscasedCompressionFormat() {
createDeliveryStreamExpecting("compression-miscased-stream", "firehose-compression-miscased",
"\"CompressionFormat\": \"SNAPPY\"")
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createRejectsFileExtensionBreakingTheApiPattern() {
createDeliveryStreamExpecting("compression-bad-ext-stream", "firehose-compression-bad-ext",
"\"FileExtension\": \"nodot\"")
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'extendedS3DestinationConfiguration.fileExtension' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: ^(|\\.[0-9a-z!\\-_.*'()]+)$"));
}
/** AWS names the member the value arrived in, so the legacy shape reports its own path. */
@Test
void legacyDestinationShapeReportsItsOwnPathInValidationErrors() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
.body("""
{
"DeliveryStreamName": "compression-legacy-shape-stream",
"S3DestinationConfiguration": {
"RoleARN": "%s",
"BucketARN": "arn:aws:s3:::firehose-compression-legacy",
"CompressionFormat": "BROTLI"
}
}
""".formatted(ROLE_ARN))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'s3DestinationConfiguration.compressionFormat' failed to satisfy constraint: "
+ "Member must satisfy enum value set: " + ENUM_SET));
}
@Test
void updateDestinationReportsTheUpdateShapeInValidationErrors() {
String stream = "compression-update-shape-stream";
createDeliveryStream(stream, "firehose-compression-update-shape", "\"CompressionFormat\": \"GZIP\"");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "UpdateDestination")
.body("""
{
"DeliveryStreamName": "%s",
"CurrentDeliveryStreamVersionId": "1",
"DestinationId": "destinationId-000000000001",
"ExtendedS3DestinationUpdate": { "CompressionFormat": "BROTLI" }
}
""".formatted(stream))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'extendedS3DestinationUpdate.compressionFormat' failed to satisfy constraint: "
+ "Member must satisfy enum value set: " + ENUM_SET));
}
private void createDeliveryStream(String streamName, String bucket, String extraDestinationJson) {
createDeliveryStreamExpecting(streamName, bucket, extraDestinationJson).statusCode(200);
}
private ValidatableResponse createDeliveryStreamExpecting(
String streamName, String bucket, String extraDestinationJson) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
.body("""
{
"DeliveryStreamName": "%s",
"ExtendedS3DestinationConfiguration": {
"RoleARN": "%s",
"BucketARN": "arn:aws:s3:::%s",
%s
}
}
""".formatted(streamName, ROLE_ARN, bucket, extraDestinationJson))
.when()
.post("/")
.then();
}
private ValidatableResponse describe(String streamName) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "DescribeDeliveryStream")
.body("{ \"DeliveryStreamName\": \"" + streamName + "\" }")
.when()
.post("/")
.then()
.statusCode(200);
}
private void putFiveRecordsAndFlush(String streamName) {
String data = Base64.getEncoder().encodeToString(RECORD.getBytes(StandardCharsets.UTF_8));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "PutRecordBatch")
.body("""
{
"DeliveryStreamName": "%s",
"Records": [
{"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}
]
}
""".formatted(streamName, data, data, data, data, data))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedPutCount", equalTo(0));
firehoseService.flush(streamName);
}
private String firstDeliveredKey(String bucket) {
return given().when().get("/" + bucket)
.then().statusCode(200)
.extract().xmlPath().getString("ListBucketResult.Contents[0].Key");
}
/**
* Content decoders are switched off so the compressed bytes arrive as stored:
* a client that honours Content-Encoding would gunzip the GZIP object in
* flight and the framing under test would never be seen.
*/
private Response getObject(String bucket, String key) {
return given()
.config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders()))
.when()
.get("/" + bucket + "/" + key)
.then()
.statusCode(200)
.extract().response();
}
}
@@ -0,0 +1,151 @@
package io.github.hectorvent.floci.services.firehose;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Locks the container format of each CompressionFormat, since a consumer that
* reads the delivered objects only works if the framing is the one AWS writes.
* The expectations come from objects delivered by real AWS, see
* https://github.com/floci-io/floci/issues/2328.
*/
class FirehoseCompressionTest {
private static final byte[] PAYLOAD =
"{\"seq\":1}\n{\"seq\":2}\n{\"seq\":3}\n".getBytes(StandardCharsets.UTF_8);
private static String hexPrefix(byte[] body, int length) {
return HexFormat.of().formatHex(body, 0, length);
}
@ParameterizedTest
@EnumSource(FirehoseCompression.class)
void everyFormatRoundTripsToTheOriginalPayload(FirehoseCompression format) throws IOException {
byte[] compressed = format.compress(PAYLOAD);
assertSamePayload(PAYLOAD, FirehoseCompressionDecoder.decompress(format, compressed));
}
@Test
void uncompressedReturnsThePayloadUntouchedWithNoExtensionOrEncoding() throws IOException {
assertEquals("", FirehoseCompression.UNCOMPRESSED.extension());
assertNull(FirehoseCompression.UNCOMPRESSED.contentEncoding());
assertSamePayload(PAYLOAD, FirehoseCompression.UNCOMPRESSED.compress(PAYLOAD));
}
@Test
void gzipWritesAGzipStream() throws IOException {
assertEquals(".gz", FirehoseCompression.GZIP.extension());
assertEquals("gzip", FirehoseCompression.GZIP.contentEncoding());
assertEquals("1f8b", hexPrefix(FirehoseCompression.GZIP.compress(PAYLOAD), 2));
}
/** AWS writes exactly one entry, named with a UUID unrelated to the object key. */
@Test
void zipWritesASingleEntryNamedWithAUuid() throws IOException {
assertEquals(".zip", FirehoseCompression.ZIP.extension());
assertEquals("zip", FirehoseCompression.ZIP.contentEncoding());
byte[] compressed = FirehoseCompression.ZIP.compress(PAYLOAD);
assertEquals("504b", hexPrefix(compressed, 2));
FirehoseCompressionDecoder.ZipEntryContent entry =
FirehoseCompressionDecoder.singleZipEntry(compressed);
assertEquals(entry.name(), UUID.fromString(entry.name()).toString());
}
/**
* The xerial stream format, not the official Snappy framing format: the two
* are mutually unreadable, and AWS delivers this one.
*/
@Test
void snappyWritesTheXerialStreamFormat() throws IOException {
assertEquals(".snappy", FirehoseCompression.SNAPPY.extension());
assertEquals("snappy-java", FirehoseCompression.SNAPPY.contentEncoding());
byte[] compressed = FirehoseCompression.SNAPPY.compress(PAYLOAD);
assertEquals("82" + HexFormat.of().formatHex("SNAPPY".getBytes(StandardCharsets.US_ASCII)) + "00",
hexPrefix(compressed, 8));
}
/**
* Same extension as Snappy, different framing and Content-Encoding. The
* extension is .snappy and not the .hsnappy the S3 object name documentation
* tables, because that is what the service delivers.
*/
@Test
void hadoopSnappyWritesHadoopBlockFramingHeadedByTheUncompressedLength() throws IOException {
assertEquals(".snappy", FirehoseCompression.HADOOP_SNAPPY.extension());
assertEquals("hadoop-snappy", FirehoseCompression.HADOOP_SNAPPY.contentEncoding());
byte[] compressed = FirehoseCompression.HADOOP_SNAPPY.compress(PAYLOAD);
// The leading length is the first block's; this payload fits in one block.
assertEquals(PAYLOAD.length, ByteBuffer.wrap(compressed).getInt());
// Unlike the xerial stream format, the block framing carries no magic header.
assertNotEquals("82", hexPrefix(compressed, 1));
}
/**
* Firehose buffers up to megabytes, so the formats have to survive payloads
* larger than snappy-java's 32 KiB block: past that, the Hadoop framing repeats
* and its leading length stops describing the whole payload.
*/
@ParameterizedTest
@EnumSource(FirehoseCompression.class)
void everyFormatRoundTripsPayloadsLargerThanOneSnappyBlock(FirehoseCompression format) throws IOException {
byte[] large = new byte[200_000];
for (int i = 0; i < large.length; i++) {
large[i] = (byte) ('a' + (i % 26));
}
byte[] compressed = format.compress(large);
if (format == FirehoseCompression.HADOOP_SNAPPY) {
assertNotEquals(large.length, ByteBuffer.wrap(compressed).getInt(),
"the leading length describes the first block, not the payload");
}
assertArrayEquals(large, FirehoseCompressionDecoder.decompress(format, compressed));
}
@Test
void wireValuesAreMatchedCaseExactlyTheWayAwsMatchesTheEnum() {
assertEquals(FirehoseCompression.SNAPPY, FirehoseCompression.fromWireValue("Snappy").orElseThrow());
assertEquals(FirehoseCompression.HADOOP_SNAPPY,
FirehoseCompression.fromWireValue("HADOOP_SNAPPY").orElseThrow());
assertTrue(FirehoseCompression.fromWireValue("SNAPPY").isEmpty());
assertTrue(FirehoseCompression.fromWireValue("gzip").isEmpty());
assertTrue(FirehoseCompression.fromWireValue("BROTLI").isEmpty());
assertTrue(FirehoseCompression.fromWireValue("").isEmpty());
assertTrue(FirehoseCompression.fromWireValue(null).isEmpty());
}
/**
* A stream stored before the value was validated must still deliver its
* records, uncompressed, rather than losing them to a lookup failure.
*/
@Test
void deliveryFallsBackToUncompressedForAbsentOrUnknownFormats() {
assertEquals(FirehoseCompression.UNCOMPRESSED, FirehoseCompression.forDelivery(null));
assertEquals(FirehoseCompression.UNCOMPRESSED, FirehoseCompression.forDelivery("nonsense"));
assertEquals(FirehoseCompression.GZIP, FirehoseCompression.forDelivery("GZIP"));
}
/** Compares as text so a mismatch is readable, then as bytes so it is exact. */
private static void assertSamePayload(byte[] expected, byte[] actual) {
assertEquals(new String(expected, StandardCharsets.UTF_8), new String(actual, StandardCharsets.UTF_8));
assertArrayEquals(expected, actual);
}
}
@@ -8,21 +8,28 @@ 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.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -31,6 +38,9 @@ import static org.mockito.Mockito.when;
class FirehoseServiceTest {
private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
/** AWS delivers every format as application/octet-stream, compressed or not. */
private static final String OCTET_STREAM = "application/octet-stream";
private static final String FIVE_RECORDS = "{\"n\":0}\n{\"n\":1}\n{\"n\":2}\n{\"n\":3}\n{\"n\":4}\n";
private FirehoseService firehoseService;
private StorageFactory storageFactory;
@@ -61,6 +71,13 @@ class FirehoseServiceTest {
new RegionResolver("us-east-1", "000000000000"), clock, config);
}
private static S3Destination destination(String bucketArn, String compressionFormat) {
S3Destination s3 = new S3Destination();
s3.setBucketArn(bucketArn);
s3.setCompressionFormat(compressionFormat);
return s3;
}
private void putRecords(String streamName, int count) {
for (int i = 0; i < count; i++) {
firehoseService.putRecord(streamName, new Record(("{\"n\":" + i + "}").getBytes(StandardCharsets.UTF_8)));
@@ -73,12 +90,36 @@ class FirehoseServiceTest {
firehoseService.flush(streamName);
}
private String deliveredKey(String expectedBucket) {
private record Delivered(String key, byte[] body, String contentType, String contentEncoding) {
String text() {
return new String(body, StandardCharsets.UTF_8);
}
String decoded(FirehoseCompression format) throws IOException {
return new String(FirehoseCompressionDecoder.decompress(format, body), StandardCharsets.UTF_8);
}
}
private Delivered delivered(String expectedBucket) {
ArgumentCaptor<String> bucket = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
verify(s3Service).putObject(bucket.capture(), key.capture(), any(byte[].class), anyString(), anyMap());
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
ArgumentCaptor<String> contentType = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
verify(s3Service).putObject(bucket.capture(), key.capture(), body.capture(), contentType.capture(),
anyMap(), options.capture());
assertEquals(expectedBucket, bucket.getValue());
return key.getValue();
return new Delivered(key.getValue(), body.getValue(), contentType.getValue(),
options.getValue().getContentEncoding());
}
private String deliveredKey(String expectedBucket) {
return delivered(expectedBucket).key();
}
private void verifyNothingDelivered() {
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(),
anyMap(), any(PutObjectOptions.class));
}
@Test
@@ -147,7 +188,7 @@ class FirehoseServiceTest {
firehoseService.flushDueBuffers(clock.instant().plusSeconds(299));
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
}
@Test
@@ -157,9 +198,7 @@ class FirehoseServiceTest {
firehoseService.flushDueBuffers(clock.instant().plusSeconds(300));
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
assertEquals("{\"n\":0}\n{\"n\":1}\n", new String(body.getValue(), StandardCharsets.UTF_8));
assertEquals("{\"n\":0}\n{\"n\":1}\n", delivered("floci-firehose-results").text());
}
@Test
@@ -174,12 +213,10 @@ class FirehoseServiceTest {
putRecords("hinted-stream", 1);
firehoseService.flushDueBuffers(clock.instant().plusSeconds(59));
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
firehoseService.flushDueBuffers(clock.instant().plusSeconds(60));
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("custom-bucket"), anyString(), body.capture(), anyString(), anyMap());
assertEquals("{\"n\":0}\n", new String(body.getValue(), StandardCharsets.UTF_8));
assertEquals("{\"n\":0}\n", delivered("custom-bucket").text());
}
/** Matches real AWS: the volume trigger is bytes vs SizeInMBs, never a record count. */
@@ -188,7 +225,7 @@ class FirehoseServiceTest {
firehoseService.createDeliveryStream("trickle-stream", null);
putRecords("trickle-stream", 20);
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
}
@Test
@@ -202,13 +239,11 @@ class FirehoseServiceTest {
firehoseService.createDeliveryStream("bulky-stream", s3);
firehoseService.putRecord("bulky-stream", new Record(new byte[512 * 1024]));
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
firehoseService.putRecord("bulky-stream", new Record(new byte[512 * 1024]));
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("custom-bucket"), anyString(), body.capture(), anyString(), anyMap());
// Both 512 KiB records, each followed by the newline the flush appends.
assertEquals(2 * 512 * 1024 + 2, body.getValue().length);
assertEquals(2 * 512 * 1024 + 2, delivered("custom-bucket").body().length);
}
/** Emulator-only opt-in: flush-record-count=1 restores LocalStack-style record-at-a-time delivery. */
@@ -218,9 +253,7 @@ class FirehoseServiceTest {
firehoseService.createDeliveryStream("eager-stream", null);
firehoseService.putRecord("eager-stream", new Record("{\"n\":0}".getBytes(StandardCharsets.UTF_8)));
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
assertEquals("{\"n\":0}\n", new String(body.getValue(), StandardCharsets.UTF_8));
assertEquals("{\"n\":0}\n", delivered("floci-firehose-results").text());
}
@Test
@@ -228,13 +261,11 @@ class FirehoseServiceTest {
firehoseService = newService(3);
firehoseService.createDeliveryStream("counted-stream", null);
putRecords("counted-stream", 2);
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
firehoseService.putRecord("counted-stream", new Record("{\"n\":2}".getBytes(StandardCharsets.UTF_8)));
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
assertEquals("{\"n\":0}\n{\"n\":1}\n{\"n\":2}\n", new String(body.getValue(), StandardCharsets.UTF_8));
assertEquals("{\"n\":0}\n{\"n\":1}\n{\"n\":2}\n", delivered("floci-firehose-results").text());
}
/** Matches real AWS: DeleteDeliveryStream discards undelivered records instead of flushing them. */
@@ -246,7 +277,7 @@ class FirehoseServiceTest {
firehoseService.deleteDeliveryStream("doomed-stream");
firehoseService.flushDueBuffers(clock.instant().plusSeconds(301));
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verifyNothingDelivered();
}
@Test
@@ -258,6 +289,134 @@ class FirehoseServiceTest {
firehoseService.flushDueBuffers(afterInterval);
firehoseService.flushDueBuffers(afterInterval.plusSeconds(301));
verify(s3Service).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
verify(s3Service).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap(),
any(PutObjectOptions.class));
}
@Test
void uncompressedDeliveryCarriesRawBytesWithNoExtensionOrContentEncoding() {
firehoseService.createDeliveryStream("plain-stream", destination("arn:aws:s3:::custom-bucket",
"UNCOMPRESSED"));
putRecordsAndFlush("plain-stream");
Delivered delivered = delivered("custom-bucket");
// Ending in the UUID means nothing was appended to the object name.
assertTrue(delivered.key().matches(".*-" + UUID_REGEX), delivered.key());
assertEquals(OCTET_STREAM, delivered.contentType());
assertNull(delivered.contentEncoding());
assertEquals(FIVE_RECORDS, delivered.text());
}
@ParameterizedTest
@EnumSource(value = FirehoseCompression.class, names = "UNCOMPRESSED", mode = EnumSource.Mode.EXCLUDE)
void compressedFormatsDeliverTheirOwnFramingExtensionAndContentEncoding(FirehoseCompression format)
throws IOException {
firehoseService.createDeliveryStream("compressed-stream",
destination("arn:aws:s3:::custom-bucket", format.wireValue()));
putRecordsAndFlush("compressed-stream");
Delivered delivered = delivered("custom-bucket");
assertTrue(delivered.key().endsWith(format.extension()), delivered.key());
assertEquals(OCTET_STREAM, delivered.contentType());
assertEquals(format.contentEncoding(), delivered.contentEncoding());
assertFalse(Arrays.equals(FIVE_RECORDS.getBytes(StandardCharsets.UTF_8), delivered.body()),
"body should not be the plain payload");
assertEquals(FIVE_RECORDS, delivered.decoded(format));
}
/**
* Verified against real AWS: FileExtension replaces the extension the
* compression format contributes rather than being appended to it, and leaves
* the body and its Content-Encoding alone.
*/
@Test
void fileExtensionReplacesTheCompressionExtension() throws IOException {
S3Destination s3 = destination("arn:aws:s3:::custom-bucket", "GZIP");
s3.setFileExtension(".custom.log");
firehoseService.createDeliveryStream("ext-stream", s3);
putRecordsAndFlush("ext-stream");
Delivered delivered = delivered("custom-bucket");
assertTrue(delivered.key().endsWith(".custom.log"), delivered.key());
assertFalse(delivered.key().contains(".gz"), delivered.key());
assertEquals("gzip", delivered.contentEncoding());
assertEquals(FIVE_RECORDS, delivered.decoded(FirehoseCompression.GZIP));
}
@Test
void fileExtensionIsAddedWhenTheStreamIsUncompressed() {
S3Destination s3 = destination("arn:aws:s3:::custom-bucket", "UNCOMPRESSED");
s3.setFileExtension(".custom.log");
firehoseService.createDeliveryStream("ext-stream", s3);
putRecordsAndFlush("ext-stream");
Delivered delivered = delivered("custom-bucket");
assertTrue(delivered.key().endsWith(".custom.log"), delivered.key());
assertNull(delivered.contentEncoding());
assertEquals(FIVE_RECORDS, delivered.text());
}
/** The empty string is a valid FileExtension AWS treats as "not specified". */
@Test
void emptyFileExtensionFallsBackToTheCompressionExtension() {
S3Destination s3 = destination("arn:aws:s3:::custom-bucket", "GZIP");
s3.setFileExtension("");
firehoseService.createDeliveryStream("ext-stream", s3);
putRecordsAndFlush("ext-stream");
assertTrue(deliveredKey("custom-bucket").endsWith(".gz"), "expected the GZIP extension back");
}
/**
* Verified against real AWS: a stream updated while records are still buffered
* delivers them with the format in effect at delivery rather than at ingest,
* and the key carries the version resulting from the update. AWS does not flush
* the pending buffer early either, it keeps to the original interval.
*/
@Test
void compressionChangedWhileRecordsAreBufferedAppliesAtDeliveryTime() {
firehoseService.createDeliveryStream("mid-stream", destination("arn:aws:s3:::custom-bucket", "GZIP"));
putRecords("mid-stream", 5);
S3Destination update = new S3Destination();
update.setCompressionFormat("UNCOMPRESSED");
firehoseService.updateDestination("mid-stream", "1", "destinationId-000000000001", update);
verifyNothingDelivered();
firehoseService.flush("mid-stream");
Delivered delivered = delivered("custom-bucket");
assertNull(delivered.contentEncoding());
assertEquals(FIVE_RECORDS, delivered.text());
assertTrue(delivered.key().contains("mid-stream-2-"), delivered.key());
}
@Test
void updateDestinationMergesFileExtension() {
firehoseService.createDeliveryStream("ext-stream", destination("arn:aws:s3:::custom-bucket", "GZIP"));
S3Destination update = new S3Destination();
update.setFileExtension(".custom.log");
firehoseService.updateDestination("ext-stream", "1", "destinationId-000000000001", update);
S3Destination described = firehoseService.describeDeliveryStream("ext-stream").s3Destination();
assertEquals(".custom.log", described.getFileExtension());
assertEquals("GZIP", described.getCompressionFormat());
}
/**
* Record payloads are arbitrary bytes, so a delivery must not round-trip them
* through a String: that replaces every byte sequence that is not valid UTF-8.
*/
@Test
void recordsThatAreNotValidUtf8AreDeliveredByteForByte() {
byte[] binary = {(byte) 0xff, (byte) 0xfe, 0x00, (byte) 0x80};
firehoseService.createDeliveryStream("binary-stream", null);
firehoseService.putRecord("binary-stream", new Record(binary));
firehoseService.flush("binary-stream");
assertArrayEquals(new byte[]{(byte) 0xff, (byte) 0xfe, 0x00, (byte) 0x80, '\n'},
delivered("floci-firehose-results").body());
}
}
@@ -0,0 +1,111 @@
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 org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The error codes and messages asserted here were captured from real AWS's raw
* HTTP responses, see https://github.com/floci-io/floci/issues/2328.
*/
class S3DestinationValidatorTest {
private static final String ENUM_SET = "[ZIP, HADOOP_SNAPPY, Snappy, GZIP, UNCOMPRESSED]";
private static S3Destination withCompressionFormat(String compressionFormat) {
S3Destination config = new S3Destination();
config.setCompressionFormat(compressionFormat);
return config;
}
private static S3Destination withFileExtension(String fileExtension) {
S3Destination config = new S3Destination();
config.setFileExtension(fileExtension);
return config;
}
@ParameterizedTest
@ValueSource(strings = {"UNCOMPRESSED", "GZIP", "ZIP", "Snappy", "HADOOP_SNAPPY"})
void wireShapeAcceptsEveryFormatFlociDelivers(String compressionFormat) {
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withCompressionFormat(compressionFormat), "extendedS3DestinationConfiguration"));
}
/** Wrong case is a different value to AWS, so it fails the enum like any typo. */
@ParameterizedTest
@ValueSource(strings = {"BROTLI", "SNAPPY", "gzip", "", "snappy"})
void wireShapeRejectsValuesOutsideTheEnumWithTheAwsMessage(String compressionFormat) {
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withCompressionFormat(compressionFormat), "extendedS3DestinationConfiguration"));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("1 validation error detected: Value at "
+ "'extendedS3DestinationConfiguration.compressionFormat' failed to satisfy constraint: "
+ "Member must satisfy enum value set: " + ENUM_SET, error.getMessage());
}
/** AWS names the member that carried the value, which differs per request shape. */
@Test
void wireShapeReportsTheShapeTheValueArrivedIn() {
for (String shape : new String[]{"s3DestinationConfiguration", "extendedS3DestinationUpdate",
"s3DestinationUpdate"}) {
AwsException error = assertThrows(AwsException.class,
() -> S3DestinationValidator.validateWireShape(withCompressionFormat("BROTLI"), shape));
assertEquals("1 validation error detected: Value at '" + shape + ".compressionFormat' "
+ "failed to satisfy constraint: Member must satisfy enum value set: " + ENUM_SET,
error.getMessage());
}
}
/**
* The dot is itself an allowed character after the leading one, so ".." passes
* (confirmed against real AWS) however odd it looks as an extension.
*/
@ParameterizedTest
@ValueSource(strings = {".gz", ".custom.log", ".log", "", ".a-b_c!*'()", ".123", ".."})
void wireShapeAcceptsFileExtensionsMatchingTheApiPattern(String fileExtension) {
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withFileExtension(fileExtension), "extendedS3DestinationConfiguration"));
}
@ParameterizedTest
@ValueSource(strings = {"nodot", ".Custom.LOG", ".", ".with space", ".tab\t", "gz."})
void wireShapeRejectsFileExtensionsBreakingTheApiPattern(String fileExtension) {
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withFileExtension(fileExtension), "extendedS3DestinationConfiguration"));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at "
+ "'extendedS3DestinationConfiguration.fileExtension' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: ^(|\\.[0-9a-z!\\-_.*'()]+)$",
error.getMessage());
}
@Test
void wireShapeRejectsFileExtensionsLongerThan128Characters() {
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withFileExtension("." + "a".repeat(127)), "extendedS3DestinationConfiguration"));
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withFileExtension("." + "a".repeat(128)), "extendedS3DestinationConfiguration"));
assertEquals("1 validation error detected: Value at "
+ "'extendedS3DestinationConfiguration.fileExtension' failed to satisfy constraint: "
+ "Member must have length less than or equal to 128", error.getMessage());
}
@Test
void wireShapeIgnoresDestinationsThatSpecifyNeitherMember() {
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(null, "s3DestinationConfiguration"));
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
new S3Destination(), "s3DestinationConfiguration"));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import org.junit.jupiter.api.Test;
import java.time.Instant;
@@ -8,6 +9,7 @@ import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -100,19 +102,59 @@ class S3ObjectKeyResolverTest {
assertTrue(suffix.matches("my-stream-1-2026-07-13-10-42-07-" + UUID_REGEX), suffix);
}
private static S3Destination destination(String prefix, String customTimeZone, String fileExtension) {
S3Destination s3 = new S3Destination();
s3.setPrefix(prefix);
s3.setCustomTimeZone(customTimeZone);
s3.setFileExtension(fileExtension);
return s3;
}
@Test
void resolveKeyConcatenatesEvaluatedPrefixAndSuffix() {
String key = S3ObjectKeyResolver.resolveKey("legacy", "my-stream", "3", INSTANT, ZoneOffset.UTC);
String key = S3ObjectKeyResolver.resolveKey(destination("legacy", null, null), "my-stream", "3",
INSTANT, FirehoseCompression.UNCOMPRESSED);
assertTrue(key.matches("legacy2026/07/13/10/my-stream-3-2026-07-13-10-42-07-" + UUID_REGEX), key);
}
@Test
void customTimeZoneShiftsPrefixAndSuffixAcrossTheDayBoundary() {
String key = S3ObjectKeyResolver.resolveKey(null, "s", "1",
Instant.parse("2026-01-01T23:30:00Z"), ZoneId.of("Europe/Madrid"));
String key = S3ObjectKeyResolver.resolveKey(destination(null, "Europe/Madrid", null), "s", "1",
Instant.parse("2026-01-01T23:30:00Z"), FirehoseCompression.UNCOMPRESSED);
assertTrue(key.matches("2026/01/02/00/s-1-2026-01-02-00-30-00-" + UUID_REGEX), key);
}
@Test
void keyEndsWithTheCompressionExtension() {
String key = S3ObjectKeyResolver.resolveKey(destination(null, null, null), "s", "1",
INSTANT, FirehoseCompression.GZIP);
assertTrue(key.endsWith(".gz"), key);
}
/** Verified against real AWS: FileExtension replaces the compression extension. */
@Test
void fileExtensionReplacesTheCompressionExtension() {
String key = S3ObjectKeyResolver.resolveKey(destination(null, null, ".custom.log"), "s", "1",
INSTANT, FirehoseCompression.GZIP);
assertTrue(key.endsWith(".custom.log"), key);
assertFalse(key.contains(".gz"), key);
}
@Test
void fileExtensionIsAppendedWhenTheStreamIsUncompressed() {
String key = S3ObjectKeyResolver.resolveKey(destination(null, null, ".custom.log"), "s", "1",
INSTANT, FirehoseCompression.UNCOMPRESSED);
assertTrue(key.endsWith(".custom.log"), key);
}
/** The empty string is a valid FileExtension AWS treats as "not specified". */
@Test
void emptyFileExtensionFallsBackToTheCompressionExtension() {
String key = S3ObjectKeyResolver.resolveKey(destination(null, null, ""), "s", "1",
INSTANT, FirehoseCompression.GZIP);
assertTrue(key.endsWith(".gz"), key);
}
@Test
void resolveZoneFallsBackToUtc() {
assertEquals(ZoneOffset.UTC, S3ObjectKeyResolver.resolveZone(null));