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

+1 -1
View File
@@ -271,7 +271,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| Athena | In-process with DuckDB sidecar | Real SQL execution over S3 and Glue-backed views |
| Glue | In-process | Data Catalog, Schema Registry, tables consumed by Athena |
| EMR | In-process | Cluster (job flow) lifecycle, instance groups and fleets, steps, security configurations, tagging |
| Data Firehose | In-process | Streaming delivery, NDJSON flush to S3 |
| Data Firehose | In-process | Streaming delivery, buffered flush to S3 with GZIP/ZIP/Snappy compression |
| Managed Service for Apache Flink | Real Docker | Kinesis Analytics V2 control plane; StartApplication runs a real Flink cluster (JobManager + TaskManager, image per RuntimeEnvironment), pulls the application JAR from local S3, and submits the job |
| ECS | Real Docker | Clusters, task definitions, tasks, services, capacity providers, task sets |
| EC2 | Real Docker | RunInstances launches containers, SSH key injection, UserData, IMDS, VPC resources |
@@ -444,6 +444,15 @@
<version>1.84</version>
<scope>test</scope>
</dependency>
<!-- Decodes the Snappy variants Firehose delivers to S3 (issue #2328).
Pinned because this module imports no BOM; keep it in step with the
version the Quarkus BOM manages for the emulator itself. -->
<dependency>
<groupId>org.xerial.snappy</groupId>
<artifactId>snappy-java</artifactId>
<version>1.1.10.8</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,258 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.xerial.snappy.Snappy;
import org.xerial.snappy.SnappyInputStream;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.services.firehose.FirehoseClient;
import software.amazon.awssdk.services.firehose.model.BufferingHints;
import software.amazon.awssdk.services.firehose.model.CompressionFormat;
import software.amazon.awssdk.services.firehose.model.CreateDeliveryStreamRequest;
import software.amazon.awssdk.services.firehose.model.DeleteDeliveryStreamRequest;
import software.amazon.awssdk.services.firehose.model.DeliveryStreamType;
import software.amazon.awssdk.services.firehose.model.ExtendedS3DestinationConfiguration;
import software.amazon.awssdk.services.firehose.model.PutRecordBatchRequest;
import software.amazon.awssdk.services.firehose.model.Record;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.core.SdkBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Issue #2328 — the delivered S3 object must actually be compressed the way the
* stream's CompressionFormat says, with the key extension and Content-Encoding
* real AWS uses. This is the only Firehose coverage that reads the delivered
* bytes back through an SDK client, and in CI it runs against the GraalVM native
* image, where the Snappy formats depend on a bundled JNI library.
*/
@DisplayName("Firehose S3 delivery compression — issue #2328")
class FirehoseCompressionDeliveryTest {
private static final String RECORD = "{\"seq\":1}\n";
private static final int RECORD_COUNT = 5;
private static final String EXPECTED_PAYLOAD = RECORD.repeat(RECORD_COUNT);
/**
* The buffering interval has to elapse for the delivery to happen, so it is
* kept short. AWS accepts anything in 0..900 (verified against the service, not
* just its model), so this is still a contract-faithful stream; against Floci
* the flush then lands on the next tick of its background flusher.
*/
private static final int BUFFERING_INTERVAL_SECONDS = 5;
private static final long POLL_TIMEOUT_MILLIS = 240_000L;
private static FirehoseClient firehose;
private static S3Client s3;
private static String bucket;
private static String streamPrefix;
/**
* HADOOP_SNAPPY shares the .snappy extension with Snappy and differs only in
* framing and Content-Encoding: the S3 object name documentation tables
* .hsnappy, but the service delivers .snappy (verified against real AWS).
*/
private record Format(CompressionFormat compressionFormat, String extension, String contentEncoding) {
String slug() {
return compressionFormat.toString().toLowerCase(Locale.ROOT).replace('_', '-');
}
@Override
public String toString() {
return compressionFormat.toString();
}
}
private static Stream<Format> formats() {
return Stream.of(
new Format(CompressionFormat.UNCOMPRESSED, "", null),
new Format(CompressionFormat.GZIP, ".gz", "gzip"),
new Format(CompressionFormat.ZIP, ".zip", "zip"),
new Format(CompressionFormat.SNAPPY, ".snappy", "snappy-java"),
new Format(CompressionFormat.HADOOP_SNAPPY, ".snappy", "hadoop-snappy"));
}
/**
* Every stream is created and filled up front so the single buffering interval
* is shared by all of them instead of being waited out once per format.
*/
@BeforeAll
static void setup() {
String roleArn = TestFixtures.isRealAws()
? System.getenv("FIREHOSE_ROLE_ARN")
: "arn:aws:iam::000000000000:role/firehose-role";
if (TestFixtures.isRealAws() && roleArn == null) {
Assumptions.abort("FIREHOSE_ROLE_ARN not set");
}
firehose = TestFixtures.firehoseClient();
s3 = TestFixtures.s3Client();
bucket = TestFixtures.uniqueName("firehose-compression");
streamPrefix = TestFixtures.uniqueName("sdk-compression");
s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
List<Format> formats = formats().toList();
for (Format format : formats) {
firehose.createDeliveryStream(CreateDeliveryStreamRequest.builder()
.deliveryStreamName(streamName(format))
.deliveryStreamType(DeliveryStreamType.DIRECT_PUT)
.extendedS3DestinationConfiguration(ExtendedS3DestinationConfiguration.builder()
.roleARN(roleArn)
.bucketARN("arn:aws:s3:::" + bucket)
.prefix(format.slug() + "/")
.compressionFormat(format.compressionFormat())
.bufferingHints(BufferingHints.builder()
.intervalInSeconds(BUFFERING_INTERVAL_SECONDS)
.sizeInMBs(1)
.build())
.build())
.build());
}
for (Format format : formats) {
Record entry = Record.builder()
.data(SdkBytes.fromString(RECORD, StandardCharsets.UTF_8))
.build();
assertThat(firehose.putRecordBatch(PutRecordBatchRequest.builder()
.deliveryStreamName(streamName(format))
.records(Collections.nCopies(RECORD_COUNT, entry))
.build()).failedPutCount()).isZero();
}
}
@AfterAll
static void cleanup() {
if (firehose != null) {
formats().forEach(format -> {
try {
firehose.deleteDeliveryStream(DeleteDeliveryStreamRequest.builder()
.deliveryStreamName(streamName(format)).build());
} catch (Exception ignored) {
// Best effort: a stream that never got created must not fail the run.
}
});
firehose.close();
}
if (s3 != null) {
try {
s3.listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build()).contents()
.forEach(object -> s3.deleteObject(DeleteObjectRequest.builder()
.bucket(bucket).key(object.key()).build()));
s3.deleteBucket(builder -> builder.bucket(bucket));
} catch (Exception ignored) {
// Best effort cleanup of the probe bucket.
}
s3.close();
}
}
private static String streamName(Format format) {
return streamPrefix + "-" + format.slug();
}
@ParameterizedTest(name = "{0}")
@MethodSource("formats")
@DisplayName("Delivered object carries the format's framing, extension and Content-Encoding")
void deliveredObjectMatchesTheCompressionFormat(Format format) throws Exception {
String key = waitForDeliveredKey(format.slug() + "/");
assertThat(key).endsWith(format.extension());
if (format.extension().isEmpty()) {
assertThat(key).doesNotEndWith(".gz").doesNotEndWith(".zip").doesNotEndWith(".snappy");
}
try (ResponseInputStream<GetObjectResponse> object = s3.getObject(
GetObjectRequest.builder().bucket(bucket).key(key).build())) {
GetObjectResponse response = object.response();
assertThat(response.contentType()).isEqualTo("application/octet-stream");
assertThat(response.contentEncoding()).isEqualTo(format.contentEncoding());
assertThat(decompress(format, object.readAllBytes()))
.as("delivered body must decode to the records that were put")
.isEqualTo(EXPECTED_PAYLOAD);
}
}
private String waitForDeliveredKey(String prefix) throws InterruptedException {
long deadline = System.currentTimeMillis() + POLL_TIMEOUT_MILLIS;
while (System.currentTimeMillis() < deadline) {
List<S3Object> contents = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucket).prefix(prefix).build()).contents();
if (!contents.isEmpty()) {
return contents.get(0).key();
}
Thread.sleep(5_000L);
}
throw new AssertionError("no object delivered under " + prefix + " within "
+ POLL_TIMEOUT_MILLIS / 1000 + "s");
}
private static String decompress(Format format, byte[] body) throws IOException {
byte[] plain = switch (format.compressionFormat()) {
case UNCOMPRESSED -> body;
case GZIP -> new GZIPInputStream(new ByteArrayInputStream(body)).readAllBytes();
case ZIP -> singleZipEntry(body);
case SNAPPY -> new SnappyInputStream(new ByteArrayInputStream(body)).readAllBytes();
case HADOOP_SNAPPY -> hadoopSnappy(body);
default -> throw new IllegalArgumentException("unhandled format " + format);
};
return new String(plain, StandardCharsets.UTF_8);
}
/** AWS writes exactly one entry, named with a UUID unrelated to the object key. */
private static byte[] singleZipEntry(byte[] body) throws IOException {
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(body))) {
ZipEntry entry = zip.getNextEntry();
assertThat(entry).as("zip must hold an entry").isNotNull();
byte[] content = zip.readAllBytes();
assertThat(zip.getNextEntry()).as("zip must hold exactly one entry").isNull();
return content;
}
}
/**
* 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.
*/
private 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.write(plain);
produced += plain.length;
}
assertThat(produced).isEqualTo(blockLength);
}
return out.toByteArray();
}
}
+25 -3
View File
@@ -32,18 +32,40 @@ Floci emulates Amazon Data Firehose for streaming data ingestion and delivery to
An emulator-only record-count trigger is also available for local dev: set `floci.services.firehose.flush-record-count` (env: `FLOCI_SERVICES_FIREHOSE_FLUSH_RECORD_COUNT`) to flush after that many buffered records — `1` gives LocalStack-style record-at-a-time delivery. Disabled by default (`0`) so delivery timing matches real AWS.
Buffers are also flushed on shutdown, so pending records are not lost. Deleting a delivery stream discards its pending records without flushing, matching real AWS.
3. **Format**: Records are flushed as raw NDJSON (newline-delimited JSON) to the bucket configured in the S3 destination (`floci-firehose-results` if the stream has no destination configuration).
3. **Format**: Buffered records are concatenated as bytes and delivered to the bucket configured in the S3 destination (`floci-firehose-results` if the stream has no destination configuration). The object is then compressed according to the destination's `CompressionFormat` and always stored with `Content-Type: application/octet-stream`, as AWS does.
Known deviations from AWS in the delivery path:
- **Record separator.** Floci appends a newline after any record that does not already end with one, so the delivered object is newline-delimited. Real AWS concatenates the record bytes verbatim and inserts no separator — three records of `abc` are delivered as the 9 bytes `abcabcabc`, not as 12 bytes with separators. Producers that rely on the delimiter therefore work against Floci and not against AWS, which is why AWS's own guidance is to put the delimiter inside the record.
- **Optional destination.** Floci accepts a delivery stream with no destination configuration at all, and one whose destination omits `BucketARN` or `RoleARN`; with no destination it delivers to `floci-firehose-results`. AWS requires exactly one complete destination: it answers `InvalidArgumentException` ("Exactly one destination configuration is supported for a Firehose") when none is given, and `ValidationException` ("Member must not be null") for a destination missing `bucketARN` or `roleARN`. The default bucket is a local-development convenience with no AWS equivalent.
## Compression
`CompressionFormat` is applied to the delivered object, adding the key extension and `Content-Encoding` AWS pairs with each format:
| `CompressionFormat` | Key extension | `Content-Encoding` | Container format |
|---|---|---|---|
| `UNCOMPRESSED` | *(none)* | *(none)* | the records as they were put |
| `GZIP` | `.gz` | `gzip` | gzip stream |
| `ZIP` | `.zip` | `zip` | zip archive holding a single deflated entry named with a UUID |
| `Snappy` | `.snappy` | `snappy-java` | the [xerial snappy-java stream format](https://github.com/xerial/snappy-java#compatibility-notes) (magic `0x82 "SNAPPY" 0x00`), **not** the [official Snappy framing format](https://github.com/google/snappy/blob/main/framing_format.txt) |
| `HADOOP_SNAPPY` | `.snappy` | `hadoop-snappy` | Hadoop's block framing, what Hadoop and Spark `SnappyCodec` consumers read |
The two Snappy variants share an extension and are told apart only by `Content-Encoding`; they are mutually unreadable, so a consumer must pick the matching decoder. Note that AWS's [object name documentation](https://docs.aws.amazon.com/firehose/latest/dev/s3-object-name.html) tables `.hsnappy` for Hadoop-Snappy, but the service delivers `.snappy`; Floci follows the service.
Any other value, including differently-cased ones such as `SNAPPY` instead of `Snappy`, is rejected with `ValidationException`.
## S3 object keys
Delivered objects are named `<evaluated prefix><streamName>-<versionId>-<yyyy-MM-dd-HH-mm-ss>-<uuid>` (no file extension), matching [AWS's object name format](https://docs.aws.amazon.com/firehose/latest/dev/s3-object-name.html):
Delivered objects are named `<evaluated prefix><streamName>-<versionId>-<yyyy-MM-dd-HH-mm-ss>-<uuid><file extension>`, matching [AWS's object name format](https://docs.aws.amazon.com/firehose/latest/dev/s3-object-name.html):
- Without a `Prefix`, the default prefix `yyyy/MM/dd/HH/` is used.
- A `Prefix` without expressions gets `yyyy/MM/dd/HH/` appended by literal concatenation — no `/` is inserted, exactly like AWS (`legacy` → `legacy2026/07/13/14/...`).
- [Custom prefix expressions](https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html) are evaluated: `!{timestamp:<pattern>}` (Java `DateTimeFormatter` pattern; all instances share the same instant) and `!{firehose:random-string}` (a fresh 11-character alphanumeric string per instance). When the prefix contains any expression, nothing is appended to it.
- `CustomTimeZone` is honored for all timestamps; absent or invalid time zones fall back to UTC.
- `<file extension>` comes from the `CompressionFormat` table above, unless the destination sets `FileExtension`, which **replaces** it rather than being appended to it (`GZIP` plus `FileExtension: .custom.log` yields a key ending in `.custom.log`, with a gzip body and `Content-Encoding: gzip` regardless). The empty string means "not specified" and brings the compression extension back. `FileExtension` must match `^(|\.[0-9a-z!\-_.*'()]+)$` and be at most 128 characters, or the request is rejected with `ValidationException`.
Known deviations from AWS: timestamps are evaluated at flush time instead of the oldest buffered record's arrival time; expressions AWS would reject at create time (unknown namespaces, `!{partitionKeyFromQuery:...}`/`!{partitionKeyFromLambda:...}` dynamic partitioning keys, invalid patterns) are kept literally in the key; delivered content is never compressed, so no compression extension is ever added.
Known deviations from AWS: timestamps are evaluated at flush time instead of the oldest buffered record's arrival time; expressions AWS would reject at create time (unknown namespaces, `!{partitionKeyFromQuery:...}`/`!{partitionKeyFromLambda:...}` dynamic partitioning keys, invalid patterns) are kept literally in the key; `FileExtension` is accepted on the legacy `S3DestinationConfiguration` shape too, where AWS only defines it on the extended one.
## Configuration
+6
View File
@@ -139,6 +139,12 @@
<version>4.3.0</version>
</dependency>
<!-- Snappy for Firehose Snappy/HADOOP_SNAPPY delivery to S3: the only Java
library that writes the xerial stream format AWS uses. -->
<dependency>
<groupId>org.xerial.snappy</groupId>
<artifactId>snappy-java</artifactId>
</dependency>
<!-- Docker client for Lambda container lifecycle management -->
<dependency>
@@ -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());
}
@@ -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);
}
}
@@ -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) {
@@ -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; }
+4
View File
@@ -60,6 +60,10 @@ quarkus:
- --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService
- --initialize-at-run-time=graphql.util.IdGenerator
- --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials
# snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a
# bundled JNI library from the static initializers of these two classes.
- --initialize-at-run-time=org.xerial.snappy.Snappy
- --initialize-at-run-time=org.xerial.snappy.SnappyLoader
floci:
@@ -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));