mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(firehose): convert JSON records to Parquet via the floci-duck sidecar (#3333)
* feat(firehose): convert JSON records to Parquet via the floci-duck sidecar Deliver data-format-converting streams for real: each flushed record is parsed and type-checked in Java against the stream's Glue table schema (per-record ParseError/MalformedData routing with AWS's probed message shapes), valid rows are staged as normalized NDJSON and written to the destination as Parquet by DuckDB's COPY, and failed records go to the evaluated ErrorOutputPrefix as AWS-shaped NDJSON error lines. Batch-level failures (missing Glue table, unsupported schema, sidecar errors) route every record to the error output instead of dropping them. Adds the floci.services.firehose.staging-bucket setting and replaces the PR-1-era unconverted-delivery warning. * fix(firehose): deliver a scheduled flush as the stream's own account A scheduled flush runs on the flusher thread, where no request context is active, so the Glue lookup, the staging writes, the destination writes and the sidecar all resolved the default account instead of the stream's owner. A stream owned by another account had its Glue table missed and its objects written to the wrong partition. The delivery now runs under RequestScopes, which the CUR scheduler already uses for the same reason, so every store the delivery touches agrees on the owner. The unconverted path gets this too. Cleanup failures in the compatibility test are logged rather than swallowed, per the repository rule on tolerated exceptions. * fix(firehose): cap the staging buffer size hints rows.size() * 128 overflows an int at about 16.7 million records, so a batch of many small records failed before writing any of them, and short of that it asked for a multi-gigabyte array. Both hints are computed as a long and capped at 8 MiB; the streams grow as needed, so this only affects the first allocation. * docs(firehose): state what a failed error-output write actually guarantees The comment claimed a failure of the error-output write leaves the converted rows in the staging bucket, but the enclosing finally removes the staged object however the method exits, and the Parquet bytes are read into memory before either destination write, so nothing is retained to recover from. What holds is that nothing is delivered and the flush fails as a whole, which is what it says now, along with where recovery does live: the source, which a Kinesis-backed stream has and a DirectPut buffer does not. The reverse ordering is documented rather than claimed away: the two destination writes are not atomic, so an error object can land and the Parquet write then fail, reporting the failed records while the converted ones are gone.
This commit is contained in:
1 parent
d4e9dcbe55
commit
9a2a89399a
13 files changed
+2158
-31
No files matched your search
+358
@@ -0,0 +1,358 @@
|
||||
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.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.athena.AthenaClient;
|
||||
import software.amazon.awssdk.services.athena.model.Datum;
|
||||
import software.amazon.awssdk.services.athena.model.QueryExecutionState;
|
||||
import software.amazon.awssdk.services.athena.model.QueryExecutionStatus;
|
||||
import software.amazon.awssdk.services.athena.model.ResultConfiguration;
|
||||
import software.amazon.awssdk.services.athena.model.StartQueryExecutionRequest;
|
||||
import software.amazon.awssdk.services.athena.model.StartQueryExecutionResponse;
|
||||
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.DataFormatConversionConfiguration;
|
||||
import software.amazon.awssdk.services.firehose.model.DeleteDeliveryStreamRequest;
|
||||
import software.amazon.awssdk.services.firehose.model.DeliveryStreamStatus;
|
||||
import software.amazon.awssdk.services.firehose.model.DeliveryStreamType;
|
||||
import software.amazon.awssdk.services.firehose.model.DescribeDeliveryStreamRequest;
|
||||
import software.amazon.awssdk.services.firehose.model.Deserializer;
|
||||
import software.amazon.awssdk.services.firehose.model.ExtendedS3DestinationConfiguration;
|
||||
import software.amazon.awssdk.services.firehose.model.InputFormatConfiguration;
|
||||
import software.amazon.awssdk.services.firehose.model.OpenXJsonSerDe;
|
||||
import software.amazon.awssdk.services.firehose.model.OutputFormatConfiguration;
|
||||
import software.amazon.awssdk.services.firehose.model.ParquetSerDe;
|
||||
import software.amazon.awssdk.services.firehose.model.PutRecordBatchRequest;
|
||||
import software.amazon.awssdk.services.firehose.model.Record;
|
||||
import software.amazon.awssdk.services.firehose.model.SchemaConfiguration;
|
||||
import software.amazon.awssdk.services.firehose.model.Serializer;
|
||||
import software.amazon.awssdk.services.glue.GlueClient;
|
||||
import software.amazon.awssdk.services.glue.model.Column;
|
||||
import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;
|
||||
import software.amazon.awssdk.services.glue.model.CreateTableRequest;
|
||||
import software.amazon.awssdk.services.glue.model.DatabaseInput;
|
||||
import software.amazon.awssdk.services.glue.model.DeleteDatabaseRequest;
|
||||
import software.amazon.awssdk.services.glue.model.DeleteTableRequest;
|
||||
import software.amazon.awssdk.services.glue.model.SerDeInfo;
|
||||
import software.amazon.awssdk.services.glue.model.StorageDescriptor;
|
||||
import software.amazon.awssdk.services.glue.model.TableInput;
|
||||
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.ListObjectsV2Request;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* End-to-end proof that a data-format-converting stream delivers a real
|
||||
* Parquet object: records put through the SDK come back out of S3 as a file
|
||||
* carrying the PAR1 magic under a .parquet key, and the records that cannot
|
||||
* convert land under the evaluated ErrorOutputPrefix as AWS-shaped NDJSON
|
||||
* error lines. Against Floci this exercises the floci-duck sidecar for real,
|
||||
* which the emulator's unit tests mock.
|
||||
*/
|
||||
@DisplayName("Firehose data format conversion delivery (JSON to Parquet)")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class FirehoseParquetDeliveryTest {
|
||||
|
||||
private static final int BUFFERING_INTERVAL_SECONDS = 5;
|
||||
private static final long POLL_TIMEOUT_MILLIS = 240_000L;
|
||||
private static final byte[] PARQUET_MAGIC = "PAR1".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
private static final String VALID_RECORD_1 =
|
||||
"{\"ticker\": \"AAA\", \"price\": 1.5, \"qty\": 10, \"active\": true, \"ts\": \"2026-09-07 12:00:00\"}\n";
|
||||
private static final String VALID_RECORD_2 = "{\"ticker\": \"MISSING_FIELDS\"}\n";
|
||||
private static final String MISMATCH_RECORD = "{\"ticker\": \"BAD\", \"price\": \"oops\"}\n";
|
||||
private static final String UNPARSEABLE_RECORD = "this is not json at all\n";
|
||||
|
||||
private static FirehoseClient firehose;
|
||||
private static GlueClient glue;
|
||||
private static S3Client s3;
|
||||
private static String bucket;
|
||||
private static String streamName;
|
||||
private static String database;
|
||||
private static final String TABLE = "events";
|
||||
|
||||
@BeforeAll
|
||||
static void setup() throws InterruptedException {
|
||||
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();
|
||||
glue = TestFixtures.glueClient();
|
||||
s3 = TestFixtures.s3Client();
|
||||
bucket = TestFixtures.uniqueName("firehose-parquet");
|
||||
streamName = TestFixtures.uniqueName("sdk-parquet");
|
||||
database = TestFixtures.uniqueName("firehose_parquet_db").replace('-', '_');
|
||||
|
||||
s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
|
||||
glue.createDatabase(CreateDatabaseRequest.builder()
|
||||
.databaseInput(DatabaseInput.builder().name(database).build()).build());
|
||||
glue.createTable(CreateTableRequest.builder()
|
||||
.databaseName(database)
|
||||
.tableInput(TableInput.builder()
|
||||
.name(TABLE)
|
||||
.tableType("EXTERNAL_TABLE")
|
||||
.storageDescriptor(StorageDescriptor.builder()
|
||||
.columns(
|
||||
Column.builder().name("ticker").type("string").build(),
|
||||
Column.builder().name("price").type("double").build(),
|
||||
Column.builder().name("qty").type("int").build(),
|
||||
Column.builder().name("active").type("boolean").build(),
|
||||
Column.builder().name("ts").type("timestamp").build())
|
||||
// The destination prefix with a Parquet SerDe, as a real
|
||||
// Firehose-to-Parquet setup defines it, so the delivered
|
||||
// objects can be read back through Athena.
|
||||
.location("s3://" + bucket + "/data/")
|
||||
.inputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat")
|
||||
.outputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat")
|
||||
.serdeInfo(SerDeInfo.builder()
|
||||
.serializationLibrary(
|
||||
"org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe")
|
||||
.build())
|
||||
.build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
firehose.createDeliveryStream(CreateDeliveryStreamRequest.builder()
|
||||
.deliveryStreamName(streamName)
|
||||
.deliveryStreamType(DeliveryStreamType.DIRECT_PUT)
|
||||
.extendedS3DestinationConfiguration(ExtendedS3DestinationConfiguration.builder()
|
||||
.roleARN(roleArn)
|
||||
.bucketARN("arn:aws:s3:::" + bucket)
|
||||
.prefix("data/")
|
||||
.errorOutputPrefix("errors/!{firehose:error-output-type}/")
|
||||
.compressionFormat(CompressionFormat.UNCOMPRESSED)
|
||||
.bufferingHints(BufferingHints.builder()
|
||||
.sizeInMBs(64)
|
||||
.intervalInSeconds(BUFFERING_INTERVAL_SECONDS)
|
||||
.build())
|
||||
.dataFormatConversionConfiguration(DataFormatConversionConfiguration.builder()
|
||||
.enabled(true)
|
||||
.schemaConfiguration(SchemaConfiguration.builder()
|
||||
.roleARN(roleArn)
|
||||
.databaseName(database)
|
||||
.tableName(TABLE)
|
||||
.build())
|
||||
.inputFormatConfiguration(InputFormatConfiguration.builder()
|
||||
.deserializer(Deserializer.builder()
|
||||
.openXJsonSerDe(OpenXJsonSerDe.builder().build())
|
||||
.build())
|
||||
.build())
|
||||
.outputFormatConfiguration(OutputFormatConfiguration.builder()
|
||||
.serializer(Serializer.builder()
|
||||
.parquetSerDe(ParquetSerDe.builder().build())
|
||||
.build())
|
||||
.build())
|
||||
.build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
awaitStreamActive();
|
||||
|
||||
assertThat(firehose.putRecordBatch(PutRecordBatchRequest.builder()
|
||||
.deliveryStreamName(streamName)
|
||||
.records(
|
||||
record(VALID_RECORD_1),
|
||||
record(VALID_RECORD_2),
|
||||
record(MISMATCH_RECORD),
|
||||
record(UNPARSEABLE_RECORD))
|
||||
.build()).failedPutCount()).isZero();
|
||||
}
|
||||
|
||||
// Real AWS returns from CreateDeliveryStream while the stream is still CREATING
|
||||
// and rejects PutRecordBatch until it turns ACTIVE; Floci creates it active, so
|
||||
// this returns on the first poll locally.
|
||||
private static void awaitStreamActive() throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + POLL_TIMEOUT_MILLIS;
|
||||
while (true) {
|
||||
DeliveryStreamStatus status = firehose.describeDeliveryStream(
|
||||
DescribeDeliveryStreamRequest.builder()
|
||||
.deliveryStreamName(streamName).build())
|
||||
.deliveryStreamDescription().deliveryStreamStatus();
|
||||
if (status == DeliveryStreamStatus.ACTIVE) {
|
||||
return;
|
||||
}
|
||||
if (System.currentTimeMillis() >= deadline) {
|
||||
throw new AssertionError("delivery stream stayed " + status + " for "
|
||||
+ POLL_TIMEOUT_MILLIS / 1000 + "s");
|
||||
}
|
||||
Thread.sleep(5_000L);
|
||||
}
|
||||
}
|
||||
|
||||
private static Record record(String data) {
|
||||
return Record.builder().data(SdkBytes.fromString(data, StandardCharsets.UTF_8)).build();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (firehose != null) {
|
||||
try {
|
||||
firehose.deleteDeliveryStream(DeleteDeliveryStreamRequest.builder()
|
||||
.deliveryStreamName(streamName).build());
|
||||
} catch (Exception e) {
|
||||
// Best effort: a stream that never got created must not fail the run.
|
||||
System.out.println("Cleanup of delivery stream " + streamName + " failed: " + e);
|
||||
}
|
||||
firehose.close();
|
||||
}
|
||||
if (glue != null) {
|
||||
try {
|
||||
glue.deleteTable(DeleteTableRequest.builder().databaseName(database).name(TABLE).build());
|
||||
glue.deleteDatabase(DeleteDatabaseRequest.builder().name(database).build());
|
||||
} catch (Exception e) {
|
||||
// Best effort cleanup of the probe schema.
|
||||
System.out.println("Cleanup of Glue database " + database + " failed: " + e);
|
||||
}
|
||||
glue.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 e) {
|
||||
// Best effort cleanup of the probe bucket.
|
||||
System.out.println("Cleanup of bucket " + bucket + " failed: " + e);
|
||||
}
|
||||
s3.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
@DisplayName("Valid records are delivered as one Parquet object under a .parquet key")
|
||||
void deliversARealParquetObject() throws Exception {
|
||||
String key = waitForDeliveredKey("data/");
|
||||
|
||||
assertThat(key).endsWith(".parquet");
|
||||
byte[] body = s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build())
|
||||
.readAllBytes();
|
||||
assertThat(body.length).isGreaterThan(PARQUET_MAGIC.length * 2);
|
||||
assertThat(java.util.Arrays.copyOfRange(body, 0, PARQUET_MAGIC.length))
|
||||
.as("delivered object must start with the Parquet magic")
|
||||
.isEqualTo(PARQUET_MAGIC);
|
||||
assertThat(java.util.Arrays.copyOfRange(body, body.length - PARQUET_MAGIC.length, body.length))
|
||||
.as("delivered object must end with the Parquet magic")
|
||||
.isEqualTo(PARQUET_MAGIC);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
@DisplayName("Unconvertible records land under errors/format-conversion-failed/ as NDJSON")
|
||||
void routesFailedRecordsToTheErrorOutput() throws Exception {
|
||||
String key = waitForDeliveredKey("errors/format-conversion-failed/");
|
||||
|
||||
String lastSegment = key.substring(key.lastIndexOf('/') + 1);
|
||||
assertThat(lastSegment).as("error object carries no file extension").doesNotContain(".");
|
||||
|
||||
byte[] body = s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build())
|
||||
.readAllBytes();
|
||||
List<String> lines = new String(body, StandardCharsets.UTF_8).strip().lines().toList();
|
||||
assertThat(lines).hasSize(2);
|
||||
|
||||
String mismatch = lines.stream().filter(l -> l.contains("MalformedData")).findFirst().orElseThrow();
|
||||
assertThat(mismatch).contains("\"lastErrorCode\":\"DataFormatConversion.MalformedData\"");
|
||||
assertThat(mismatch).contains(
|
||||
Base64.getEncoder().encodeToString(MISMATCH_RECORD.getBytes(StandardCharsets.UTF_8)));
|
||||
assertThat(mismatch).contains("\"databaseName\":\"" + database + "\"");
|
||||
|
||||
String unparseable = lines.stream().filter(l -> l.contains("ParseError")).findFirst().orElseThrow();
|
||||
assertThat(unparseable).contains("\"lastErrorCode\":\"DataFormatConversion.ParseError\"");
|
||||
assertThat(unparseable).contains(
|
||||
Base64.getEncoder().encodeToString(UNPARSEABLE_RECORD.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The PAR1 framing only proves the object is a Parquet file. Reading it back
|
||||
* through Athena, which resolves the Glue table to the delivery prefix, is what
|
||||
* shows the projection itself is right: both valid records are present, the
|
||||
* absent members became null rather than being dropped, and the values kept
|
||||
* their column types instead of arriving as strings.
|
||||
*/
|
||||
@Test
|
||||
@Order(3)
|
||||
@DisplayName("The delivered Parquet reads back through Athena with typed values")
|
||||
void deliveredParquetReadsBackThroughAthena() throws Exception {
|
||||
waitForDeliveredKey("data/");
|
||||
|
||||
try (AthenaClient athena = TestFixtures.athenaClient()) {
|
||||
StartQueryExecutionResponse started = athena.startQueryExecution(
|
||||
StartQueryExecutionRequest.builder()
|
||||
.queryString("SELECT ticker, price, qty, active, ts FROM \"" + database
|
||||
+ "\".\"" + TABLE + "\" ORDER BY ticker")
|
||||
.workGroup("primary")
|
||||
.resultConfiguration(ResultConfiguration.builder()
|
||||
.outputLocation("s3://" + bucket + "/athena-results/")
|
||||
.build())
|
||||
.build());
|
||||
|
||||
QueryExecutionStatus status = TestFixtures.awaitAthenaQueryTerminal(
|
||||
athena, started.queryExecutionId(), Duration.ofSeconds(120));
|
||||
assertThat(status.state())
|
||||
.as("Athena read-back did not succeed: %s", status.stateChangeReason())
|
||||
.isEqualTo(QueryExecutionState.SUCCEEDED);
|
||||
|
||||
List<List<String>> rows = athena.getQueryResults(r -> r
|
||||
.queryExecutionId(started.queryExecutionId()))
|
||||
.resultSet().rows().stream()
|
||||
.map(row -> row.data().stream().map(Datum::varCharValue).toList())
|
||||
.filter(row -> !"ticker".equals(row.get(0)))
|
||||
.toList();
|
||||
|
||||
assertThat(rows).as("both valid records must be in the Parquet object").hasSize(2);
|
||||
|
||||
List<String> typed = rows.stream().filter(row -> "AAA".equals(row.get(0))).findFirst()
|
||||
.orElseThrow();
|
||||
assertThat(typed.get(1)).isEqualTo("1.5");
|
||||
assertThat(typed.get(2)).isEqualTo("10");
|
||||
assertThat(typed.get(3)).isIn("true", "TRUE");
|
||||
assertThat(typed.get(4)).startsWith("2026-09-07 12:00:00");
|
||||
|
||||
List<String> sparse = rows.stream().filter(row -> "MISSING_FIELDS".equals(row.get(0)))
|
||||
.findFirst().orElseThrow();
|
||||
assertThat(sparse).as("no column may be dropped for a sparse record").hasSize(5);
|
||||
// Real Athena omits VarCharValue for a null cell, which the SDK maps to
|
||||
// null; Floci returns an empty string, so both spellings are accepted.
|
||||
assertThat(sparse.subList(1, sparse.size()))
|
||||
.as("members absent from the record must be null, not dropped")
|
||||
.allSatisfy(value -> assertThat(value).isNullOrEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -244,6 +244,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
|
||||
| `FLOCI_SERVICES_FIREHOSE_ENABLED` | `true` | Enable the Kinesis Data Firehose service |
|
||||
| `FLOCI_SERVICES_FIREHOSE_TICK_INTERVAL_SECONDS` | `10` | How often (seconds) the buffer flusher checks for streams whose `BufferingHints.IntervalInSeconds` has elapsed |
|
||||
| `FLOCI_SERVICES_FIREHOSE_FLUSH_RECORD_COUNT` | `0` | Emulator-only: flush after this many buffered records (`0` = disabled, AWS-faithful; `1` = LocalStack-style record-at-a-time delivery) |
|
||||
| `FLOCI_SERVICES_FIREHOSE_STAGING_BUCKET` | `floci-firehose-staging` | S3 bucket used to stage NDJSON batches before DuckDB writes the Parquet object for format-converting streams |
|
||||
|
||||
### EventBridge
|
||||
|
||||
|
||||
@@ -59,7 +59,13 @@ Any other value, including differently-cased ones such as `SNAPPY` instead of `S
|
||||
|
||||
## Data format conversion
|
||||
|
||||
`DataFormatConversionConfiguration` on the extended S3 destination is accepted, validated, persisted, and echoed back by `DescribeDeliveryStream`. **The conversion itself, JSON to Parquet at delivery time, is not implemented yet**: a conversion-enabled stream delivers its records unconverted, under the usual key format, and creating or updating one logs a warning saying so.
|
||||
`DataFormatConversionConfiguration` on the extended S3 destination converts buffered JSON records to Parquet at delivery time, typed by the stream's Glue table schema. Parquet is the only format Floci writes: the configuration is validated as AWS models it, but an enabled `OrcSerDe` is rejected at create and update time, so the rest of this section describes the Parquet path only. The Parquet file itself is written by the `floci-duck` sidecar (the same engine behind Athena, S3 Select, and CUR), so conversion needs Docker available, or a pre-started sidecar via `floci.services.duck.url`.
|
||||
|
||||
Each buffered record is parsed and type-checked against the Glue table's columns. The valid rows are staged as NDJSON in `floci.services.firehose.staging-bucket`, then written to the destination as one Parquet object keyed like any other delivery but ending in `.parquet`, unless `FileExtension` replaces it. `ParquetSerDe.Compression` picks the codec, SNAPPY by default.
|
||||
|
||||
Records that cannot be converted fail **individually**, as on AWS: the rest of the batch still converts. They are delivered instead to the evaluated `ErrorOutputPrefix`, where `!{firehose:error-output-type}` resolves to `format-conversion-failed`, as one extensionless object holding an NDJSON line per record: `attemptsMade`, `arrivalTimestamp`, `lastErrorCode`, `lastErrorMessage`, `attemptEndingTimestamp`, base64 `rawData`, and a `dataCatalogTable` block. The code is `DataFormatConversion.ParseError` for a record that is not valid JSON, `DataFormatConversion.MalformedData` for one whose values do not fit the column types.
|
||||
|
||||
A failure of the batch as a whole is routed rather than discarded: a missing Glue table, a schema Floci cannot convert, or a sidecar failure sends every buffered record to the error output, under `DataFormatConversion.EntityNotFoundException`, `.UnsupportedSchema` and `.InternalError` respectively; those three codes are Floci's own. That routing is only as good as the write it depends on. Floci does not retry a delivery, and a flush whose S3 write fails loses its batch on a DirectPut stream, with or without conversion. The two destination writes of a mixed batch are not atomic either: the error output is written first, so its failure delivers nothing at all, but the reverse remains possible, where the error object lands and the Parquet write then fails, reporting the failed records while the converted ones are gone.
|
||||
|
||||
Validation matches AWS on both `CreateDeliveryStream` and `UpdateDestination`, down to the [modeled](https://docs.aws.amazon.com/firehose/latest/APIReference/API_DataFormatConversionConfiguration.html) bounds, enums and patterns, so a raw JSON client cannot store a configuration AWS would reject. Two rules are worth knowing because they constrain the destination rather than the conversion block: `CompressionFormat` must be `UNCOMPRESSED`, compression being chosen by the output serializer instead, and an explicitly specified `BufferingHints.SizeInMBs` must be at least 64. Omitting `BufferingHints` stores 128 MiB, AWS's larger default for converting streams, rather than the ordinary 5 MiB.
|
||||
|
||||
@@ -67,10 +73,15 @@ An omitted `Enabled` counts as enabled; `Enabled: false` stores and merges the c
|
||||
|
||||
### Known deviations from AWS
|
||||
|
||||
- **An enabled `OrcSerDe` is rejected** with `InvalidArgumentException` at create/update time. Real AWS accepts it; Floci's planned conversion engine (DuckDB) cannot write ORC, and refusing early beats storing a configuration that could never deliver. A disabled one is stored and echoed with its ORC members intact.
|
||||
- **The Glue table is not resolved at create or update time.** Real AWS rejects a `SchemaConfiguration` naming a database or table that does not exist, with `InvalidArgumentException` wrapping a Glue `EntityNotFoundException`; Floci accepts it. Floci performs no role-assumption check either, where AWS validates the role last.
|
||||
- **An enabled `OrcSerDe` is rejected** with `InvalidArgumentException` at create/update time. Real AWS accepts it; DuckDB cannot write ORC, and refusing early beats storing a configuration that could never deliver. A disabled one is stored and echoed with its ORC members intact.
|
||||
- **The Glue table is not resolved at create or update time.** Real AWS rejects a `SchemaConfiguration` naming a database or table that does not exist, with `InvalidArgumentException` wrapping a Glue `EntityNotFoundException`. Floci accepts it and only discovers the missing table at delivery, routing that batch to the error output as `DataFormatConversion.EntityNotFoundException`. Floci performs no role-assumption check either, where AWS validates the role last.
|
||||
- **Two kinds of validation are skipped**: the element constraints AWS puts on `OrcSerDe.BloomFilterColumns` and `HiveJsonSerDe.TimestampFormats` entries (the equivalent ones on `ColumnToJsonKeyMappings` are enforced), and AWS's semantic check of SerDe option values, which answers `InvalidArgumentException` ("Invalid deserializer option(s): ...") for a well-formed but unusable value.
|
||||
- A malformed but non-empty `SchemaConfiguration.RoleARN` is accepted. AWS answers `InvalidParameterValueException` ("Invalid role ARN.") before its modeled rules run; Floci validates no ARNs, so it applies only the length and pattern rules, which an empty value trips exactly as on AWS.
|
||||
- **Several stored members do not reach the conversion**: `HiveJsonSerDe.TimestampFormats`, `OpenXJsonSerDe.ConvertDotsInJsonKeysToUnderscores`, every `ParquetSerDe` member except `Compression`, and `SchemaConfiguration.Region`, `CatalogId` and `VersionId`, which are not resolved against the Glue store (Floci's catalog is neither region- nor version-partitioned) and only flow into the error-output metadata.
|
||||
- An epoch timestamp outside the range AWS's Parquet writer can hold wraps there into an unrelated instant (probed: `999999999999` seconds arrives as the year 2092, not 33658). Floci keeps such a value as long as it is representable as a `TIMESTAMP`, and fails only a value beyond that, as its own record's `DataFormatConversion.MalformedData` rather than as a silently corrupted row.
|
||||
- Complex and binary Hive types (`array`, `map`, `struct`, `binary`) are not convertible; a schema containing them routes the batch to the error output as `DataFormatConversion.UnsupportedSchema`.
|
||||
- Error-output records report the delivery time as both `arrivalTimestamp` and `attemptEndingTimestamp` (Floci does not track per-record arrival), and omit AWS's `sequenceNumber`/`subSequenceNumber` members. An absent `ErrorOutputPrefix` writes them at the bucket root with no default time prefix, which matches AWS's object-name documentation but was not probed.
|
||||
- The Parquet object carries no `Content-Encoding`, where AWS labels it `hadoop-snappy` even though the body is a plain Parquet file (probed), and its row order may differ from put order, as it does on AWS (probed).
|
||||
|
||||
## S3 object keys
|
||||
|
||||
@@ -89,6 +100,7 @@ Known deviations from AWS: timestamps are evaluated at flush time instead of the
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_FIREHOSE_ENABLED` | `true` | Enable or disable the service |
|
||||
| `FLOCI_SERVICES_FIREHOSE_STAGING_BUCKET` | `floci-firehose-staging` | S3 bucket used to stage NDJSON batches before DuckDB writes the Parquet object |
|
||||
|
||||
## Example
|
||||
|
||||
|
||||
@@ -1492,6 +1492,14 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("0")
|
||||
int flushRecordCount();
|
||||
|
||||
/**
|
||||
* S3 bucket used to stage validated NDJSON batches before DuckDB writes
|
||||
* the Parquet object for data-format-converting delivery streams.
|
||||
* Created on first use if it doesn't exist.
|
||||
*/
|
||||
@WithDefault("floci-firehose-staging")
|
||||
String stagingBucket();
|
||||
}
|
||||
|
||||
interface KmsServiceConfig {
|
||||
|
||||
+834
@@ -0,0 +1,834 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.DataFormatConversionConfiguration;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OpenXJsonSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ParquetSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.SchemaConfiguration;
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.services.glue.model.Column;
|
||||
import io.github.hectorvent.floci.services.glue.model.Table;
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.SignStyle;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Delivers a flushed batch of a data-format-converting stream: each record is
|
||||
* parsed and type-checked against the stream's Glue table schema in Java, the
|
||||
* valid rows are staged as normalized NDJSON and written to the destination as
|
||||
* Parquet by the floci-duck sidecar's {@code COPY ... (FORMAT PARQUET)}, and
|
||||
* the failing records go to the error output, one NDJSON line each, under the
|
||||
* evaluated ErrorOutputPrefix.
|
||||
*
|
||||
* The per-record split mirrors real AWS, which routes both unparseable records
|
||||
* ({@code DataFormatConversion.ParseError}, with a raw Jackson message: AWS
|
||||
* itself parses with Jackson) and schema mismatches
|
||||
* ({@code DataFormatConversion.MalformedData}, "Data does not match the
|
||||
* schema. For input string: ...") to the error output individually while the
|
||||
* rest of the batch still converts. Failures of the batch as a whole, a
|
||||
* missing Glue table, a schema Floci cannot convert, or a DuckDB failure,
|
||||
* send every buffered record to the error output instead of dropping them;
|
||||
* the batch-level error codes are Floci's own and are documented as such.
|
||||
*
|
||||
* Typing comes from the Glue schema, never from JSON inference, so a batch's
|
||||
* column types cannot drift with its data. The staged rows are already
|
||||
* normalized to the target types, which keeps the DuckDB {@code COPY}
|
||||
* deterministic; {@code read_json} receives the explicit column list.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class FirehoseParquetConverter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FirehoseParquetConverter.class);
|
||||
private static final String ERROR_OUTPUT_TYPE = "format-conversion-failed";
|
||||
private static final String CONTENT_TYPE = "application/octet-stream";
|
||||
private static final Pattern DECIMAL_TYPE = Pattern.compile("decimal\\((\\d+),\\s*(\\d+)\\)");
|
||||
private static final Pattern SIZED_TEXT_TYPE = Pattern.compile("(char|varchar)\\((\\d+)\\)");
|
||||
private static final int MAX_CHAR_LENGTH = 255;
|
||||
private static final int MAX_VARCHAR_LENGTH = 65535;
|
||||
private static final int MAX_DECIMAL_PRECISION = 38;
|
||||
private static final BigDecimal EPOCH_MILLIS_FLOOR = new BigDecimal("1000000000000");
|
||||
private static final BigDecimal MAX_TIMESTAMP_MILLIS = BigDecimal.valueOf(Long.MAX_VALUE / 1000);
|
||||
private static final int MAX_TIMESTAMP_DIGITS = String.valueOf(Long.MAX_VALUE / 1000).length();
|
||||
private static final int MAX_BUFFER_HINT = 8 * 1024 * 1024;
|
||||
// Probed: AWS reads a space-separated timestamp leniently, one-digit month, day,
|
||||
// hour, minute and second included, and a date column the same way, while its
|
||||
// 'T' form is the strict ISO one and rejects "2026-9-7T12:00:02Z".
|
||||
private static final Pattern DATE_VALUE = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})");
|
||||
private static final Pattern LENIENT_TIMESTAMP = Pattern.compile(
|
||||
"(\\d{4})-(\\d{1,2})-(\\d{1,2}) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})(\\.\\d{1,9})?");
|
||||
private static final Pattern ISO_TIMESTAMP =
|
||||
Pattern.compile("(\\d{4}-\\d{2}-\\d{2})T(\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?)Z?");
|
||||
// A "yyyy" pattern signs any year wider than four digits, and DuckDB cannot cast
|
||||
// the "+33658-.." that an out-of-the-ordinary epoch then produces, which would
|
||||
// fail the COPY for the whole batch rather than just that record. NORMAL drops
|
||||
// that plus while keeping the minus a year before 0000 needs.
|
||||
private static final DateTimeFormatter EPOCH_TIMESTAMP = new DateTimeFormatterBuilder()
|
||||
.appendValue(ChronoField.YEAR, 4, 10, SignStyle.NORMAL)
|
||||
.appendPattern("-MM-dd HH:mm:ss.SSS")
|
||||
.toFormatter(Locale.ROOT)
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private final GlueService glueService;
|
||||
private final FlociDuckClient duckClient;
|
||||
private final S3Service s3Service;
|
||||
private final ObjectMapper mapper;
|
||||
private final ObjectReader recordReader;
|
||||
private final RegionResolver regionResolver;
|
||||
private final String stagingBucket;
|
||||
|
||||
@Inject
|
||||
public FirehoseParquetConverter(GlueService glueService, FlociDuckClient duckClient,
|
||||
S3Service s3Service, ObjectMapper mapper,
|
||||
RegionResolver regionResolver, EmulatorConfig config) {
|
||||
this(glueService, duckClient, s3Service, mapper, regionResolver,
|
||||
config.services().firehose().stagingBucket());
|
||||
}
|
||||
|
||||
FirehoseParquetConverter(GlueService glueService, FlociDuckClient duckClient,
|
||||
S3Service s3Service, ObjectMapper mapper,
|
||||
RegionResolver regionResolver, String stagingBucket) {
|
||||
this.glueService = glueService;
|
||||
this.duckClient = duckClient;
|
||||
this.s3Service = s3Service;
|
||||
this.mapper = mapper;
|
||||
// Trailing content after the first value makes the whole record malformed;
|
||||
// the shared mapper keeps its own settings, so the strictness is scoped here.
|
||||
// USE_BIG_DECIMAL_FOR_FLOATS as well: a DECIMAL column must keep the value the
|
||||
// record carried, and a double cannot hold more than about 17 digits of it.
|
||||
this.recordReader = mapper.reader()
|
||||
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
|
||||
this.regionResolver = regionResolver;
|
||||
this.stagingBucket = stagingBucket;
|
||||
}
|
||||
|
||||
/** What a delivery produced, for the flush log line. */
|
||||
public record Outcome(int convertedRecords, int failedRecords, String dataKey, String errorKey) {}
|
||||
|
||||
public Outcome deliver(DeliveryStreamDescription stream, String bucket, List<byte[]> records,
|
||||
Instant deliveryTime) {
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
DataFormatConversionConfiguration conversion = s3.getDataFormatConversionConfiguration();
|
||||
SchemaConfiguration schemaConfig = conversion.getSchemaConfiguration();
|
||||
|
||||
List<ColumnSpec> schema;
|
||||
try {
|
||||
schema = resolveSchema(schemaConfig);
|
||||
} catch (AwsException e) {
|
||||
return failWholeBatch(stream, s3, bucket, records, deliveryTime, schemaConfig,
|
||||
"DataFormatConversion." + e.getErrorCode(), e.getMessage());
|
||||
} catch (UnsupportedSchemaException e) {
|
||||
return failWholeBatch(stream, s3, bucket, records, deliveryTime, schemaConfig,
|
||||
"DataFormatConversion.UnsupportedSchema", e.getMessage());
|
||||
}
|
||||
|
||||
KeyResolver keyResolver = keyResolver(conversion);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
List<FailedRecord> failures = new ArrayList<>();
|
||||
for (byte[] record : records) {
|
||||
try {
|
||||
rows.add(project(record, schema, keyResolver));
|
||||
} catch (RecordConversionException e) {
|
||||
failures.add(new FailedRecord(record, e.errorCode, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
// The conversion runs against the staging bucket first, so the batch's outcome
|
||||
// is settled before anything reaches the destination. Each destination key is
|
||||
// then written exactly once: no overwrite, and no consumer of the bucket's
|
||||
// notifications sees a partial error object replaced by a batch-level one.
|
||||
String stagedParquetKey = null;
|
||||
if (!rows.isEmpty()) {
|
||||
try {
|
||||
stagedParquetKey = convertToStagedParquet(stream, s3, schema, rows, deliveryTime,
|
||||
conversion.getOutputFormatConfiguration().getSerializer().getParquetSerDe());
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Parquet conversion for stream {0} failed, routing the batch to the error output: {1}",
|
||||
stream.getDeliveryStreamName(), e.getMessage());
|
||||
return failWholeBatch(stream, s3, bucket, records, deliveryTime, schemaConfig,
|
||||
"DataFormatConversion.InternalError",
|
||||
"Floci could not convert the batch: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] parquet = null;
|
||||
if (stagedParquetKey != null) {
|
||||
try {
|
||||
parquet = s3Service.getObject(stagingBucket, stagedParquetKey).getData();
|
||||
} catch (Exception e) {
|
||||
// Read before either destination write, so a sidecar that reported
|
||||
// success without a readable object still fails the batch as a whole
|
||||
// rather than after its per-record errors are already published.
|
||||
LOG.errorv("Staged Parquet for stream {0} could not be read back,"
|
||||
+ " routing the batch to the error output: {1}",
|
||||
stream.getDeliveryStreamName(), e.getMessage());
|
||||
return failWholeBatch(stream, s3, bucket, records, deliveryTime, schemaConfig,
|
||||
"DataFormatConversion.InternalError",
|
||||
"Floci could not convert the batch: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Still before the Parquet: a failure here delivers nothing at all and the
|
||||
// flush fails as a whole. Nothing is kept for a retry, the staged object goes
|
||||
// on the way out either way, so recovery belongs to the source: a Kinesis
|
||||
// stream re-reads its uncommitted checkpoint, a DirectPut buffer cannot.
|
||||
String errorKey = failures.isEmpty()
|
||||
? null
|
||||
: writeErrorOutput(stream, s3, bucket, failures, deliveryTime, schemaConfig);
|
||||
String dataKey = null;
|
||||
if (parquet != null) {
|
||||
dataKey = S3ObjectKeyResolver.resolveKey(s3, stream.getDeliveryStreamName(),
|
||||
stream.getVersionId(), deliveryTime, ".parquet");
|
||||
// Put rather than copy: a delivery notification is ObjectCreated:Put on
|
||||
// AWS and on the unconverted path, and copyObject would announce this one
|
||||
// as ObjectCreated:Copy to any subscriber filtering on the event name.
|
||||
s3Service.putObject(bucket, dataKey, parquet, CONTENT_TYPE, Map.of());
|
||||
}
|
||||
return new Outcome(rows.size(), failures.size(), dataKey, errorKey);
|
||||
} finally {
|
||||
if (stagedParquetKey != null) {
|
||||
safeDelete(stagedParquetKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── schema resolution ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The Glue store is not region- or catalog-partitioned, so
|
||||
* SchemaConfiguration.Region and CatalogId only flow into the error-output
|
||||
* metadata; VersionId is not resolved (the live table is always used).
|
||||
*/
|
||||
private List<ColumnSpec> resolveSchema(SchemaConfiguration schemaConfig) {
|
||||
Table table = glueService.getTable(schemaConfig.getDatabaseName(), schemaConfig.getTableName());
|
||||
List<Column> columns = table.getStorageDescriptor() == null
|
||||
? null : table.getStorageDescriptor().getColumns();
|
||||
if (columns == null || columns.isEmpty()) {
|
||||
throw new UnsupportedSchemaException("Glue table " + schemaConfig.getDatabaseName() + "."
|
||||
+ schemaConfig.getTableName() + " has no columns.");
|
||||
}
|
||||
List<ColumnSpec> schema = new ArrayList<>(columns.size());
|
||||
for (Column column : columns) {
|
||||
if (column == null) {
|
||||
throw new UnsupportedSchemaException("Table " + schemaConfig.getDatabaseName() + "."
|
||||
+ schemaConfig.getTableName() + " has a null column.");
|
||||
}
|
||||
String name = column.getName();
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new UnsupportedSchemaException("Column name " + name
|
||||
+ " is not supported for Parquet conversion.");
|
||||
}
|
||||
ColumnSpec spec = ColumnSpec.fromHiveType(name, column.getType());
|
||||
if (spec == null) {
|
||||
throw new UnsupportedSchemaException("Column " + name + " has Hive type " + column.getType()
|
||||
+ ", which Floci cannot convert to Parquet.");
|
||||
}
|
||||
schema.add(spec);
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
|
||||
// ── per-record projection ────────────────────────────────────────────────
|
||||
|
||||
private Map<String, Object> project(byte[] record, List<ColumnSpec> schema, KeyResolver keyResolver) {
|
||||
JsonNode node;
|
||||
try {
|
||||
// readValue rather than readTree: an empty or blank record makes the tree
|
||||
// reader answer with nothing at all, which would then be mistaken for a
|
||||
// parsed non-object, where this raises Jackson's own end-of-input error.
|
||||
node = recordReader.readValue(record, JsonNode.class);
|
||||
} catch (Exception e) {
|
||||
throw new RecordConversionException("DataFormatConversion.ParseError",
|
||||
"Encountered malformed JSON. " + e.getMessage());
|
||||
}
|
||||
if (node == null || !node.isObject()) {
|
||||
throw new RecordConversionException("DataFormatConversion.MalformedData",
|
||||
"Data does not match the schema. A JSON object is required.");
|
||||
}
|
||||
Map<String, JsonNode> index = keyResolver.index(node);
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
for (ColumnSpec column : schema) {
|
||||
JsonNode value = keyResolver.find(node, index, column.name());
|
||||
row.put(column.name(), value == null || value.isNull() ? null : column.coerce(value));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a schema column to the JSON member holding its value. OpenX's
|
||||
* ColumnToJsonKeyMappings renames the key that is looked up; the lookup
|
||||
* itself is an exact match first, then a case-insensitive one unless
|
||||
* OpenX's CaseInsensitive is explicitly false (case-insensitive is the
|
||||
* SerDe's documented default, and it lowercases keys before deserializing,
|
||||
* so a mapped key matches whatever case the record carries). HiveJsonSerDe
|
||||
* follows the same path; its TimestampFormats are not honored (documented
|
||||
* deviation).
|
||||
*/
|
||||
private static KeyResolver keyResolver(DataFormatConversionConfiguration conversion) {
|
||||
OpenXJsonSerDe openX = conversion.getInputFormatConfiguration().getDeserializer().getOpenXJsonSerDe();
|
||||
Map<String, String> mappings = openX == null || openX.getColumnToJsonKeyMappings() == null
|
||||
? Map.of() : openX.getColumnToJsonKeyMappings();
|
||||
boolean caseInsensitive = openX == null || !Boolean.FALSE.equals(openX.getCaseInsensitive());
|
||||
return new KeyResolver() {
|
||||
@Override
|
||||
public Map<String, JsonNode> index(JsonNode record) {
|
||||
if (!caseInsensitive) {
|
||||
return Map.of();
|
||||
}
|
||||
// Built once per record rather than rescanned per column: a wide
|
||||
// schema over a 128 MiB batch would otherwise cost columns x fields.
|
||||
// First occurrence wins, as the per-column scan it replaces did.
|
||||
Map<String, JsonNode> byLowerKey = new LinkedHashMap<>();
|
||||
var fields = record.fields();
|
||||
while (fields.hasNext()) {
|
||||
var field = fields.next();
|
||||
byLowerKey.putIfAbsent(field.getKey().toLowerCase(Locale.ROOT), field.getValue());
|
||||
}
|
||||
return byLowerKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonNode find(JsonNode record, Map<String, JsonNode> index, String column) {
|
||||
String key = mappings.getOrDefault(column, column);
|
||||
JsonNode exact = record.get(key);
|
||||
if (exact != null || !caseInsensitive) {
|
||||
return exact;
|
||||
}
|
||||
return index.get(key.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ── parquet write via floci-duck ─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Converts the batch into a Parquet object in the staging bucket and returns its
|
||||
* key. Delivery copies it to the destination only once the whole batch's outcome
|
||||
* is known, so a conversion failure never has to undo a destination write.
|
||||
*/
|
||||
private String convertToStagedParquet(DeliveryStreamDescription stream, S3Destination s3,
|
||||
List<ColumnSpec> schema, List<Map<String, Object>> rows,
|
||||
Instant deliveryTime, ParquetSerDe parquetSerDe) throws Exception {
|
||||
String runId = UUID.randomUUID().toString();
|
||||
String parquetKey = "firehose-staging/" + stream.getDeliveryStreamName() + "/" + runId + ".parquet";
|
||||
String stagingKey = "firehose-staging/" + stream.getDeliveryStreamName() + "/" + runId + ".ndjson";
|
||||
ensureStagingBucket();
|
||||
|
||||
// Straight to bytes: a default converting batch buffers 128 MiB, and going
|
||||
// through a StringBuilder and a String would hold two more copies of it.
|
||||
ByteArrayOutputStream ndjson = new ByteArrayOutputStream(initialSize(rows.size(), 128));
|
||||
for (Map<String, Object> row : rows) {
|
||||
ndjson.write(mapper.writeValueAsBytes(row));
|
||||
ndjson.write('\n');
|
||||
}
|
||||
s3Service.putObject(stagingBucket, stagingKey, ndjson.toByteArray(),
|
||||
"application/x-ndjson", Map.of());
|
||||
try {
|
||||
StringBuilder columns = new StringBuilder();
|
||||
for (ColumnSpec column : schema) {
|
||||
if (columns.length() > 0) {
|
||||
columns.append(", ");
|
||||
}
|
||||
// Glue column names are broader than SQL identifiers, so the name is
|
||||
// escaped like any other literal rather than restricted up front.
|
||||
columns.append('\'').append(escapeSqlLiteral(column.name()))
|
||||
.append("': '").append(column.duckType()).append('\'');
|
||||
}
|
||||
// floci-duck's /execute wraps the main sql field in a CSV-emitting COPY
|
||||
// for Athena compatibility, so the Parquet COPY goes in setup_sql and the
|
||||
// wrapped sql is a throwaway SELECT. Passing no output path keeps that
|
||||
// export from running at all: it would be a second way to fail after the
|
||||
// Parquet object is already written, and its failure would send a batch
|
||||
// that converted fine to the error output.
|
||||
String setupSql = "COPY (SELECT * FROM read_json('"
|
||||
+ escapeSqlLiteral("s3://" + stagingBucket + "/" + stagingKey)
|
||||
+ "', format='newline_delimited', columns={" + columns + "})) TO '"
|
||||
+ escapeSqlLiteral("s3://" + stagingBucket + "/" + parquetKey)
|
||||
+ "' (FORMAT PARQUET, COMPRESSION " + parquetCompression(parquetSerDe) + ")";
|
||||
// The account S3Service itself resolved, so the sidecar reads the staged
|
||||
// NDJSON from, and writes the Parquet to, the same partition. A scheduled
|
||||
// flush establishes the stream's own account before reaching here, so this
|
||||
// is the owner in that path as much as in a request.
|
||||
try {
|
||||
duckClient.execute("SELECT 1 AS ok", setupSql, null, regionResolver.getAccountId());
|
||||
} catch (Exception e) {
|
||||
// The COPY may have completed even though the call reports failure, so
|
||||
// the object is removed here: the caller never learns its key and could
|
||||
// not clean it up, and a repeating failure would fill the staging bucket.
|
||||
safeDelete(parquetKey);
|
||||
throw e;
|
||||
}
|
||||
return parquetKey;
|
||||
} finally {
|
||||
safeDelete(stagingKey);
|
||||
}
|
||||
}
|
||||
|
||||
/** Real AWS defaults ParquetSerDe compression to SNAPPY; create-time validation pins the enum. */
|
||||
private static String parquetCompression(ParquetSerDe parquetSerDe) {
|
||||
String compression = parquetSerDe == null || parquetSerDe.getCompression() == null
|
||||
? "SNAPPY" : parquetSerDe.getCompression();
|
||||
return switch (compression) {
|
||||
case "GZIP" -> "GZIP";
|
||||
case "UNCOMPRESSED" -> "UNCOMPRESSED";
|
||||
default -> "SNAPPY";
|
||||
};
|
||||
}
|
||||
|
||||
// ── error output ─────────────────────────────────────────────────────────
|
||||
|
||||
private Outcome failWholeBatch(DeliveryStreamDescription stream, S3Destination s3, String bucket,
|
||||
List<byte[]> records, Instant deliveryTime,
|
||||
SchemaConfiguration schemaConfig, String errorCode, String errorMessage) {
|
||||
List<FailedRecord> failures = new ArrayList<>(records.size());
|
||||
for (byte[] record : records) {
|
||||
failures.add(new FailedRecord(record, errorCode, errorMessage));
|
||||
}
|
||||
String errorKey = writeErrorOutput(stream, s3, bucket, failures, deliveryTime, schemaConfig);
|
||||
return new Outcome(0, failures.size(), null, errorKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* One NDJSON line per failed record, in the shape real AWS writes (probed):
|
||||
* timestamps, code, message, base64 rawData, and the dataCatalogTable block.
|
||||
* Deviations: both timestamps are the delivery time (Floci does not track
|
||||
* per-record arrival), and AWS's sequenceNumber/subSequenceNumber members
|
||||
* are omitted (DirectPut records have no sequence in Floci).
|
||||
*/
|
||||
private String writeErrorOutput(DeliveryStreamDescription stream, S3Destination s3, String bucket,
|
||||
List<FailedRecord> failures, Instant deliveryTime,
|
||||
SchemaConfiguration schemaConfig) {
|
||||
String errorKey = S3ObjectKeyResolver.resolveErrorKey(s3, stream.getDeliveryStreamName(),
|
||||
stream.getVersionId(), deliveryTime, ERROR_OUTPUT_TYPE);
|
||||
Map<String, Object> catalogTable = new LinkedHashMap<>();
|
||||
// Omitted members fall back to the stream's own account and region, recorded
|
||||
// when it was created, rather than to whatever is ambient at delivery time.
|
||||
catalogTable.put("catalogId", schemaConfig.getCatalogId() != null
|
||||
? schemaConfig.getCatalogId()
|
||||
: stream.getAccountId() != null ? stream.getAccountId() : regionResolver.getAccountId());
|
||||
catalogTable.put("databaseName", schemaConfig.getDatabaseName());
|
||||
catalogTable.put("tableName", schemaConfig.getTableName());
|
||||
catalogTable.put("region", schemaConfig.getRegion() != null
|
||||
? schemaConfig.getRegion()
|
||||
: AwsArnUtils.regionOrDefault(stream.getDeliveryStreamARN(),
|
||||
regionResolver.getDefaultRegion()));
|
||||
catalogTable.put("versionId", schemaConfig.getVersionId() != null
|
||||
? schemaConfig.getVersionId() : "LATEST");
|
||||
catalogTable.put("roleArn", schemaConfig.getRoleArn());
|
||||
|
||||
ByteArrayOutputStream body = new ByteArrayOutputStream(initialSize(failures.size(), 256));
|
||||
for (FailedRecord failure : failures) {
|
||||
Map<String, Object> line = new LinkedHashMap<>();
|
||||
line.put("attemptsMade", 1);
|
||||
line.put("arrivalTimestamp", deliveryTime.toEpochMilli());
|
||||
line.put("lastErrorCode", failure.errorCode());
|
||||
line.put("lastErrorMessage", failure.errorMessage());
|
||||
line.put("attemptEndingTimestamp", deliveryTime.toEpochMilli());
|
||||
line.put("rawData", Base64.getEncoder().encodeToString(failure.data()));
|
||||
line.put("dataCatalogTable", catalogTable);
|
||||
try {
|
||||
body.write(mapper.writeValueAsBytes(line));
|
||||
body.write('\n');
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalServerException",
|
||||
"Failed to serialize a Firehose error-output record: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
s3Service.putObject(bucket, errorKey, body.toByteArray(), CONTENT_TYPE, Map.of());
|
||||
return errorKey;
|
||||
}
|
||||
|
||||
private void ensureStagingBucket() {
|
||||
try {
|
||||
s3Service.createBucket(stagingBucket, regionResolver.getDefaultRegion());
|
||||
} catch (AwsException e) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())
|
||||
&& !"BucketAlreadyExists".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Escapes a value for embedding inside a DuckDB single-quoted SQL literal. */
|
||||
/**
|
||||
* A sizing hint only, so it is capped: a batch of many small records would
|
||||
* otherwise ask for a multi-gigabyte array, or overflow the product to a
|
||||
* negative int and fail before any record is written.
|
||||
*/
|
||||
private static int initialSize(int count, int perEntry) {
|
||||
return (int) Math.min((long) count * perEntry, MAX_BUFFER_HINT);
|
||||
}
|
||||
|
||||
private static String escapeSqlLiteral(String raw) {
|
||||
return raw.replace("'", "''");
|
||||
}
|
||||
|
||||
private void safeDelete(String key) {
|
||||
try {
|
||||
s3Service.deleteObject(stagingBucket, key);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "Staging cleanup failed for s3://{0}/{1}", stagingBucket, key);
|
||||
}
|
||||
}
|
||||
|
||||
// ── column typing and coercion ───────────────────────────────────────────
|
||||
|
||||
private interface KeyResolver {
|
||||
/** The record's fields by lowercased key, empty when case-insensitive matching is off. */
|
||||
Map<String, JsonNode> index(JsonNode record);
|
||||
|
||||
JsonNode find(JsonNode record, Map<String, JsonNode> index, String column);
|
||||
}
|
||||
|
||||
private record FailedRecord(byte[] data, String errorCode, String errorMessage) {}
|
||||
|
||||
private static final class RecordConversionException extends RuntimeException {
|
||||
final String errorCode;
|
||||
|
||||
RecordConversionException(String errorCode, String message) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class UnsupportedSchemaException extends RuntimeException {
|
||||
UnsupportedSchemaException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
enum ColumnKind { BOOLEAN, INTEGRAL, FLOATING, DECIMAL, TEXT, DATE, TIMESTAMP }
|
||||
|
||||
record ColumnSpec(String name, String duckType, ColumnKind kind) {
|
||||
|
||||
/** Primitive Hive types only; complex and binary types return null (unsupported). */
|
||||
static ColumnSpec fromHiveType(String name, String hiveType) {
|
||||
String type = hiveType == null ? "" : hiveType.trim().toLowerCase(Locale.ROOT);
|
||||
Matcher decimal = DECIMAL_TYPE.matcher(type);
|
||||
if (decimal.matches()) {
|
||||
return decimalSpec(name, decimal.group(1), decimal.group(2));
|
||||
}
|
||||
return switch (type) {
|
||||
case "boolean" -> new ColumnSpec(name, "BOOLEAN", ColumnKind.BOOLEAN);
|
||||
case "tinyint" -> new ColumnSpec(name, "TINYINT", ColumnKind.INTEGRAL);
|
||||
case "smallint" -> new ColumnSpec(name, "SMALLINT", ColumnKind.INTEGRAL);
|
||||
case "int", "integer" -> new ColumnSpec(name, "INTEGER", ColumnKind.INTEGRAL);
|
||||
case "bigint" -> new ColumnSpec(name, "BIGINT", ColumnKind.INTEGRAL);
|
||||
case "float", "real" -> new ColumnSpec(name, "FLOAT", ColumnKind.FLOATING);
|
||||
case "double", "double precision" -> new ColumnSpec(name, "DOUBLE", ColumnKind.FLOATING);
|
||||
case "decimal" -> new ColumnSpec(name, "DECIMAL(10,0)", ColumnKind.DECIMAL);
|
||||
case "string" -> new ColumnSpec(name, "VARCHAR", ColumnKind.TEXT);
|
||||
case "date" -> new ColumnSpec(name, "DATE", ColumnKind.DATE);
|
||||
case "timestamp" -> new ColumnSpec(name, "TIMESTAMP", ColumnKind.TIMESTAMP);
|
||||
default -> sizedTextSpec(name, type);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code char(n)} and {@code varchar(n)} map to VARCHAR, but only when the
|
||||
* whole type parses and its length is one Hive accepts. Glue does not check
|
||||
* the type string, so a prefix match would let {@code varchar(foo)} or
|
||||
* {@code char(10)garbage} through as text instead of reporting the schema.
|
||||
*/
|
||||
private static ColumnSpec sizedTextSpec(String name, String type) {
|
||||
Matcher sized = SIZED_TEXT_TYPE.matcher(type);
|
||||
if (!sized.matches() || sized.group(2).length() > 5) {
|
||||
return null;
|
||||
}
|
||||
int length = Integer.parseInt(sized.group(2));
|
||||
int max = "char".equals(sized.group(1)) ? MAX_CHAR_LENGTH : MAX_VARCHAR_LENGTH;
|
||||
if (length < 1 || length > max) {
|
||||
return null;
|
||||
}
|
||||
return new ColumnSpec(name, "VARCHAR", ColumnKind.TEXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* A precision or scale outside what DECIMAL can hold is a property of the
|
||||
* schema, not of any one record, so an out-of-range width is unsupported
|
||||
* rather than left for the COPY to reject as a batch-level failure.
|
||||
*/
|
||||
private static ColumnSpec decimalSpec(String name, String precisionText, String scaleText) {
|
||||
if (precisionText.length() > 2 || scaleText.length() > 2) {
|
||||
return null;
|
||||
}
|
||||
int precision = Integer.parseInt(precisionText);
|
||||
int scale = Integer.parseInt(scaleText);
|
||||
if (precision < 1 || precision > MAX_DECIMAL_PRECISION || scale < 0 || scale > precision) {
|
||||
return null;
|
||||
}
|
||||
return new ColumnSpec(name, "DECIMAL(" + precision + "," + scale + ")", ColumnKind.DECIMAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerces one JSON value to this column's type or reports the record as
|
||||
* MalformedData. The "For input string" cause mirrors real AWS, whose own
|
||||
* failure for a non-numeric string in a double column is "Data does not
|
||||
* match the schema. For input string: \"oops\"", the raw
|
||||
* NumberFormatException message.
|
||||
*/
|
||||
Object coerce(JsonNode value) {
|
||||
try {
|
||||
return switch (kind) {
|
||||
case BOOLEAN -> coerceBoolean(value);
|
||||
case INTEGRAL -> coerceIntegral(value);
|
||||
case FLOATING -> coerceFloating(value);
|
||||
case DECIMAL -> coerceDecimal(value);
|
||||
case TEXT -> value.isValueNode() ? value.asText() : value.toString();
|
||||
case DATE -> coerceDate(value);
|
||||
case TIMESTAMP -> coerceTimestamp(value);
|
||||
};
|
||||
} catch (RecordConversionException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RecordConversionException("DataFormatConversion.MalformedData",
|
||||
"Data does not match the schema. " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Hive {@code float} column is 32-bit, and DuckDB refuses to cast a value
|
||||
* the type cannot hold, which would fail the COPY for the whole batch rather
|
||||
* than this record. A {@code double} column takes the value as it stands.
|
||||
*/
|
||||
private Object coerceFloating(JsonNode value) {
|
||||
double parsed;
|
||||
if (value.isNumber()) {
|
||||
parsed = value.doubleValue();
|
||||
if (!Double.isFinite(parsed)) {
|
||||
// A finite record value past the double range arrives here already
|
||||
// turned to infinity, which would stage as a value the record
|
||||
// never wrote.
|
||||
throw outOfRange(value.decimalValue());
|
||||
}
|
||||
} else {
|
||||
String text = requireScalar(value).trim();
|
||||
parsed = Double.parseDouble(text);
|
||||
if (!Double.isFinite(parsed)) {
|
||||
throw new NumberFormatException("For input string: \"" + text + "\"");
|
||||
}
|
||||
}
|
||||
if ("FLOAT".equals(duckType) && Float.isInfinite((float) parsed)) {
|
||||
throw outOfRange(parsed);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Range-checks integral values here rather than leaving them to DuckDB: a
|
||||
* value the CAST rejects fails the COPY, and with it every record in the
|
||||
* batch, where AWS fails only the record that does not fit the column.
|
||||
*/
|
||||
private Object coerceIntegral(JsonNode value) {
|
||||
BigInteger parsed = value.isIntegralNumber() ? value.bigIntegerValue()
|
||||
: new BigInteger(requireScalar(value).trim());
|
||||
long min;
|
||||
long max;
|
||||
switch (duckType) {
|
||||
case "TINYINT" -> {
|
||||
min = Byte.MIN_VALUE;
|
||||
max = Byte.MAX_VALUE;
|
||||
}
|
||||
case "SMALLINT" -> {
|
||||
min = Short.MIN_VALUE;
|
||||
max = Short.MAX_VALUE;
|
||||
}
|
||||
case "INTEGER" -> {
|
||||
min = Integer.MIN_VALUE;
|
||||
max = Integer.MAX_VALUE;
|
||||
}
|
||||
default -> {
|
||||
min = Long.MIN_VALUE;
|
||||
max = Long.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
if (parsed.compareTo(BigInteger.valueOf(min)) < 0
|
||||
|| parsed.compareTo(BigInteger.valueOf(max)) > 0) {
|
||||
throw outOfRange(parsed);
|
||||
}
|
||||
return parsed.longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rounds to the column's scale the way the DuckDB cast would, and rejects
|
||||
* the record when the result no longer fits the precision, for the same
|
||||
* blast-radius reason as {@link #coerceIntegral(JsonNode)}.
|
||||
*/
|
||||
private Object coerceDecimal(JsonNode value) {
|
||||
BigDecimal parsed = value.isNumber() ? value.decimalValue()
|
||||
: new BigDecimal(requireScalar(value).trim());
|
||||
Matcher bounds = DECIMAL_TYPE.matcher(duckType.toLowerCase(Locale.ROOT));
|
||||
if (!bounds.matches()) {
|
||||
return parsed;
|
||||
}
|
||||
int precision = Integer.parseInt(bounds.group(1));
|
||||
int scale = Integer.parseInt(bounds.group(2));
|
||||
if (parsed.signum() == 0) {
|
||||
// Zero fits every DECIMAL, but "0e1000000000" carries a scale that would
|
||||
// make the digit count below read it as enormous.
|
||||
return BigDecimal.ZERO.setScale(scale);
|
||||
}
|
||||
// Decided from precision and scale before setScale, which would otherwise
|
||||
// write out every digit of an exponent like 1e1000000000 to find that out.
|
||||
// The subtraction is long: a scale near Integer.MIN_VALUE, which "1e2147483647"
|
||||
// carries, would overflow an int back into the range this is guarding.
|
||||
long integerDigits = (long) parsed.precision() - parsed.scale();
|
||||
if (integerDigits > (long) precision - scale) {
|
||||
throw outOfRange(parsed);
|
||||
}
|
||||
if (integerDigits < (long) -scale - 1) {
|
||||
return BigDecimal.ZERO.setScale(scale);
|
||||
}
|
||||
BigDecimal rounded = parsed.setScale(scale, RoundingMode.HALF_UP);
|
||||
if (rounded.precision() > precision) {
|
||||
throw outOfRange(parsed);
|
||||
}
|
||||
return rounded;
|
||||
}
|
||||
|
||||
private RecordConversionException outOfRange(Number value) {
|
||||
return new RecordConversionException("DataFormatConversion.MalformedData",
|
||||
"Data does not match the schema. Value " + value + " is out of range for column "
|
||||
+ name + " of type " + duckType + ".");
|
||||
}
|
||||
|
||||
private String requireScalar(JsonNode value) {
|
||||
if (!value.isValueNode()) {
|
||||
throw new RecordConversionException("DataFormatConversion.MalformedData",
|
||||
"Data does not match the schema. Column " + name + " cannot hold a JSON "
|
||||
+ (value.isArray() ? "array." : "object."));
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private Object coerceBoolean(JsonNode value) {
|
||||
if (value.isBoolean()) {
|
||||
return value.booleanValue();
|
||||
}
|
||||
String text = requireScalar(value);
|
||||
if ("true".equalsIgnoreCase(text) || "false".equalsIgnoreCase(text)) {
|
||||
return Boolean.parseBoolean(text);
|
||||
}
|
||||
throw new NumberFormatException("For input string: \"" + text + "\"");
|
||||
}
|
||||
|
||||
private Object coerceDate(JsonNode value) {
|
||||
String text = requireScalar(value);
|
||||
Matcher date = DATE_VALUE.matcher(text);
|
||||
if (!date.matches()) {
|
||||
throw new NumberFormatException("For input string: \"" + text + "\"");
|
||||
}
|
||||
return LocalDate.parse(padded(date.group(1), date.group(2), date.group(3))).toString();
|
||||
}
|
||||
|
||||
private static String padded(String year, String month, String day) {
|
||||
return year + "-" + pad(month) + "-" + pad(day);
|
||||
}
|
||||
|
||||
private static String pad(String field) {
|
||||
return field.length() == 1 ? "0" + field : field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the probed "yyyy-MM-dd HH:mm:ss[.fraction]" shape, ISO 'T'
|
||||
* variants, and epoch numbers, which real AWS also accepts written as
|
||||
* strings (all probed 2026-09-08 against us-west-2).
|
||||
*/
|
||||
private Object coerceTimestamp(JsonNode value) {
|
||||
if (value.isNumber()) {
|
||||
return fromEpoch(value.decimalValue());
|
||||
}
|
||||
String text = requireScalar(value);
|
||||
Matcher iso = ISO_TIMESTAMP.matcher(text);
|
||||
if (iso.matches()) {
|
||||
String normalized = iso.group(1) + " " + iso.group(2);
|
||||
LocalDateTime.parse(normalized.replace(' ', 'T'));
|
||||
return normalized;
|
||||
}
|
||||
Matcher lenient = LENIENT_TIMESTAMP.matcher(text);
|
||||
if (lenient.matches()) {
|
||||
String normalized = padded(lenient.group(1), lenient.group(2), lenient.group(3))
|
||||
+ " " + pad(lenient.group(4)) + ":" + pad(lenient.group(5))
|
||||
+ ":" + pad(lenient.group(6))
|
||||
+ (lenient.group(7) == null ? "" : lenient.group(7));
|
||||
LocalDateTime.parse(normalized.replace(' ', 'T'));
|
||||
return normalized;
|
||||
}
|
||||
try {
|
||||
return fromEpoch(new BigDecimal(text.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new NumberFormatException("For input string: \"" + text + "\"");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Probed against real AWS: an epoch number below 1e12 in absolute value is
|
||||
* read as seconds and one at or above it as milliseconds, so 1518033528 is
|
||||
* February 2018 rather than January 1970, and a fractional value keeps its
|
||||
* sub-second part. A value that overflows the int64 nanoseconds AWS's
|
||||
* writer holds wraps there into an unrelated instant; the instant is kept
|
||||
* here wherever a TIMESTAMP can hold it, and only a value beyond that
|
||||
* fails its record, which docs/services/firehose.md records as a deviation.
|
||||
*/
|
||||
private Object fromEpoch(BigDecimal epoch) {
|
||||
if (epoch.signum() == 0) {
|
||||
// As in coerceDecimal: zero is the epoch whatever exponent wrote it.
|
||||
return EPOCH_TIMESTAMP.format(Instant.EPOCH);
|
||||
}
|
||||
// The digit count settles the range before setScale materializes the value:
|
||||
// an exponent like 1e1000000000 is out of range without writing it out. The
|
||||
// subtraction is long, since "1e2147483647" would overflow it as an int.
|
||||
if ((long) epoch.precision() - epoch.scale() > MAX_TIMESTAMP_DIGITS) {
|
||||
throw outOfRange(epoch);
|
||||
}
|
||||
BigDecimal millis = epoch.abs().compareTo(EPOCH_MILLIS_FLOOR) < 0
|
||||
? epoch.multiply(BigDecimal.valueOf(1000))
|
||||
: epoch;
|
||||
if ((long) millis.precision() - millis.scale() < 0) {
|
||||
// Under a tenth of a millisecond, so it rounds to the epoch. Rounding it
|
||||
// the long way would write out an exponent like 1e-1000000000 in full.
|
||||
return EPOCH_TIMESTAMP.format(Instant.EPOCH);
|
||||
}
|
||||
BigDecimal rounded = millis.setScale(0, RoundingMode.HALF_UP);
|
||||
if (rounded.abs().compareTo(MAX_TIMESTAMP_MILLIS) > 0) {
|
||||
throw outOfRange(epoch);
|
||||
}
|
||||
return EPOCH_TIMESTAMP.format(Instant.ofEpochMilli(rounded.longValueExact()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -100,6 +101,7 @@ public class FirehoseService implements ResourceProvider {
|
||||
// Values are replaced whole, never mutated in place, so a flusher that snapshots one
|
||||
// commits exactly the position that snapshot covered.
|
||||
private final Map<String, Map<String, String>> pendingSourceIterators = new ConcurrentHashMap<>();
|
||||
private final FirehoseParquetConverter parquetConverter;
|
||||
private final Clock clock;
|
||||
private final long tickIntervalSeconds;
|
||||
private final int flushRecordCount;
|
||||
@@ -184,7 +186,8 @@ public class FirehoseService implements ResourceProvider {
|
||||
|
||||
@Inject
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, KinesisService kinesisService,
|
||||
RegionResolver regionResolver, Clock clock, EmulatorConfig config) {
|
||||
RegionResolver regionResolver, Clock clock, EmulatorConfig config,
|
||||
FirehoseParquetConverter parquetConverter) {
|
||||
this.streamStore = storageFactory.create("firehose", "streams.json",
|
||||
new TypeReference<Map<String, DeliveryStreamDescription>>() {});
|
||||
this.sourceIteratorStore = storageFactory.create("firehose", "source-iterators.json",
|
||||
@@ -192,6 +195,7 @@ public class FirehoseService implements ResourceProvider {
|
||||
this.s3Service = s3Service;
|
||||
this.kinesisService = kinesisService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.parquetConverter = parquetConverter;
|
||||
this.clock = clock;
|
||||
this.tickIntervalSeconds = Math.max(1, config.services().firehose().tickIntervalSeconds());
|
||||
this.flushRecordCount = Math.max(0, config.services().firehose().flushRecordCount());
|
||||
@@ -325,7 +329,6 @@ public class FirehoseService implements ResourceProvider {
|
||||
streamPut(streamKey, description);
|
||||
buffers.put(streamKey, Collections.synchronizedList(new ArrayList<>()));
|
||||
LOG.infov("Created Firehose delivery stream: {0}", name);
|
||||
warnIfConversionEnabled(name, s3Config);
|
||||
return arn;
|
||||
}
|
||||
|
||||
@@ -376,26 +379,6 @@ public class FirehoseService implements ResourceProvider {
|
||||
stream.setLastUpdateTimestamp(java.time.Instant.now());
|
||||
streamPut(streamKey, stream);
|
||||
LOG.infov("Updated destination {0} of Firehose delivery stream {1}", destinationId, name);
|
||||
warnIfConversionEnabled(name, stream.s3Destination());
|
||||
}
|
||||
|
||||
/**
|
||||
* Says, where the configuration is set, that conversion will not be applied. Fires
|
||||
* on every create and on every update that leaves conversion enabled, including an
|
||||
* update about something else, so a caller who keeps changing the destination keeps
|
||||
* being told.
|
||||
*
|
||||
* Deliberately not in the flush path: that runs on every buffered delivery and on
|
||||
* every retry after a failed write, so warning there floods the log and needs a
|
||||
* per-stream marker whose lifetime has to track creates and deletes. Create and
|
||||
* update are caller-driven and rare by comparison, and they are the moments a
|
||||
* caller can act on the warning anyway.
|
||||
*/
|
||||
private static void warnIfConversionEnabled(String name, S3Destination s3) {
|
||||
if (s3 != null && s3.isDataFormatConversionEnabled()) {
|
||||
LOG.warnv("Delivery stream {0} enables data format conversion, which Floci does not"
|
||||
+ " apply yet; its records will be delivered unconverted", name);
|
||||
}
|
||||
}
|
||||
|
||||
public void startDeliveryStreamEncryption(String name, String keyType, String keyArn) {
|
||||
@@ -862,9 +845,30 @@ public class FirehoseService implements ResourceProvider {
|
||||
return;
|
||||
}
|
||||
|
||||
// Every store this delivery touches, Glue and S3 included, reads the account
|
||||
// from the request context, and a scheduled flush has none. Without this the
|
||||
// work would run as the default account rather than the stream's owner: the
|
||||
// stream's Glue table would be missed and its objects would land in the wrong
|
||||
// partition. The sidecar follows the same context, so both sides stay together.
|
||||
RequestScopes.runAs(stream.getAccountId(),
|
||||
() -> deliverBuffer(streamName, stream, toFlush, checkpoint));
|
||||
}
|
||||
|
||||
private void deliverBuffer(String streamName, DeliveryStreamDescription stream,
|
||||
List<byte[]> toFlush, Map<String, String> checkpoint) {
|
||||
try {
|
||||
String bucket = resolveBucket(stream);
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
if (s3 != null && s3.isDataFormatConversionEnabled()) {
|
||||
ensureBucket(bucket);
|
||||
FirehoseParquetConverter.Outcome outcome =
|
||||
parquetConverter.deliver(stream, bucket, toFlush, clock.instant());
|
||||
LOG.infov("Converted {0} records ({1} failed) from stream {2} to s3://{3}/{4}",
|
||||
outcome.convertedRecords(), outcome.failedRecords(), streamName, bucket,
|
||||
outcome.dataKey() != null ? outcome.dataKey() : outcome.errorKey());
|
||||
commitSourceIterators(streamName, checkpoint);
|
||||
return;
|
||||
}
|
||||
FirehoseCompression compression =
|
||||
FirehoseCompression.forDelivery(s3 == null ? null : s3.getCompressionFormat());
|
||||
String key = S3ObjectKeyResolver.resolveKey(s3, stream.getDeliveryStreamName(),
|
||||
|
||||
+38
-3
@@ -48,11 +48,46 @@ final class S3ObjectKeyResolver {
|
||||
|
||||
static String resolveKey(S3Destination s3, String streamName, String versionId,
|
||||
Instant deliveryTime, FirehoseCompression compression) {
|
||||
return resolveKey(s3, streamName, versionId, deliveryTime, compression.extension());
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant for format-converting deliveries, whose extension comes from the
|
||||
* output format (.parquet) rather than the compression format; an explicit
|
||||
* {@code FileExtension} still replaces it, like on plain deliveries.
|
||||
*/
|
||||
static String resolveKey(S3Destination s3, String streamName, String versionId,
|
||||
Instant deliveryTime, String defaultExtension) {
|
||||
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);
|
||||
+ fileExtension(s3, defaultExtension);
|
||||
}
|
||||
|
||||
/**
|
||||
* Error-output object key: {@code <evaluated ErrorOutputPrefix><suffix>} with no
|
||||
* file extension (verified against real AWS for format-conversion failures). The
|
||||
* prefix supports the same expressions as {@code Prefix} plus
|
||||
* {@code !{firehose:error-output-type}}, and unlike the data prefix it gets no
|
||||
* default {@code yyyy/MM/dd/HH/} appended when absent or expressionless.
|
||||
*/
|
||||
static String resolveErrorKey(S3Destination s3, String streamName, String versionId,
|
||||
Instant deliveryTime, String errorOutputType) {
|
||||
ZonedDateTime time = ZonedDateTime.ofInstant(
|
||||
deliveryTime, resolveZone(s3 == null ? null : s3.getCustomTimeZone()));
|
||||
String prefix = s3 == null ? null : s3.getErrorOutputPrefix();
|
||||
StringBuilder out = new StringBuilder();
|
||||
Matcher matcher = EXPRESSION.matcher(prefix == null ? "" : prefix);
|
||||
while (matcher.find()) {
|
||||
String replacement = "firehose".equals(matcher.group("namespace"))
|
||||
&& "error-output-type".equals(matcher.group("argument"))
|
||||
? errorOutputType
|
||||
: evaluateExpression(matcher, time);
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
return out + objectNameSuffix(streamName, versionId, time);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,9 +96,9 @@ final class S3ObjectKeyResolver {
|
||||
* 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) {
|
||||
private static String fileExtension(S3Destination s3, String defaultExtension) {
|
||||
String fileExtension = s3 == null ? null : s3.getFileExtension();
|
||||
return fileExtension == null || fileExtension.isEmpty() ? compression.extension() : fileExtension;
|
||||
return fileExtension == null || fileExtension.isEmpty() ? defaultExtension : fileExtension;
|
||||
}
|
||||
|
||||
static String evaluatePrefix(String prefix, ZonedDateTime time) {
|
||||
|
||||
@@ -401,6 +401,7 @@ floci:
|
||||
enabled: true
|
||||
tick-interval-seconds: 10
|
||||
flush-record-count: 0
|
||||
staging-bucket: floci-firehose-staging
|
||||
kms:
|
||||
enabled: true
|
||||
cognito:
|
||||
|
||||
+42
-2
@@ -58,6 +58,8 @@ class FirehoseDataFormatConversionTest {
|
||||
private static final String DESTINATION_ID = "destinationId-000000000001";
|
||||
|
||||
private FirehoseService service;
|
||||
private FirehoseParquetConverter parquetConverter;
|
||||
private S3Service s3Service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -78,8 +80,11 @@ class FirehoseDataFormatConversionTest {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
service = new FirehoseService(storageFactory, Mockito.mock(S3Service.class),
|
||||
Mockito.mock(KinesisService.class), regionResolver, new MutableClock(), config);
|
||||
parquetConverter = Mockito.mock(FirehoseParquetConverter.class);
|
||||
s3Service = Mockito.mock(S3Service.class);
|
||||
service = new FirehoseService(storageFactory, s3Service,
|
||||
Mockito.mock(KinesisService.class), regionResolver, new MutableClock(), config,
|
||||
parquetConverter);
|
||||
}
|
||||
|
||||
private static SchemaConfiguration schema() {
|
||||
@@ -511,6 +516,41 @@ class FirehoseDataFormatConversionTest {
|
||||
.getSchemaConfiguration().getDatabaseName());
|
||||
}
|
||||
|
||||
/** Conversion-enabled flushes route through the converter instead of the raw concat path. */
|
||||
@Test
|
||||
void flushDelegatesConversionEnabledStreamsToTheConverter() {
|
||||
Mockito.when(parquetConverter.deliver(any(), anyString(), any(), any()))
|
||||
.thenReturn(new FirehoseParquetConverter.Outcome(1, 0, "data/key.parquet", null));
|
||||
service.createDeliveryStream("stream", destination(s3 -> {}));
|
||||
service.putRecord("stream", record("{\"ticker\": \"AAA\"}"));
|
||||
|
||||
service.flush("stream");
|
||||
|
||||
Mockito.verify(parquetConverter).deliver(any(), Mockito.eq("results"), any(), any());
|
||||
Mockito.verify(s3Service, Mockito.never()).putObject(anyString(), anyString(),
|
||||
any(byte[].class), anyString(), Mockito.anyMap(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void flushKeepsTheRawPathForDisabledConversion() {
|
||||
service.createDeliveryStream("stream", destination(s3 ->
|
||||
s3.getDataFormatConversionConfiguration().setEnabled(false)));
|
||||
service.putRecord("stream", record("{\"ticker\": \"AAA\"}"));
|
||||
|
||||
service.flush("stream");
|
||||
|
||||
Mockito.verify(parquetConverter, Mockito.never()).deliver(any(), anyString(), any(), any());
|
||||
Mockito.verify(s3Service).putObject(Mockito.eq("results"), anyString(),
|
||||
any(byte[].class), anyString(), Mockito.anyMap(), any());
|
||||
}
|
||||
|
||||
private static io.github.hectorvent.floci.services.firehose.model.Record record(String json) {
|
||||
io.github.hectorvent.floci.services.firehose.model.Record record =
|
||||
new io.github.hectorvent.floci.services.firehose.model.Record();
|
||||
record.setData(json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return record;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOntoAStreamWithoutADestinationValidatesTheUpdateItself() {
|
||||
service.createDeliveryStream("bare", (S3Destination) null, List.of());
|
||||
|
||||
+802
@@ -0,0 +1,802 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.DataFormatConversionConfiguration;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Deserializer;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.InputFormatConfiguration;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OpenXJsonSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OutputFormatConfiguration;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ParquetSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.SchemaConfiguration;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Serializer;
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.services.glue.model.Column;
|
||||
import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
|
||||
import io.github.hectorvent.floci.services.glue.model.Table;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
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.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.ArgumentMatchers.startsWith;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The error codes, message shapes, and the per-record routing asserted here
|
||||
* follow the delivery behavior probed against real AWS (see okinaka/floci
|
||||
* discussion 118): parse failures and schema mismatches fail individually
|
||||
* while the rest of the batch converts; batch-level failure codes are Floci's
|
||||
* own, documented in docs/services/firehose.md.
|
||||
*/
|
||||
class FirehoseParquetConverterTest {
|
||||
|
||||
private static final String BUCKET = "results";
|
||||
private static final String STAGING = "floci-firehose-staging";
|
||||
private static final Instant DELIVERY_TIME = Instant.parse("2026-01-01T00:00:00Z");
|
||||
private static final byte[] STAGED_PARQUET = "PAR1staged".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private GlueService glueService;
|
||||
private FlociDuckClient duckClient;
|
||||
private S3Service s3Service;
|
||||
private FirehoseParquetConverter converter;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
glueService = mock(GlueService.class);
|
||||
duckClient = mock(FlociDuckClient.class);
|
||||
s3Service = mock(S3Service.class);
|
||||
converter = new FirehoseParquetConverter(glueService, duckClient, s3Service, mapper,
|
||||
new RegionResolver("us-east-1", "000000000000"), STAGING);
|
||||
// The staged Parquet the sidecar would have written, read back at delivery.
|
||||
when(s3Service.getObject(eq(STAGING), anyString())).thenReturn(
|
||||
new S3Object(STAGING, "staged.parquet", STAGED_PARQUET, "application/octet-stream"));
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(
|
||||
new Column("ticker", "string"),
|
||||
new Column("price", "double"),
|
||||
new Column("qty", "int"),
|
||||
new Column("active", "boolean"),
|
||||
new Column("ts", "timestamp")));
|
||||
}
|
||||
|
||||
private static Table table(Column... columns) {
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setColumns(java.util.Arrays.asList(columns));
|
||||
Table table = new Table();
|
||||
table.setStorageDescriptor(descriptor);
|
||||
return table;
|
||||
}
|
||||
|
||||
private static DeliveryStreamDescription stream() {
|
||||
SchemaConfiguration schema = new SchemaConfiguration();
|
||||
schema.setRoleArn("arn:aws:iam::000000000000:role/firehose-role");
|
||||
schema.setDatabaseName("db");
|
||||
schema.setTableName("events");
|
||||
Deserializer deserializer = new Deserializer();
|
||||
deserializer.setOpenXJsonSerDe(new OpenXJsonSerDe());
|
||||
InputFormatConfiguration input = new InputFormatConfiguration();
|
||||
input.setDeserializer(deserializer);
|
||||
Serializer serializer = new Serializer();
|
||||
serializer.setParquetSerDe(new ParquetSerDe());
|
||||
OutputFormatConfiguration output = new OutputFormatConfiguration();
|
||||
output.setSerializer(serializer);
|
||||
DataFormatConversionConfiguration conversion = new DataFormatConversionConfiguration();
|
||||
conversion.setEnabled(true);
|
||||
conversion.setSchemaConfiguration(schema);
|
||||
conversion.setInputFormatConfiguration(input);
|
||||
conversion.setOutputFormatConfiguration(output);
|
||||
|
||||
S3Destination s3 = new S3Destination();
|
||||
s3.setBucketArn("arn:aws:s3:::" + BUCKET);
|
||||
s3.setPrefix("data/");
|
||||
s3.setErrorOutputPrefix("errors/!{firehose:error-output-type}/");
|
||||
s3.setCompressionFormat("UNCOMPRESSED");
|
||||
s3.setDataFormatConversionConfiguration(conversion);
|
||||
return new DeliveryStreamDescription("stream", "arn:aws:firehose:::stream", s3);
|
||||
}
|
||||
|
||||
private static byte[] record(String json) {
|
||||
return (json + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String stagedNdjson() {
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq(STAGING), startsWith("firehose-staging/stream/"),
|
||||
body.capture(), eq("application/x-ndjson"), anyMap());
|
||||
return new String(body.getValue(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** The one error object among the destination writes, which now also carry the Parquet. */
|
||||
private List<JsonNode> errorLines() throws Exception {
|
||||
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service, org.mockito.Mockito.atLeastOnce()).putObject(eq(BUCKET), key.capture(),
|
||||
body.capture(), eq("application/octet-stream"), anyMap());
|
||||
|
||||
List<Integer> errorWrites = new ArrayList<>();
|
||||
for (int i = 0; i < key.getAllValues().size(); i++) {
|
||||
if (key.getAllValues().get(i).startsWith("errors/format-conversion-failed/")) {
|
||||
errorWrites.add(i);
|
||||
}
|
||||
}
|
||||
assertEquals(1, errorWrites.size(), "error writes were " + key.getAllValues());
|
||||
|
||||
List<JsonNode> lines = new ArrayList<>();
|
||||
String object = new String(body.getAllValues().get(errorWrites.get(0)), StandardCharsets.UTF_8);
|
||||
for (String line : object.strip().split("\n")) {
|
||||
lines.add(mapper.readTree(line));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertsValidRecordsAndNormalizesValuesForDuck() {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\", \"price\": 1.5, \"qty\": 10, \"active\": true,"
|
||||
+ " \"ts\": \"2026-09-07 12:00:00\"}"),
|
||||
record("{\"ticker\": \"MISSING_FIELDS\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(2, outcome.convertedRecords());
|
||||
assertEquals(0, outcome.failedRecords());
|
||||
assertTrue(outcome.dataKey().startsWith("data/2026/01/01/00/stream-1-2026-01-01-00-00-00-"));
|
||||
assertTrue(outcome.dataKey().endsWith(".parquet"));
|
||||
assertNull(outcome.errorKey());
|
||||
|
||||
String ndjson = stagedNdjson();
|
||||
assertTrue(ndjson.contains("{\"ticker\":\"AAA\",\"price\":1.5,\"qty\":10,\"active\":true,"
|
||||
+ "\"ts\":\"2026-09-07 12:00:00\"}"), "staged rows were: " + ndjson);
|
||||
assertTrue(ndjson.contains("{\"ticker\":\"MISSING_FIELDS\",\"price\":null,\"qty\":null,"
|
||||
+ "\"active\":null,\"ts\":null}"), "staged rows were: " + ndjson);
|
||||
|
||||
ArgumentCaptor<String> setupSql = ArgumentCaptor.forClass(String.class);
|
||||
// No output path: the sidecar's CSV export would be a second failure point
|
||||
// after the Parquet object is already written.
|
||||
verify(duckClient).execute(eq("SELECT 1 AS ok"), setupSql.capture(), isNull(), any());
|
||||
assertTrue(setupSql.getValue().contains(
|
||||
"columns={'ticker': 'VARCHAR', 'price': 'DOUBLE', 'qty': 'INTEGER',"
|
||||
+ " 'active': 'BOOLEAN', 'ts': 'TIMESTAMP'}"),
|
||||
"setup sql was: " + setupSql.getValue());
|
||||
assertTrue(setupSql.getValue().contains("TO 's3://" + STAGING + "/firehose-staging/stream/"),
|
||||
"setup sql was: " + setupSql.getValue());
|
||||
assertTrue(setupSql.getValue().contains(".parquet' (FORMAT PARQUET, COMPRESSION SNAPPY)"),
|
||||
"setup sql was: " + setupSql.getValue());
|
||||
|
||||
// The destination key is written once, and with a Put so its notification
|
||||
// matches the unconverted delivery path.
|
||||
ArgumentCaptor<byte[]> delivered = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq(BUCKET), eq(outcome.dataKey()), delivered.capture(),
|
||||
eq("application/octet-stream"), anyMap());
|
||||
assertEquals("PAR1staged", new String(delivered.getValue(), StandardCharsets.UTF_8));
|
||||
verify(s3Service).deleteObject(eq(STAGING), endsWithSuffix(".ndjson"));
|
||||
verify(s3Service).deleteObject(eq(STAGING), endsWithSuffix(".parquet"));
|
||||
}
|
||||
|
||||
private static String endsWithSuffix(String suffix) {
|
||||
return org.mockito.ArgumentMatchers.argThat(key -> key != null && key.endsWith(suffix));
|
||||
}
|
||||
|
||||
@Test
|
||||
void schemaMismatchAndUnparseableRecordsFailIndividually() throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\", \"price\": 1.5, \"qty\": 10, \"active\": true,"
|
||||
+ " \"ts\": \"2026-09-07 12:00:00\"}"),
|
||||
record("{\"ticker\": \"BAD\", \"price\": \"oops\"}"),
|
||||
"this is not json at all\n".getBytes(StandardCharsets.UTF_8)), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(2, outcome.failedRecords());
|
||||
assertNotNull(outcome.dataKey());
|
||||
|
||||
List<JsonNode> lines = errorLines();
|
||||
assertEquals(2, lines.size());
|
||||
JsonNode mismatch = lines.get(0);
|
||||
assertEquals("DataFormatConversion.MalformedData", mismatch.get("lastErrorCode").asText());
|
||||
assertEquals("Data does not match the schema. For input string: \"oops\"",
|
||||
mismatch.get("lastErrorMessage").asText());
|
||||
assertEquals(1, mismatch.get("attemptsMade").asInt());
|
||||
assertEquals(DELIVERY_TIME.toEpochMilli(), mismatch.get("arrivalTimestamp").asLong());
|
||||
assertEquals("{\"ticker\": \"BAD\", \"price\": \"oops\"}\n",
|
||||
new String(Base64.getDecoder().decode(mismatch.get("rawData").asText()),
|
||||
StandardCharsets.UTF_8));
|
||||
assertEquals("000000000000", mismatch.get("dataCatalogTable").get("catalogId").asText());
|
||||
assertEquals("db", mismatch.get("dataCatalogTable").get("databaseName").asText());
|
||||
assertEquals("LATEST", mismatch.get("dataCatalogTable").get("versionId").asText());
|
||||
|
||||
JsonNode unparseable = lines.get(1);
|
||||
assertEquals("DataFormatConversion.ParseError", unparseable.get("lastErrorCode").asText());
|
||||
assertTrue(unparseable.get("lastErrorMessage").asText().startsWith("Encountered malformed JSON."),
|
||||
"message was: " + unparseable.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "\n"})
|
||||
void emptyRecordsFailAsParseErrorRatherThanMalformedData(String content) throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(content.getBytes(StandardCharsets.UTF_8)), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.ParseError", errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trailingContentAfterTheJsonObjectFailsTheRecordAsParseError() throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\"}"),
|
||||
record("{\"ticker\": \"BAD\"} and then some")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.ParseError", errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
// Values DuckDB's CAST would reject must fail their own record, not the COPY:
|
||||
// a batch-wide InternalError would lose the records that do fit the column.
|
||||
@Test
|
||||
void integralValuesOutsideTheColumnWidthFailOnlyTheirOwnRecord() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("qty", "tinyint")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"qty\": 127}"),
|
||||
record("{\"qty\": 128}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertTrue(stagedNdjson().contains("{\"qty\":127}"), "staged rows were: " + stagedNdjson());
|
||||
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.MalformedData", line.get("lastErrorCode").asText());
|
||||
assertEquals("Data does not match the schema. Value 128 is out of range for column qty"
|
||||
+ " of type TINYINT.", line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decimalValuesRoundToScaleAndFailOnlyWhenThePrecisionOverflows() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("amount", "decimal(4,2)")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"amount\": 12.345}"),
|
||||
record("{\"amount\": 12345.67}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertTrue(stagedNdjson().contains("{\"amount\":12.35}"), "staged rows were: " + stagedNdjson());
|
||||
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.MalformedData", line.get("lastErrorCode").asText());
|
||||
assertEquals("Data does not match the schema. Value 12345.67 is out of range for column amount"
|
||||
+ " of type DECIMAL(4,2).", line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void epochMillisBeyondTheTimestampRangeFailOnlyTheirOwnRecord() throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\", \"ts\": 1757246400000}"),
|
||||
record("{\"ticker\": \"BAD\", \"ts\": 18446744073709551616}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"2025-09-07 12:00:00.000\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.MalformedData", line.get("lastErrorCode").asText());
|
||||
assertEquals("Data does not match the schema. Value 18446744073709551616 is out of range"
|
||||
+ " for column ts of type TIMESTAMP.", line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorMetadataFallsBackToTheStreamsOwnAccountAndRegion() throws Exception {
|
||||
DeliveryStreamDescription stream = new DeliveryStreamDescription("stream",
|
||||
"arn:aws:firehose:eu-west-1:111122223333:deliverystream/stream",
|
||||
stream().s3Destination());
|
||||
stream.setAccountId("111122223333");
|
||||
|
||||
converter.deliver(stream, BUCKET, List.of(record("not json")), DELIVERY_TIME);
|
||||
|
||||
JsonNode catalogTable = errorLines().get(0).get("dataCatalogTable");
|
||||
assertEquals("111122223333", catalogTable.get("catalogId").asText());
|
||||
assertEquals("eu-west-1", catalogTable.get("region").asText());
|
||||
}
|
||||
|
||||
// Probed against real AWS (us-west-2, 2026-09-08): an epoch number below 1e12
|
||||
// is seconds and one at or above it is milliseconds, in both the numeric and
|
||||
// the string spelling, and a fractional value keeps its sub-second part.
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"1518033528, 2018-02-07 19:58:48.000",
|
||||
"1518033528123, 2018-02-07 19:58:48.123",
|
||||
"999999999999, 33658-09-27 01:46:39.000",
|
||||
"1000000000000, 2001-09-09 01:46:40.000",
|
||||
"1518033528.123, 2018-02-07 19:58:48.123",
|
||||
"0, 1970-01-01 00:00:00.000",
|
||||
"-1000, 1969-12-31 23:43:20.000",
|
||||
})
|
||||
void epochNumbersFollowTheProbedSecondsOrMillisRule(String epoch, String expected) {
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\", \"ts\": " + epoch + "}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"" + expected + "\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"1518033528, 2018-02-07 19:58:48.000",
|
||||
"1518033528123, 2018-02-07 19:58:48.123",
|
||||
})
|
||||
void epochNumbersAreAlsoAcceptedAsStrings(String epoch, String expected) {
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\", \"ts\": \"" + epoch + "\"}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"" + expected + "\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void columnNamesOutsideSqlIdentifiersAreConvertedAndEscaped() {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(
|
||||
new Column("event-id", "string"),
|
||||
new Column("it's odd", "string")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"event-id\": \"E1\", \"it's odd\": \"yes\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertTrue(stagedNdjson().contains("{\"event-id\":\"E1\",\"it's odd\":\"yes\"}"),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
|
||||
ArgumentCaptor<String> setupSql = ArgumentCaptor.forClass(String.class);
|
||||
verify(duckClient).execute(anyString(), setupSql.capture(), isNull(), any());
|
||||
assertTrue(setupSql.getValue().contains("columns={'event-id': 'VARCHAR', 'it''s odd': 'VARCHAR'}"),
|
||||
"setup sql was: " + setupSql.getValue());
|
||||
}
|
||||
|
||||
// The range check accepts it, so the formatter must not reject the year's sign.
|
||||
// Probed against real AWS: a space-separated timestamp is read leniently, down to
|
||||
// one-digit hours, while the 'T' form stays strict ISO and rejects a short month.
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"'2026-09-07 12:00:02', '2026-09-07 12:00:02'",
|
||||
"'2026-9-7 12:00:02', '2026-09-07 12:00:02'",
|
||||
"'2026-9-07 12:00:02', '2026-09-07 12:00:02'",
|
||||
"'2026-09-07 1:2:3', '2026-09-07 01:02:03'",
|
||||
"'2026-9-7 12:00:02.5', '2026-09-07 12:00:02.5'",
|
||||
"'2018-02-07T20:38:48Z', '2018-02-07 20:38:48'",
|
||||
})
|
||||
void spaceSeparatedTimestampsAreReadLeniently(String written, String staged) {
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\", \"ts\": \"" + written + "\"}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"" + staged + "\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIsoTimestampWithAShortMonthFailsItsRecord() throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\", \"ts\": \"2026-9-7T12:00:02Z\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.MalformedData",
|
||||
errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"'2026-09-07', '2026-09-07'", "'2026-9-7', '2026-09-07'", "'2026-9-07', '2026-09-07'"})
|
||||
void dateColumnsAreReadLenientlyToo(String written, String staged) {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("d", "date")));
|
||||
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"d\": \"" + written + "\"}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"d\":\"" + staged + "\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void epochsBeforeYearZeroKeepTheirSign() {
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\", \"ts\": -62200000000}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"-0002-12-17 14:13:20.000\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonDecimalsKeepTheirDigitsForDecimalColumns() {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("amount", "decimal(22,2)")));
|
||||
|
||||
converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"amount\": 12345678901234567890.12}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("{\"amount\":12345678901234567890.12}"),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
// A short record can name an enormous value. The range has to be settled from the
|
||||
// digit count, or materializing it to find out exhausts the heap.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"decimal(22,2)", "timestamp"})
|
||||
void hugeExponentsFailTheirRecordWithoutBeingMaterialized(String hiveType) throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("value", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"value\": \"1e1000000000\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.MalformedData",
|
||||
errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
// A scale near Integer.MIN_VALUE overflows the digit count if it is taken as an int,
|
||||
// which would fold an enormous value back into the range the guard is checking.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"decimal(22,2)", "timestamp"})
|
||||
void exponentsThatOverflowTheDigitCountStillFailTheirRecord(String hiveType) throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("value", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"value\": \"1e2147483647\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.MalformedData",
|
||||
errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
// Rounding these the long way would write the exponent out in full.
|
||||
@Test
|
||||
void exponentsTooSmallToSurviveRoundingBecomeZeroWithoutBeingMaterialized() {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(
|
||||
new Column("amount", "decimal(22,2)"),
|
||||
new Column("ts", "timestamp")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"amount\": \"1e-1000000000\", \"ts\": \"1e-1000000000\"}")),
|
||||
DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertTrue(stagedNdjson().contains("\"amount\":0.00"), "staged rows were: " + stagedNdjson());
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"1970-01-01 00:00:00.000\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
// Zero fits every column, whatever exponent the record used to write it.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"0e1000000000", "0e-1000000000", "0", "0.0"})
|
||||
void exponentEncodedZeroIsAcceptedEverywhere(String written) {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(
|
||||
new Column("amount", "decimal(22,2)"),
|
||||
new Column("ts", "timestamp")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"amount\": \"" + written + "\", \"ts\": \"" + written + "\"}")),
|
||||
DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertTrue(stagedNdjson().contains("\"amount\":0.00"), "staged rows were: " + stagedNdjson());
|
||||
assertTrue(stagedNdjson().contains("\"ts\":\"1970-01-01 00:00:00.000\""),
|
||||
"staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableStagedParquetFailsTheBatchBeforeAnyDestinationWrite() throws Exception {
|
||||
when(s3Service.getObject(eq(STAGING), anyString()))
|
||||
.thenThrow(new RuntimeException("staged object is gone"));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\"}"),
|
||||
record("not json")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(2, outcome.failedRecords());
|
||||
assertNull(outcome.dataKey());
|
||||
List<JsonNode> lines = errorLines();
|
||||
assertEquals(2, lines.size());
|
||||
assertTrue(lines.stream().allMatch(line ->
|
||||
"DataFormatConversion.InternalError".equals(line.get("lastErrorCode").asText())),
|
||||
"error lines were: " + lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSidecarRunsAsTheAccountTheRowsWereStagedAs() {
|
||||
DeliveryStreamDescription stream = stream();
|
||||
stream.setAccountId("111122223333");
|
||||
|
||||
converter.deliver(stream, BUCKET, List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
// What routes the write is the account S3Service resolved, not the one
|
||||
// recorded on the stream: the sidecar must read back the partition the
|
||||
// staged rows landed in. Outside a request both are the default account.
|
||||
verify(duckClient).execute(anyString(), anyString(), isNull(), eq("000000000000"));
|
||||
}
|
||||
|
||||
// The two writes are not coordinated, so their order decides what a failure of
|
||||
// the second one leaves behind. Writing the error output first means a failure
|
||||
// delivers nothing at all, which a Kinesis-backed stream can re-read, instead of
|
||||
// leaving the valid rows delivered and the failed records gone with the buffer.
|
||||
@Test
|
||||
void aFailedErrorOutputWriteLeavesNothingDelivered() {
|
||||
doThrow(new RuntimeException("s3 unavailable")).when(s3Service)
|
||||
.putObject(eq(BUCKET), anyString(), any(), anyString(), anyMap());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\"}"),
|
||||
record("not json")), DELIVERY_TIME));
|
||||
|
||||
verify(s3Service, never()).putObject(eq(BUCKET), endsWithSuffix(".parquet"), any(),
|
||||
anyString(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSidecarFailureAfterPerRecordErrorsWritesOneErrorObject() throws Exception {
|
||||
doThrow(new RuntimeException("floci-duck is unreachable")).when(duckClient)
|
||||
.execute(anyString(), anyString(), isNull(), any());
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ticker\": \"AAA\"}"),
|
||||
record("not json")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(2, outcome.failedRecords());
|
||||
assertNull(outcome.dataKey());
|
||||
|
||||
// The conversion is settled before anything reaches the destination, so the
|
||||
// per-record failures never became an object that a batch failure must replace.
|
||||
List<JsonNode> lines = errorLines();
|
||||
assertEquals(2, lines.size());
|
||||
assertTrue(lines.stream().allMatch(line ->
|
||||
"DataFormatConversion.InternalError".equals(line.get("lastErrorCode").asText())),
|
||||
"error lines were: " + lines);
|
||||
verify(s3Service, never()).putObject(eq(BUCKET), endsWithSuffix(".parquet"), any(),
|
||||
anyString(), anyMap());
|
||||
}
|
||||
|
||||
// The COPY may have produced the object even when the call reports failure, and
|
||||
// the caller never learns its key, so cleanup has to happen where it is known.
|
||||
@Test
|
||||
void aFailedConversionRemovesTheStagedParquet() {
|
||||
doThrow(new RuntimeException("floci-duck is unreachable")).when(duckClient)
|
||||
.execute(anyString(), anyString(), isNull(), any());
|
||||
|
||||
converter.deliver(stream(), BUCKET, List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
verify(s3Service).deleteObject(eq(STAGING), endsWithSuffix(".parquet"));
|
||||
verify(s3Service).deleteObject(eq(STAGING), endsWithSuffix(".ndjson"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingGlueTableFailsTheWholeBatchWithoutCallingDuck() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenThrow(
|
||||
new AwsException("EntityNotFoundException", "Table not found: db.events", 400));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
verify(duckClient, never()).execute(anyString(), anyString(), isNull(), any());
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.EntityNotFoundException", line.get("lastErrorCode").asText());
|
||||
assertEquals("Table not found: db.events", line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedColumnTypeFailsTheWholeBatch() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(
|
||||
new Column("ticker", "string"), new Column("tags", "array<string>")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.UnsupportedSchema", line.get("lastErrorCode").asText());
|
||||
assertTrue(line.get("lastErrorMessage").asText().contains("array<string>"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"char(10)", "varchar(255)", "varchar(65535)"})
|
||||
void sizedTextTypesConvertAsVarchar(String hiveType) {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("note", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"note\": \"hello\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertTrue(stagedNdjson().contains("{\"note\":\"hello\"}"), "staged rows were: " + stagedNdjson());
|
||||
}
|
||||
|
||||
// Glue stores the type string without checking it, so a prefix match would take
|
||||
// these for text columns rather than reporting the schema.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"varchar(", "varchar(foo)", "char(10)garbage", "char(0)", "char(256)",
|
||||
"varchar(65536)", "varchar(999999)"})
|
||||
void malformedOrOversizedTextTypesFailTheWholeBatch(String hiveType) throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("note", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"note\": \"hello\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.UnsupportedSchema", line.get("lastErrorCode").asText());
|
||||
assertTrue(line.get("lastErrorMessage").asText().contains(hiveType),
|
||||
"message was: " + line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
// Glue stores the column list without checking its elements, and a crash here
|
||||
// would escape the schema handling and take the batch with it.
|
||||
@Test
|
||||
void aNullColumnEntryFailsTheWholeBatchAsUnsupportedSchema() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("ticker", "string"), null));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
assertEquals("DataFormatConversion.UnsupportedSchema",
|
||||
errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
// Past the double range the value is already infinity by the time it is read, so
|
||||
// staging it would write something the record never carried.
|
||||
@ParameterizedTest
|
||||
@CsvSource({"float, 1e1000", "double, 1e1000", "float, '\"Infinity\"'", "double, '\"NaN\"'"})
|
||||
void nonFiniteFloatingValuesFailTheirOwnRecord(String hiveType, String written) throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("ratio", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ratio\": 1.5}"),
|
||||
record("{\"ratio\": " + written + "}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertEquals("DataFormatConversion.MalformedData",
|
||||
errorLines().get(0).get("lastErrorCode").asText());
|
||||
}
|
||||
|
||||
// DuckDB refuses the cast, which would take the whole batch rather than this record.
|
||||
@Test
|
||||
void valuesTooLargeForAFloatColumnFailOnlyTheirOwnRecord() throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("ratio", "float")));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ratio\": 1.5}"),
|
||||
record("{\"ratio\": 1e100}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertTrue(stagedNdjson().contains("{\"ratio\":1.5}"), "staged rows were: " + stagedNdjson());
|
||||
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.MalformedData", line.get("lastErrorCode").asText());
|
||||
assertTrue(line.get("lastErrorMessage").asText().contains("of type FLOAT"),
|
||||
"message was: " + line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"decimal(39,2)", "decimal(2,3)", "decimal(999999999999,0)"})
|
||||
void decimalWidthsThatCannotBeRepresentedFailTheWholeBatch(String hiveType) throws Exception {
|
||||
when(glueService.getTable("db", "events")).thenReturn(table(new Column("amount", hiveType)));
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"amount\": 1}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.UnsupportedSchema", line.get("lastErrorCode").asText());
|
||||
assertTrue(line.get("lastErrorMessage").asText().contains(hiveType),
|
||||
"message was: " + line.get("lastErrorMessage").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duckFailureRoutesTheWholeBatchToTheErrorOutput() throws Exception {
|
||||
doThrow(new RuntimeException("floci-duck is unreachable")).when(duckClient)
|
||||
.execute(anyString(), anyString(), isNull(), any());
|
||||
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET,
|
||||
List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(0, outcome.convertedRecords());
|
||||
assertEquals(1, outcome.failedRecords());
|
||||
assertNull(outcome.dataKey());
|
||||
JsonNode line = errorLines().get(0);
|
||||
assertEquals("DataFormatConversion.InternalError", line.get("lastErrorCode").asText());
|
||||
assertTrue(line.get("lastErrorMessage").asText().contains("floci-duck is unreachable"));
|
||||
|
||||
verify(s3Service).deleteObject(eq(STAGING), endsWithSuffix(".ndjson"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void openXKeyMappingsAndCaseInsensitivityResolveJsonMembers() {
|
||||
DeliveryStreamDescription stream = stream();
|
||||
OpenXJsonSerDe openX = stream.s3Destination().getDataFormatConversionConfiguration()
|
||||
.getInputFormatConfiguration().getDeserializer().getOpenXJsonSerDe();
|
||||
openX.setColumnToJsonKeyMappings(Map.of("ticker", "sym"));
|
||||
|
||||
// The mapped key is matched case-insensitively too: OpenX lowercases
|
||||
// keys before deserializing, so a mapping cannot depend on the record's case.
|
||||
converter.deliver(stream, BUCKET, List.of(
|
||||
record("{\"SYM\": \"AAA\", \"PRICE\": 1.5}")), DELIVERY_TIME);
|
||||
|
||||
String ndjson = stagedNdjson();
|
||||
assertTrue(ndjson.contains("\"ticker\":\"AAA\""), "staged rows were: " + ndjson);
|
||||
assertTrue(ndjson.contains("\"price\":1.5"), "staged rows were: " + ndjson);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitCaseSensitivityLeavesDifferentlyCasedMembersUnmatched() {
|
||||
DeliveryStreamDescription stream = stream();
|
||||
OpenXJsonSerDe openX = stream.s3Destination().getDataFormatConversionConfiguration()
|
||||
.getInputFormatConfiguration().getDeserializer().getOpenXJsonSerDe();
|
||||
openX.setCaseInsensitive(false);
|
||||
|
||||
converter.deliver(stream, BUCKET, List.of(record("{\"PRICE\": 1.5}")), DELIVERY_TIME);
|
||||
|
||||
assertTrue(stagedNdjson().contains("\"price\":null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parquetSerDeCompressionIsForwardedToTheCopy() {
|
||||
DeliveryStreamDescription stream = stream();
|
||||
stream.s3Destination().getDataFormatConversionConfiguration().getOutputFormatConfiguration()
|
||||
.getSerializer().getParquetSerDe().setCompression("GZIP");
|
||||
|
||||
converter.deliver(stream, BUCKET, List.of(record("{\"ticker\": \"AAA\"}")), DELIVERY_TIME);
|
||||
|
||||
verify(duckClient).execute(anyString(), contains("COMPRESSION GZIP"), isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timestampsAcceptEpochMillisAndIsoTVariants() {
|
||||
converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"ts\": 1788781695000}"),
|
||||
record("{\"ts\": \"2026-09-07T12:00:02\"}")), DELIVERY_TIME);
|
||||
|
||||
String ndjson = stagedNdjson();
|
||||
assertTrue(ndjson.contains("\"ts\":\"2026-09-07 11:48:15.000\""), "staged rows were: " + ndjson);
|
||||
assertTrue(ndjson.contains("\"ts\":\"2026-09-07 12:00:02\""), "staged rows were: " + ndjson);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringNumbersCoerceLikeAwsAndBadValuesReportTheParseCause() throws Exception {
|
||||
FirehoseParquetConverter.Outcome outcome = converter.deliver(stream(), BUCKET, List.of(
|
||||
record("{\"price\": \"2.25\", \"qty\": \"20\"}"),
|
||||
record("{\"active\": \"maybe\"}")), DELIVERY_TIME);
|
||||
|
||||
assertEquals(1, outcome.convertedRecords());
|
||||
assertTrue(stagedNdjson().contains("\"price\":2.25,\"qty\":20"));
|
||||
assertEquals("Data does not match the schema. For input string: \"maybe\"",
|
||||
errorLines().get(0).get("lastErrorMessage").asText());
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ class FirehoseServiceTest {
|
||||
// sees what a GetRecords consumer sees, and a stubbed one could not show that.
|
||||
kinesisService = new KinesisService(storageFactory, regionResolver);
|
||||
return new FirehoseService(storageFactory, s3Service, kinesisService,
|
||||
regionResolver, clock, config);
|
||||
regionResolver, clock, config, mock(FirehoseParquetConverter.class));
|
||||
}
|
||||
|
||||
private static S3Destination destination(String bucketArn, String compressionFormat) {
|
||||
|
||||
+31
@@ -155,6 +155,37 @@ class S3ObjectKeyResolverTest {
|
||||
assertTrue(key.endsWith(".gz"), key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitExtensionKeysEndWithItUnlessFileExtensionReplacesIt() {
|
||||
String key = S3ObjectKeyResolver.resolveKey(destination(null, null, null), "s", "1",
|
||||
INSTANT, ".parquet");
|
||||
assertTrue(key.endsWith(".parquet"), key);
|
||||
|
||||
String replaced = S3ObjectKeyResolver.resolveKey(destination(null, null, ".custom.log"), "s", "1",
|
||||
INSTANT, ".parquet");
|
||||
assertTrue(replaced.endsWith(".custom.log"), replaced);
|
||||
assertFalse(replaced.contains(".parquet"), replaced);
|
||||
}
|
||||
|
||||
/** Verified against real AWS: the error object carries no file extension. */
|
||||
@Test
|
||||
void errorKeyEvaluatesErrorOutputTypeAndCarriesNoExtension() {
|
||||
S3Destination s3 = destination(null, null, ".custom.log");
|
||||
s3.setErrorOutputPrefix("errors/!{firehose:error-output-type}/!{timestamp:yyyy}/");
|
||||
String key = S3ObjectKeyResolver.resolveErrorKey(s3, "my-stream", "2", INSTANT,
|
||||
"format-conversion-failed");
|
||||
assertTrue(key.matches("errors/format-conversion-failed/2026/"
|
||||
+ "my-stream-2-2026-07-13-10-42-07-" + UUID_REGEX), key);
|
||||
}
|
||||
|
||||
/** Unlike the data prefix, an absent ErrorOutputPrefix gets no default time prefix. */
|
||||
@Test
|
||||
void absentErrorOutputPrefixYieldsABareSuffixAtTheBucketRoot() {
|
||||
String key = S3ObjectKeyResolver.resolveErrorKey(destination(null, null, null), "s", "1",
|
||||
INSTANT, "format-conversion-failed");
|
||||
assertTrue(key.matches("s-1-2026-07-13-10-42-07-" + UUID_REGEX), key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveZoneFallsBackToUtc() {
|
||||
assertEquals(ZoneOffset.UTC, S3ObjectKeyResolver.resolveZone(null));
|
||||
|
||||
@@ -215,6 +215,7 @@ floci:
|
||||
enabled: true
|
||||
tick-interval-seconds: 10
|
||||
flush-record-count: 0
|
||||
staging-bucket: floci-firehose-staging
|
||||
kms:
|
||||
enabled: true
|
||||
cognito:
|
||||
|
||||
Reference in new issue
Block a user