feat(firehose): apply the Lambda transform to buffered records (#3393)

* feat(firehose): apply the Lambda transform to buffered records

A flushed buffer now goes to the Lambda processor's function as a single
invocation, and what the function returns is what reaches the destination.
Ok delivers the returned data, Dropped leaves no trace, and every other
outcome routes that record to the error output while the rest of the batch
still delivers: ProcessingFailed, a record the function did not return, a
record id returned twice, and an Ok carrying no data.

A function-level error is retried NumberOfRetries more times and then fails
the whole batch as Lambda.FunctionError; a response the function returned
successfully is final however malformed it is, matching what AWS reports for
a response naming no records at all.

The transformation runs ahead of data format conversion, so a stream
configured for both converts what the function returned, and the
"not applied yet" warning the configuration used to log is gone.

* fix(firehose): clamp a NumberOfRetries wider than a long, and heal a stored Enabled

Long.parseLong threw for a NumberOfRetries too wide for a long, which the
catch treated as "not a number" and answered with the default 3. A larger
retry count than one that clamps therefore got fewer attempts: 2147483648
delivered 101 attempts where 999999999999999999999 delivered 4. Reading it
as a BigInteger keeps the clamp meaningful at any magnitude.

A ProcessingConfiguration persisted before Enabled was defaulted never
passes canonicalizeProcessors again, so the describe path now fills it, the
way that path already self-heals partial BufferingHints. Only Enabled: the
parameters AWS defaults include RoleArn, which a read must not inject from
whatever role is current by then.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-11 11:45:03 -04:00
1 parent c6e64a0977
commit d96516dc70
11 files changed
+1628 -38

No files matched your search

@@ -15,6 +15,9 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OrcSerDe;
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.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
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;
@@ -23,6 +26,7 @@ import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.util.HashMap;
@@ -59,6 +63,7 @@ class FirehoseDataFormatConversionTest {
private FirehoseService service;
private FirehoseParquetConverter parquetConverter;
private FirehoseLambdaTransformer lambdaTransformer;
private S3Service s3Service;
@BeforeEach
@@ -81,10 +86,11 @@ class FirehoseDataFormatConversionTest {
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
when(regionResolver.getAccountId()).thenReturn("000000000000");
parquetConverter = Mockito.mock(FirehoseParquetConverter.class);
lambdaTransformer = Mockito.mock(FirehoseLambdaTransformer.class);
s3Service = Mockito.mock(S3Service.class);
service = new FirehoseService(storageFactory, s3Service,
Mockito.mock(KinesisService.class), regionResolver, new MutableClock(), config,
parquetConverter);
parquetConverter, lambdaTransformer);
}
private static SchemaConfiguration schema() {
@@ -544,6 +550,57 @@ class FirehoseDataFormatConversionTest {
any(byte[].class), anyString(), Mockito.anyMap(), any());
}
/**
* A stream configured for both has to convert what the transform returned, not what
* was put: the two were wired in separately, so nothing else would catch a delivery
* that passed the original bytes to the converter.
*/
@Test
void conversionOfATransformingStreamConvertsWhatTheTransformReturned() {
Mockito.when(lambdaTransformer.transform(any(), anyString(), any(), any()))
.thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"ticker\": \"BBB\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8)),
0, 0, null));
Mockito.when(parquetConverter.deliver(any(), anyString(), any(), any()))
.thenReturn(new FirehoseParquetConverter.Outcome(1, 0, "data/key.parquet", null));
service.createDeliveryStream("stream", destination(s3 -> s3.setProcessingConfiguration(lambdaProcessing())));
service.putRecord("stream", record("{\"ticker\": \"AAA\"}"));
service.flush("stream");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<byte[]>> converted = ArgumentCaptor.forClass(List.class);
Mockito.verify(parquetConverter).deliver(any(), Mockito.eq("results"), converted.capture(), any());
assertEquals(1, converted.getValue().size());
assertEquals("{\"ticker\": \"BBB\"}",
new String(converted.getValue().get(0), java.nio.charset.StandardCharsets.UTF_8));
}
@Test
void aTransformThatKeptNothingNeverReachesTheConverter() {
Mockito.when(lambdaTransformer.transform(any(), anyString(), any(), any()))
.thenReturn(new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
service.createDeliveryStream("stream", destination(s3 -> s3.setProcessingConfiguration(lambdaProcessing())));
service.putRecord("stream", record("{\"ticker\": \"AAA\"}"));
service.flush("stream");
Mockito.verify(parquetConverter, Mockito.never()).deliver(any(), anyString(), any(), any());
}
private static ProcessingConfiguration lambdaProcessing() {
ProcessorParameter lambdaArn = new ProcessorParameter();
lambdaArn.setParameterName("LambdaArn");
lambdaArn.setParameterValue("arn:aws:lambda:us-east-1:000000000000:function:transform");
Processor processor = new Processor();
processor.setType("Lambda");
processor.setParameters(List.of(lambdaArn));
ProcessingConfiguration processing = new ProcessingConfiguration();
processing.setEnabled(true);
processing.setProcessors(List.of(processor));
return processing;
}
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();
@@ -0,0 +1,246 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
/**
* End-to-end coverage of the Lambda transform on the real delivery path: what
* the function returns is what reaches S3, and what it fails reaches the error
* output instead. {@link FirehoseLambdaTransformerTest} covers the per-record
* result semantics against the transformer directly; this class is what proves
* the flush path runs it at all.
*
* The function itself is mocked. Running a real one needs Docker, which a
* delivery-path test should not depend on, and the invocation payload is
* asserted here from what the mock received.
*/
@QuarkusTest
@TestProfile(FirehoseLambdaTransformIntegrationTest.FlushEveryPairProfile.class)
class FirehoseLambdaTransformIntegrationTest {
public static class FlushEveryPairProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
// Each test puts a batch of two, which then delivers inline.
return Map.of("floci.services.firehose.flush-record-count", "2");
}
}
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "Firehose_20150804.";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:transform";
private static final Pattern KEY_PATTERN = Pattern.compile("<Key>([^<]+)</Key>");
@InjectMock
LambdaService lambdaService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void theFunctionsOutputIsWhatReachesTheDestination() {
String stream = "transform-ok-stream";
String bucket = "transform-ok-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> "{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\""
+ encode("TRANSFORMED-" + index) + "\"}");
putRecordBatch(stream, "one", "two");
given()
.when()
.get("/" + bucket + "/" + firstKey(bucket, "data/"))
.then()
.statusCode(200)
.body(equalTo("TRANSFORMED-0\nTRANSFORMED-1\n"));
}
@Test
void aFailedRecordGoesToTheErrorOutputWhileTheRestDelivers() {
String stream = "transform-failed-stream";
String bucket = "transform-failed-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> index == 0
? "{\"recordId\":\"" + recordId + "\",\"result\":\"ProcessingFailed\"}"
: "{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\"" + encode("kept") + "\"}");
putRecordBatch(stream, "one", "two");
given()
.when()
.get("/" + bucket + "/" + firstKey(bucket, "data/"))
.then()
.statusCode(200)
.body(equalTo("kept\n"));
String errorLine = given()
.when()
.get("/" + bucket + "/" + firstKey(bucket, "errors/processing-failed/"))
.then()
.statusCode(200)
.extract().asString();
assertTrue(errorLine.contains("\"errorCode\":\"Lambda.ProcessingFailedStatus\""), errorLine);
assertTrue(errorLine.contains("\"rawData\":\"" + encode("one") + "\""), errorLine);
assertTrue(errorLine.contains("\"lambdaARN\":\"" + FUNCTION_ARN + "\""), errorLine);
}
@Test
void aBatchTheFunctionDroppedEntirelyDeliversNothing() {
String stream = "transform-dropped-stream";
String bucket = "transform-dropped-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> "{\"recordId\":\"" + recordId + "\",\"result\":\"Dropped\"}");
putRecordBatch(stream, "one", "two");
String listing = given()
.when()
.get("/" + bucket)
.then()
.statusCode(200)
.extract().asString();
assertFalse(KEY_PATTERN.matcher(listing).find(), "expected no delivered object, got: " + listing);
}
@Test
void theInvocationCarriesEveryBufferedRecord() {
String stream = "transform-payload-stream";
String bucket = "transform-payload-archive";
createDeliveryStream(stream, bucket);
List<byte[]> payloads = respondWith((recordId, index) ->
"{\"recordId\":\"" + recordId + "\",\"result\":\"Dropped\"}");
putRecordBatch(stream, "one", "two");
assertEquals(1, payloads.size(), "the whole buffer should be one invocation");
String payload = new String(payloads.get(0), StandardCharsets.UTF_8);
assertTrue(payload.contains("\"deliveryStreamArn\":\"arn:aws:firehose:"), payload);
assertTrue(payload.contains("\"data\":\"" + encode("one") + "\""), payload);
assertTrue(payload.contains("\"data\":\"" + encode("two") + "\""), payload);
}
/**
* Answers each invocation from the record ids it actually carries, which the caller
* cannot name: they are minted per batch. Returns the payloads the mock received.
*/
private List<byte[]> respondWith(RecordResponder responder) {
List<byte[]> payloads = new ArrayList<>();
Mockito.when(lambdaService.invokeArn(anyString(), any(), any())).thenAnswer(invocation -> {
byte[] payload = invocation.getArgument(1);
payloads.add(payload);
List<String> entries = new ArrayList<>();
Matcher recordIds = Pattern.compile("\"recordId\":\"([^\"]+)\"")
.matcher(new String(payload, StandardCharsets.UTF_8));
for (int index = 0; recordIds.find(); index++) {
entries.add(responder.respond(recordIds.group(1), index));
}
InvokeResult result = new InvokeResult();
result.setStatusCode(200);
result.setPayload(("{\"records\":[" + String.join(",", entries) + "]}")
.getBytes(StandardCharsets.UTF_8));
return result;
});
return payloads;
}
@FunctionalInterface
private interface RecordResponder {
String respond(String recordId, int index);
}
private static String encode(String body) {
return Base64.getEncoder().encodeToString(body.getBytes(StandardCharsets.UTF_8));
}
private void createDeliveryStream(String streamName, String bucket) {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
.body("""
{
"DeliveryStreamName": "%s",
"DeliveryStreamType": "DirectPut",
"ExtendedS3DestinationConfiguration": {
"RoleARN": "arn:aws:iam::000000000000:role/firehose-delivery-role",
"BucketARN": "arn:aws:s3:::%s",
"Prefix": "data/!{timestamp:yyyy}/",
"ErrorOutputPrefix": "errors/!{firehose:error-output-type}/",
"ProcessingConfiguration": {
"Enabled": true,
"Processors": [
{
"Type": "Lambda",
"Parameters": [{"ParameterName": "LambdaArn", "ParameterValue": "%s"}]
}
]
}
}
}
""".formatted(streamName, bucket, FUNCTION_ARN))
.when()
.post("/")
.then()
.statusCode(200)
.body("DeliveryStreamARN", notNullValue());
}
private void putRecordBatch(String streamName, String... bodies) {
List<String> records = new ArrayList<>();
for (String body : bodies) {
records.add("{\"Data\": \"" + encode(body) + "\"}");
}
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "PutRecordBatch")
.body("{ \"DeliveryStreamName\": \"" + streamName + "\", \"Records\": ["
+ String.join(",", records) + "] }")
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedPutCount", equalTo(0));
}
private String firstKey(String bucket, String prefix) {
String listing = given()
.when()
.get("/" + bucket)
.then()
.statusCode(200)
.extract().asString();
Matcher key = KEY_PATTERN.matcher(listing);
while (key.find()) {
if (key.group(1).startsWith(prefix)) {
return key.group(1);
}
}
throw new AssertionError("expected an object under " + prefix + " in " + bucket + ", got: " + listing);
}
}
@@ -0,0 +1,513 @@
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.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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 java.util.function.Function;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* The result semantics, error codes and error-object shape asserted here were
* probed against real AWS (us-west-2, 2026-09-10), including which failures are
* retried: a function that errors is, a response the function shaped wrongly is
* not.
*/
class FirehoseLambdaTransformerTest {
private static final String BUCKET = "results";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:transform";
private static final Instant DELIVERY_TIME = Instant.parse("2026-01-01T00:00:00Z");
private LambdaService lambdaService;
private S3Service s3Service;
private FirehoseLambdaTransformer transformer;
private final ObjectMapper mapper = new ObjectMapper();
private JsonNode invocationEvent;
@BeforeEach
void setUp() {
lambdaService = mock(LambdaService.class);
s3Service = mock(S3Service.class);
transformer = new FirehoseLambdaTransformer(lambdaService, s3Service, mapper,
new RegionResolver("us-east-1", "000000000000"));
}
// ── fixtures ─────────────────────────────────────────────────────────────
private static DeliveryStreamDescription stream(Processor... processors) {
ProcessingConfiguration processing = new ProcessingConfiguration();
processing.setEnabled(true);
processing.setProcessors(List.of(processors));
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::" + BUCKET);
s3.setErrorOutputPrefix("errors/!{firehose:error-output-type}/");
s3.setProcessingConfiguration(processing);
return new DeliveryStreamDescription("stream", "arn:aws:firehose:us-west-2:000000000000:deliverystream/stream", s3);
}
private static Processor lambdaProcessor(String... parameters) {
List<ProcessorParameter> list = new ArrayList<>();
list.add(parameter("LambdaArn", FUNCTION_ARN));
for (int i = 0; i < parameters.length; i += 2) {
list.add(parameter(parameters[i], parameters[i + 1]));
}
Processor processor = new Processor();
processor.setType("Lambda");
processor.setParameters(list);
return processor;
}
private static ProcessorParameter parameter(String name, String value) {
ProcessorParameter parameter = new ProcessorParameter();
parameter.setParameterName(name);
parameter.setParameterValue(value);
return parameter;
}
private static byte[] record(String body) {
return body.getBytes(StandardCharsets.UTF_8);
}
private static String encode(String body) {
return Base64.getEncoder().encodeToString(record(body));
}
/**
* Answers the invocation from the record ids the transformer actually generated,
* which is the only way a test can name them: they are minted per batch.
*/
private void replyWith(Function<List<String>, String> responder) {
when(lambdaService.invokeArn(anyString(), any(), any())).thenAnswer(invocation -> {
invocationEvent = mapper.readTree((byte[]) invocation.getArgument(1));
List<String> recordIds = new ArrayList<>();
invocationEvent.get("records").forEach(node -> recordIds.add(node.get("recordId").asText()));
InvokeResult result = new InvokeResult();
result.setStatusCode(200);
result.setPayload(responder.apply(recordIds).getBytes(StandardCharsets.UTF_8));
return result;
});
}
private static String records(String... entries) {
return "{\"records\":[" + String.join(",", entries) + "]}";
}
private static String ok(String recordId, String data) {
return "{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\"" + encode(data) + "\"}";
}
private static String outcome(String recordId, String result) {
return "{\"recordId\":\"" + recordId + "\",\"result\":\"" + result + "\"}";
}
private List<String> delivered(FirehoseLambdaTransformer.Outcome outcome) {
return outcome.records().stream()
.map(data -> new String(data, StandardCharsets.UTF_8))
.collect(Collectors.toList());
}
private List<JsonNode> errorLines() throws Exception {
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq(BUCKET), key.capture(), body.capture(),
eq("application/octet-stream"), anyMap());
assertTrue(key.getValue().startsWith("errors/processing-failed/"),
"error output key was " + key.getValue());
List<JsonNode> lines = new ArrayList<>();
for (String line : new String(body.getValue(), StandardCharsets.UTF_8).split("\n")) {
lines.add(mapper.readTree(line));
}
return lines;
}
private FirehoseLambdaTransformer.Outcome transform(DeliveryStreamDescription stream, byte[]... records) {
return transformer.transform(stream, BUCKET, List.of(records), DELIVERY_TIME);
}
// ── pass-through ─────────────────────────────────────────────────────────
@Test
void aStreamWithoutAProcessingConfigurationIsNotTransformed() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::" + BUCKET);
DeliveryStreamDescription stream =
new DeliveryStreamDescription("stream", "arn:aws:firehose:::stream", s3);
List<byte[]> records = List.of(record("a"));
FirehoseLambdaTransformer.Outcome outcome =
transformer.transform(stream, BUCKET, records, DELIVERY_TIME);
assertSame(records, outcome.records());
verifyNoInteractions(lambdaService);
}
/**
* Probed 2026-09-11: an omitted Enabled is stored as false, so it leaves the stream
* untransformed. The conversion block treats an omitted Enabled the other way, which
* is why this is asserted rather than inferred from it.
*/
@Test
void aProcessingConfigurationWithoutAnExplicitEnabledIsNotTransformed() {
DeliveryStreamDescription stream = stream(lambdaProcessor());
stream.s3Destination().getProcessingConfiguration().setEnabled(null);
FirehoseLambdaTransformer.Outcome outcome = transform(stream, record("a"));
assertEquals(List.of("a"), delivered(outcome));
verifyNoInteractions(lambdaService);
}
@Test
void aDisabledProcessingConfigurationIsNotTransformed() {
DeliveryStreamDescription stream = stream(lambdaProcessor());
stream.s3Destination().getProcessingConfiguration().setEnabled(false);
transform(stream, record("a"));
verifyNoInteractions(lambdaService);
}
@Test
void aProcessorTypeFlociDoesNotApplyLeavesTheRecordsAlone() {
Processor appendDelimiter = new Processor();
appendDelimiter.setType("AppendDelimiterToRecord");
FirehoseLambdaTransformer.Outcome outcome = transform(stream(appendDelimiter), record("a"));
assertEquals(List.of("a"), delivered(outcome));
verifyNoInteractions(lambdaService);
}
// ── invocation payload ───────────────────────────────────────────────────
@Test
void theInvocationCarriesTheProbedEventShape() {
replyWith(ids -> records(ok(ids.get(0), "transformed")));
transform(stream(lambdaProcessor()), record("original"));
assertEquals(List.of("invocationId", "deliveryStreamArn", "region", "records"),
fieldNames(invocationEvent));
assertEquals("arn:aws:firehose:us-west-2:000000000000:deliverystream/stream",
invocationEvent.get("deliveryStreamArn").asText());
assertEquals("us-west-2", invocationEvent.get("region").asText());
JsonNode record = invocationEvent.get("records").get(0);
assertEquals(List.of("recordId", "approximateArrivalTimestamp", "data"), fieldNames(record));
assertEquals(DELIVERY_TIME.toEpochMilli(), record.get("approximateArrivalTimestamp").asLong());
assertEquals(encode("original"), record.get("data").asText());
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), any(), eq(InvocationType.RequestResponse));
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
// ── per-record results ───────────────────────────────────────────────────
@Test
void okReplacesTheRecordWithTheReturnedData() {
replyWith(ids -> records(ok(ids.get(0), "one"), ok(ids.get(1), "two")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(List.of("one", "two"), delivered(outcome));
assertEquals(0, outcome.failedRecords());
assertNull(outcome.errorKey());
verify(s3Service, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap());
}
@Test
void droppedLeavesNoRecordAndNoErrorObject() {
replyWith(ids -> records(outcome(ids.get(0), "Dropped"), ok(ids.get(1), "kept")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(List.of("kept"), delivered(outcome));
assertEquals(1, outcome.droppedRecords());
assertEquals(0, outcome.failedRecords());
assertNull(outcome.errorKey());
}
@Test
void processingFailedRoutesOnlyThatRecordToTheErrorOutput() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed"), ok(ids.get(1), "kept")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(List.of("kept"), delivered(outcome));
assertEquals(1, outcome.failedRecords());
JsonNode line = errorLines().get(0);
assertEquals("Lambda.ProcessingFailedStatus", line.get("errorCode").asText());
assertEquals("ProcessingFailed status set for record", line.get("errorMessage").asText());
assertEquals(encode("a"), line.get("rawData").asText());
}
@Test
void aRecordTheFunctionDidNotReturnFails() throws Exception {
replyWith(ids -> records(ok(ids.get(0), "one")));
transform(stream(lambdaProcessor()), record("a"), record("b"));
JsonNode line = errorLines().get(0);
assertEquals("Lambda.MissingRecordId", line.get("errorCode").asText());
assertEquals(encode("b"), line.get("rawData").asText());
}
@Test
void aRecordIdReturnedTwiceFails() throws Exception {
replyWith(ids -> records(ok(ids.get(0), "one"), ok(ids.get(0), "again"), ok(ids.get(1), "two")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(List.of("two"), delivered(outcome));
assertEquals("Lambda.DuplicatedRecordId", errorLines().get(0).get("errorCode").asText());
}
@Test
void aRecordIdTheBatchNeverCarriedIsIgnored() {
replyWith(ids -> records(ok(ids.get(0), "one"), ok("not-in-this-batch", "stray")));
FirehoseLambdaTransformer.Outcome outcome = transform(stream(lambdaProcessor()), record("a"));
assertEquals(List.of("one"), delivered(outcome));
assertEquals(0, outcome.failedRecords());
}
@Test
void okWithoutDataFails() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "Ok")));
transform(stream(lambdaProcessor()), record("a"));
JsonNode line = errorLines().get(0);
assertEquals("Lambda.InvalidReturnFormat", line.get("errorCode").asText());
assertTrue(line.get("errorMessage").asText().startsWith("The data field cannot be null"));
}
/**
* The message here is Floci's own: AWS was not probed for a data field that is not
* base64 at all, only for one that is absent.
*/
@Test
void dataThatIsNotBase64Fails() throws Exception {
replyWith(ids -> records(
"{\"recordId\":\"" + ids.get(0) + "\",\"result\":\"Ok\",\"data\":\"not base64 %%%\"}",
ok(ids.get(1), "kept")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(List.of("kept"), delivered(outcome));
assertEquals(1, outcome.failedRecords());
JsonNode line = errorLines().get(0);
assertEquals("Lambda.InvalidReturnFormat", line.get("errorCode").asText());
assertTrue(line.get("errorMessage").asText().startsWith("The data field must be base64 encoded"));
assertEquals(encode("a"), line.get("rawData").asText());
}
@Test
void anUnknownResultValueFails() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "Maybe")));
transform(stream(lambdaProcessor()), record("a"));
assertEquals("Lambda.InvalidReturnFormat", errorLines().get(0).get("errorCode").asText());
}
// ── failures of the invocation itself ────────────────────────────────────
@Test
void aFunctionErrorIsRetriedAndThenFailsTheWholeBatch() throws Exception {
InvokeResult errored = new InvokeResult();
errored.setStatusCode(200);
errored.setFunctionError("Unhandled");
when(lambdaService.invokeArn(anyString(), any(), any())).thenReturn(errored);
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor("NumberOfRetries", "2")), record("a"), record("b"));
assertTrue(outcome.records().isEmpty());
assertEquals(2, outcome.failedRecords());
verify(lambdaService, times(3)).invokeArn(anyString(), any(), any());
JsonNode line = errorLines().get(0);
assertEquals("Lambda.FunctionError", line.get("errorCode").asText());
assertEquals(3, line.get("attemptsMade").asInt());
}
@Test
void anUninvokableFunctionIsRetriedTheSameWay() throws Exception {
when(lambdaService.invokeArn(anyString(), any(), any()))
.thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404));
transform(stream(lambdaProcessor("NumberOfRetries", "1")), record("a"));
verify(lambdaService, times(2)).invokeArn(anyString(), any(), any());
assertEquals("Lambda.FunctionError", errorLines().get(0).get("errorCode").asText());
}
@Test
void aResponseCarryingNoRecordsIsNotRetried() throws Exception {
replyWith(ids -> "{}");
transform(stream(lambdaProcessor("NumberOfRetries", "5")), record("a"));
verify(lambdaService, times(1)).invokeArn(anyString(), any(), any());
JsonNode line = errorLines().get(0);
assertEquals("Lambda.MissingRecordId", line.get("errorCode").asText());
assertEquals(1, line.get("attemptsMade").asInt());
}
@Test
void anUnparseableResponseFailsEveryRecordWithoutRetrying() throws Exception {
replyWith(ids -> "not json at all");
transform(stream(lambdaProcessor()), record("a"));
verify(lambdaService, times(1)).invokeArn(anyString(), any(), any());
assertEquals("Lambda.MissingRecordId", errorLines().get(0).get("errorCode").asText());
}
@Test
void anAbsentNumberOfRetriesFallsBackToTheThreeAwsDefaults() {
InvokeResult errored = new InvokeResult();
errored.setFunctionError("Unhandled");
when(lambdaService.invokeArn(anyString(), any(), any())).thenReturn(errored);
transform(stream(lambdaProcessor()), record("a"));
verify(lambdaService, times(4)).invokeArn(anyString(), any(), any());
}
/**
* AWS stores a NumberOfRetries it never range-checks, so the largest one a caller can
* write has to stay a bounded number of invocations rather than overflowing the
* attempt count or occupying the flusher thread indefinitely.
*/
@Test
void aRetryCountLargerThanFlociHonoursIsCapped() throws Exception {
InvokeResult errored = new InvokeResult();
errored.setFunctionError("Unhandled");
when(lambdaService.invokeArn(anyString(), any(), any())).thenReturn(errored);
transform(stream(lambdaProcessor("NumberOfRetries", String.valueOf(Integer.MAX_VALUE))), record("a"));
verify(lambdaService, times(101)).invokeArn(anyString(), any(), any());
assertEquals(101, errorLines().get(0).get("attemptsMade").asInt());
}
/**
* A NumberOfRetries too wide even for a long is still a number, and treating it as
* unparseable would hand it fewer attempts than a smaller one gets.
*/
@Test
void aRetryCountTooWideForALongIsCappedRatherThanDefaulted() {
InvokeResult errored = new InvokeResult();
errored.setFunctionError("Unhandled");
when(lambdaService.invokeArn(anyString(), any(), any())).thenReturn(errored);
transform(stream(lambdaProcessor("NumberOfRetries", "999999999999999999999")), record("a"));
verify(lambdaService, times(101)).invokeArn(anyString(), any(), any());
}
@Test
void aNegativeRetryCountInvokesOnce() {
replyWith(ids -> records(ok(ids.get(0), "one")));
transform(stream(lambdaProcessor("NumberOfRetries", "-5")), record("a"));
verify(lambdaService, times(1)).invokeArn(anyString(), any(), any());
}
// ── error object ─────────────────────────────────────────────────────────
@Test
void theErrorObjectFollowsTheProbedMemberOrder() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed")));
transform(stream(lambdaProcessor()), record("a"));
JsonNode line = errorLines().get(0);
assertEquals(List.of("rawData", "errorCode", "errorMessage", "attemptsMade",
"arrivalTimestamp", "attemptEndingTimestamp", "lambdaARN"),
fieldNames(line));
assertEquals(FUNCTION_ARN, line.get("lambdaARN").asText());
assertEquals(DELIVERY_TIME.toEpochMilli(), line.get("arrivalTimestamp").asLong());
assertEquals(DELIVERY_TIME.toEpochMilli(), line.get("attemptEndingTimestamp").asLong());
}
@Test
void everyFailedRecordGetsItsOwnLineInOneErrorObject() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed"), outcome(ids.get(1), "ProcessingFailed")));
FirehoseLambdaTransformer.Outcome outcome =
transform(stream(lambdaProcessor()), record("a"), record("b"));
assertEquals(2, outcome.failedRecords());
List<JsonNode> lines = errorLines();
assertEquals(2, lines.size());
assertEquals(encode("a"), lines.get(0).get("rawData").asText());
assertEquals(encode("b"), lines.get(1).get("rawData").asText());
}
@Test
void theErrorOutputKeyResolvesTheErrorOutputTypeExpression() {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed")));
FirehoseLambdaTransformer.Outcome outcome = transform(stream(lambdaProcessor()), record("a"));
assertTrue(outcome.errorKey().startsWith("errors/processing-failed/stream-"),
"error output key was " + outcome.errorKey());
}
@Test
void theBatchIsWrittenToTheDestinationBucket() {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed")));
transform(stream(lambdaProcessor()), record("a"));
verify(s3Service).putObject(eq(BUCKET), anyString(), any(), eq("application/octet-stream"),
eq(Map.of()));
}
}
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.BufferingHints;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -26,6 +27,7 @@ import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -70,7 +72,8 @@ class FirehoseProcessingConfigurationTest {
when(regionResolver.getAccountId()).thenReturn("000000000000");
service = new FirehoseService(storageFactory, mock(S3Service.class),
Mockito.mock(KinesisService.class), regionResolver, new MutableClock(), config,
Mockito.mock(FirehoseParquetConverter.class));
Mockito.mock(FirehoseParquetConverter.class),
Mockito.mock(FirehoseLambdaTransformer.class));
}
private static ProcessorParameter parameter(String name, String value) {
@@ -94,6 +97,20 @@ class FirehoseProcessingConfigurationTest {
return processing("Lambda", parameters);
}
private static Processor lambdaProcessor(ProcessorParameter... parameters) {
Processor processor = new Processor();
processor.setType("Lambda");
processor.setParameters(new ArrayList<>(List.of(parameters)));
return processor;
}
private static BufferingHints hints(int sizeInMBs, int intervalInSeconds) {
BufferingHints hints = new BufferingHints();
hints.setSizeInMBs(sizeInMBs);
hints.setIntervalInSeconds(intervalInSeconds);
return hints;
}
private static S3Destination destination(Consumer<S3Destination> customizer) {
S3Destination s3 = new S3Destination();
s3.setRoleArn(ROLE_ARN);
@@ -329,7 +346,69 @@ class FirehoseProcessingConfigurationTest {
service.updateDestination("stream", currentVersion("stream"), DESTINATION_ID,
destination(s3 -> s3.setPrefix("changed/")));
assertEquals(List.of("LambdaArn", "NumberOfRetries", "RoleArn"), storedParameterNames("stream"));
assertEquals(List.of("LambdaArn", "NumberOfRetries", "RoleArn", "BufferSizeInMBs",
"BufferIntervalInSeconds"), storedParameterNames("stream"));
}
/**
* Probed 2026-09-11: DescribeDeliveryStream echoes an omitted Enabled back as false
* here, where the conversion block echoes it as true, so the two cannot share a rule.
*/
@Test
void anOmittedEnabledIsStoredAsDisabled() {
ProcessingConfiguration processing = new ProcessingConfiguration();
processing.setProcessors(List.of(lambdaProcessor(parameter("LambdaArn", LAMBDA_ARN))));
service.createDeliveryStream("stream",
destination(s3 -> s3.setProcessingConfiguration(processing)));
S3Destination stored = service.describeDeliveryStream("stream").s3Destination();
assertEquals(false, stored.getProcessingConfiguration().getEnabled());
assertFalse(stored.isProcessingEnabled());
}
/**
* The two buffer parameters are the Lambda processor's own defaults, not the
* destination's BufferingHints: probed, a destination buffering 5 MiB over 300s still
* echoes 1 and 60 on the processor.
*/
@Test
void aProcessorWithoutBufferParametersGainsTheLambdaDefaults() {
service.createDeliveryStream("stream", destination(s3 -> {
s3.setBufferingHints(hints(5, 300));
s3.setProcessingConfiguration(lambdaProcessing(parameter("LambdaArn", LAMBDA_ARN)));
}));
List<ProcessorParameter> stored = service.describeDeliveryStream("stream").s3Destination()
.getProcessingConfiguration().getProcessors().get(0).getParameters();
assertEquals("1", parameterValue(stored, "BufferSizeInMBs"));
assertEquals("60", parameterValue(stored, "BufferIntervalInSeconds"));
}
/**
* State persisted before Enabled was defaulted never passes canonicalizeProcessors
* again, so the describe path heals it rather than reporting a stream without the
* member AWS always returns.
*/
@Test
void applyDefaultsHealsAProcessingBlockStoredWithoutEnabled() {
ProcessingConfiguration processing = new ProcessingConfiguration();
processing.setProcessors(List.of(lambdaProcessor(parameter("LambdaArn", LAMBDA_ARN))));
S3Destination stored = new S3Destination();
stored.setProcessingConfiguration(processing);
stored.applyDefaults();
assertEquals(false, processing.getEnabled());
assertFalse(stored.isProcessingEnabled());
}
private static String parameterValue(List<ProcessorParameter> parameters, String name) {
for (ProcessorParameter parameter : parameters) {
if (name.equals(parameter.getParameterName())) {
return parameter.getParameterValue();
}
}
return null;
}
// Validation runs against the update's own content, since the update replaces the
@@ -91,7 +91,8 @@ 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, mock(FirehoseParquetConverter.class));
regionResolver, clock, config, mock(FirehoseParquetConverter.class),
mock(FirehoseLambdaTransformer.class));
}
private static S3Destination destination(String bucketArn, String compressionFormat) {