Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(pipes): apply EventBridge Pipe enrichment before target delivery (#1658)

Alex Banna0e85ac92c700
diff --git a/docs/services/pipes.md b/docs/services/pipes.md
index 9683824198..b1948b1c4d 100644
--- a/docs/services/pipes.md
+++ b/docs/services/pipes.md
@@ -89,3 +89,21 @@ Floci emulates EventBridge Pipes with the following supported source and target
- SNS topics
- Kinesis streams
- Step Functions state machines
+
+## Enrichment
+
+A pipe's optional enrichment step (`source → filter → enrichment → target`) is emulated for
+**Lambda** enrichments: the filtered batch is invoked synchronously (`RequestResponse`) and the
+response becomes the target input.
+
+- **Empty responses skip the target**, matching AWS: an empty body, `null`, `{}`, or `[]` consumes
+ the source records without invoking the target. A non-empty array such as `[{}]` still invokes the
+ target (with an empty-payload element).
+- **A Lambda enrichment `FunctionError` fails the batch** — the source records are routed to the
+ pipe's dead-letter queue rather than silently consumed.
+- **Non-Lambda enrichment types** (API destinations, API Gateway, Step Functions Express) are valid
+ on AWS but not emulated; a pipe configured with one fails the batch to the DLQ rather than
+ delivering the unenriched payload.
+- **Enrichment is currently applied only on the SQS source path.** Kinesis, DynamoDB Streams and
+ Kafka sources deliver filtered records straight to the target; an enrichment configured on those
+ sources is not yet applied.
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
index 28dacb4b87..7b9593ff00 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
@@ -159,7 +159,7 @@ public class PipesPoller implements Resettable {
});
}
- private void pollSqs(Pipe pipe, String region) {
+ void pollSqs(Pipe pipe, String region) {
String queueUrl = AwsArnUtils.arnToQueueUrl(pipe.getSource(), baseUrl);
int batchSize = getBatchSize(pipe, "SqsQueueParameters");
List<Message> messages = sqsService.receiveMessage(queueUrl, batchSize, 30, 0, region);
@@ -196,6 +196,14 @@ public class PipesPoller implements Resettable {
return;
}
+ // AWS EventBridge Pipes: source → filter → ENRICHMENT → target. When an enrichment is
+ // configured it is invoked once with the filtered events (as a bare JSON array, matching the
+ // Lambda's SQSRecord[] input) and its response is forwarded to the target.
+ if (hasEnrichment(pipe)) {
+ deliverEnrichedBatch(pipe, filtered, messages, matchedMessageIds, queueUrl, region);
+ return;
+ }
+
if (isLambdaTarget(pipe)) {
String eventJson = wrapRecords(filtered);
boolean delivered = invokeWithDlq(pipe, eventJson, region);
@@ -494,6 +502,10 @@ public class PipesPoller implements Resettable {
// ──────────────────────────── Invocation & DLQ ────────────────────────────
private int deliverRecords(Pipe pipe, List<JsonNode> records, String region) {
+ // Enrichment (source → filter → ENRICHMENT → target) is currently applied only on the SQS
+ // source path (see deliverEnrichedBatch). Kinesis, DynamoDB Streams and Kafka sources
+ // deliver the filtered records straight to the target, so a pipe that configures an
+ // enrichment on those sources bypasses it — see docs/services/pipes.md.
if (isLambdaTarget(pipe)) {
return invokeWithDlq(pipe, wrapRecords(records), region) ? 0 : records.size();
}
@@ -517,6 +529,76 @@ public class PipesPoller implements Resettable {
}
}
+ private static boolean hasEnrichment(Pipe pipe) {
+ return pipe.getEnrichment() != null && !pipe.getEnrichment().isBlank();
+ }
+
+ /**
+ * Runs the pipe enrichment once over the filtered SQS batch and forwards its response to the
+ * target, then deletes the consumed source messages. The enrichment Lambda receives the events
+ * as a bare JSON array (SQSRecord[]); a null/empty enrichment response skips the target (AWS
+ * behavior) while still consuming the source messages.
+ */
+ private void deliverEnrichedBatch(Pipe pipe, List<JsonNode> filtered, List<Message> messages,
+ Set<String> matchedMessageIds, String queueUrl, String region) {
+ String eventsArray = bareArray(filtered);
+ boolean delivered;
+ try {
+ String enriched = targetInvoker.applyEnrichment(pipe, eventsArray, region);
+ if (enriched != null) {
+ // Only a Lambda target expects the batch (JSON array) shape; a Step Functions, SQS,
+ // SNS or EventBridge target must receive the raw enrichment response, matching the
+ // non-enrichment delivery path. Array-wrapping those would corrupt their input.
+ String targetPayload = isLambdaTarget(pipe)
+ ? asEventArray(objectMapper, enriched)
+ : enriched;
+ targetInvoker.invoke(pipe, targetPayload, region);
+ }
+ delivered = true;
+ } catch (Exception e) {
+ LOG.warnv("Pipe {0}: enriched delivery failed: {1} ({2})",
+ pipe.getName(), e.getMessage(), e.getClass().getSimpleName());
+ delivered = sendToDeadLetterQueue(pipe, eventsArray, region);
+ }
+ if (delivered) {
+ for (Message msg : messages) {
+ if (matchedMessageIds.contains(msg.getMessageId())) {
+ try {
+ sqsService.deleteMessage(queueUrl, msg.getReceiptHandle(), region);
+ } catch (Exception e) {
+ LOG.warnv("Pipe {0}: failed to delete SQS message {1}: {2}",
+ pipe.getName(), msg.getMessageId(), e.getMessage());
+ }
+ }
+ }
+ }
+ }
+
+ private String bareArray(List<JsonNode> records) {
+ var arr = objectMapper.createArrayNode();
+ records.forEach(arr::add);
+ return arr.toString();
+ }
+
+ /**
+ * EventBridge Pipes delivers events to a target as a batch (JSON array). An enrichment that
+ * returns a single (non-array) JSON value represents one event, so it is wrapped in a
+ * one-element array; an array response is already a batch and is forwarded unchanged.
+ */
+ static String asEventArray(ObjectMapper objectMapper, String payload) {
+ try {
+ JsonNode node = objectMapper.readTree(payload);
+ if (node.isArray()) {
+ return payload;
+ }
+ return objectMapper.createArrayNode().add(node).toString();
+ } catch (Exception e) {
+ LOG.debugv("Pipe enrichment response was not JSON, wrapping as a single string event: {0}",
+ e.getMessage());
+ return objectMapper.createArrayNode().add(payload).toString();
+ }
+ }
+
private boolean sendToDeadLetterQueue(Pipe pipe, String payload, String region) {
String dlqArn = getDlqArn(pipe);
if (dlqArn == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
index 0aab5ff1aa..8da929cb52 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.services.eventbridge.EventBridgeService;
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.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
@@ -15,6 +17,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -77,13 +80,94 @@ public class PipesTargetInvoker {
}
}
+ /**
+ * Applies a Pipe's enrichment step (AWS EventBridge Pipes: source → filter → ENRICHMENT → target).
+ * The enrichment is invoked with the filtered events and its response becomes the target input.
+ * Only Lambda enrichments are emulated. Returns the response payload to forward, or {@code null}
+ * when the enrichment returns an empty response — AWS skips the target in that case.
+ * Returns {@code payload} unchanged when no enrichment is configured.
+ */
+ public String applyEnrichment(Pipe pipe, String payload, String region) {
+ String enrichment = pipe.getEnrichment();
+ if (enrichment == null || enrichment.isBlank()) {
+ return payload;
+ }
+ JsonNode ep = pipe.getEnrichmentParameters();
+ if (ep != null && ep.path("InputTemplate").isTextual()) {
+ payload = applyInputTemplate(ep.get("InputTemplate").asText(), payload);
+ }
+ if (enrichment.contains(":lambda:") || enrichment.contains(":function:")) {
+ String fnName = lambdaFunctionName(enrichment);
+ String fnRegion = extractRegionFromArn(enrichment, region);
+ InvokeResult result = lambdaService.invoke(
+ fnRegion, fnName, payload.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
+ if (result.getFunctionError() != null) {
+ throw new AwsException("InternalException",
+ "Pipe enrichment Lambda " + fnName + " failed: " + result.getFunctionError(), 500);
+ }
+ byte[] out = result.getPayload();
+ String resp = out == null ? "" : new String(out, StandardCharsets.UTF_8).trim();
+ if (resp.isEmpty() || "null".equals(resp)) {
+ return null;
+ }
+ // AWS also skips the target when the enrichment returns an empty object {} or empty
+ // array []; only a non-empty array such as [{}] invokes the target (with an
+ // empty-payload element). Parse so whitespace variants ({ }, [ ]) are handled too.
+ try {
+ JsonNode node = objectMapper.readTree(resp);
+ if ((node.isObject() || node.isArray()) && node.isEmpty()) {
+ return null;
+ }
+ } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
+ // Non-JSON textual enrichment response — forward as-is.
+ }
+ LOG.debugv("Pipe {0}: enrichment {1} produced target payload", pipe.getName(), enrichment);
+ return resp;
+ }
+ // API destination, API Gateway and Step Functions Express enrichments are valid on AWS but
+ // not emulated here. Fail rather than silently delivering the unenriched payload — the
+ // caller routes the batch to the pipe's dead-letter queue.
+ throw new AwsException("InternalException",
+ "Pipe " + pipe.getName() + " uses an unsupported enrichment type (only Lambda is "
+ + "emulated): " + enrichment, 500);
+ }
+
private void invokeLambda(String arn, String payload, String region) {
- String fnName = arn.substring(arn.lastIndexOf(':') + 1);
+ String fnName = lambdaFunctionName(arn);
String fnRegion = extractRegionFromArn(arn, region);
- lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.RequestResponse);
+ InvokeResult result = lambdaService.invoke(
+ fnRegion, fnName, payload.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
+ // A target Lambda that returns a FunctionError is a failed delivery, not a success — surface it
+ // so the caller routes the source record to the DLQ instead of silently consuming it.
+ if (result.getFunctionError() != null) {
+ throw new AwsException("InternalException",
+ "Pipe target Lambda " + fnName + " returned an error: " + result.getFunctionError(), 500);
+ }
LOG.debugv("Pipe delivered to Lambda: {0}", arn);
}
+ /**
+ * Extracts a Lambda function name from a bare name, a name with a version/alias qualifier
+ * (e.g. "name:$LATEST"), or a full/partial function ARN
+ * ("arn:aws:lambda:region:acct:function:NAME[:qualifier]"). Taking the last ':'-segment is
+ * wrong for a qualified ARN — it yields the qualifier instead of the name.
+ */
+ static String lambdaFunctionName(String ref) {
+ if (ref == null) {
+ return null;
+ }
+ String fn = ref;
+ int fi = ref.indexOf(":function:");
+ if (fi >= 0) {
+ fn = ref.substring(fi + ":function:".length());
+ }
+ int colon = fn.indexOf(':');
+ if (colon >= 0) {
+ fn = fn.substring(0, colon);
+ }
+ return fn;
+ }
+
private void invokeSqs(String arn, String payload, String region) {
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0, region);
diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java
index ec91255438..c9cc6abdc0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.github.hectorvent.floci.services.sqs.model.Message;
import io.vertx.core.Vertx;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
@@ -27,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -57,6 +59,91 @@ class PipesPollerTest {
kafkaConsumerManager, targetInvoker, new PipesFilterMatcher(MAPPER), MAPPER, config);
}
+ @Test
+ void asEventArrayWrapsSingleObjectInBatchArray() throws Exception {
+ // Pipes delivers events to a target as a batch array; a single-object enrichment response
+ // must become a one-element array so a target like "InputPath": "$.[0]" can unwrap it.
+ String wrapped = PipesPoller.asEventArray(MAPPER, "{\"systemId\":\"S1\",\"solutions\":[1]}");
+ JsonNode node = MAPPER.readTree(wrapped);
+ assertTrue(node.isArray());
+ assertEquals(1, node.size());
+ assertEquals("S1", node.get(0).path("systemId").asText());
+ }
+
+ @Test
+ void asEventArrayLeavesArrayResponseUnchanged() throws Exception {
+ String out = PipesPoller.asEventArray(MAPPER, "[{\"a\":1},{\"a\":2}]");
+ JsonNode node = MAPPER.readTree(out);
+ assertTrue(node.isArray());
+ assertEquals(2, node.size());
+ assertEquals(2, node.get(1).path("a").asInt());
+ }
+
+ @Test
+ void asEventArrayWrapsNonJsonAsSingleStringEvent() throws Exception {
+ String out = PipesPoller.asEventArray(MAPPER, "not-json");
+ JsonNode node = MAPPER.readTree(out);
+ assertTrue(node.isArray());
+ assertEquals(1, node.size());
+ assertEquals("not-json", node.get(0).asText());
+ }
+
+ @Test
+ void pollSqs_enrichmentToNonLambdaTargetForwardsRawResponse() throws Exception {
+ // A non-Lambda target (here Step Functions) must receive the raw enrichment response, not a
+ // one-element batch array — array-wrapping would start the execution with [{...}] instead of {...}.
+ Pipe pipe = new Pipe();
+ pipe.setName("enrich-sfn");
+ pipe.setSource("arn:aws:sqs:us-east-1:000000000000:src-queue");
+ pipe.setEnrichment("arn:aws:lambda:us-east-1:000000000000:function:enrich");
+ pipe.setTarget("arn:aws:states:us-east-1:000000000000:stateMachine:tgt");
+
+ Message msg = new Message("{\"orderId\":\"o1\"}");
+ msg.setMessageId("m1");
+ msg.setReceiptHandle("rh1");
+ when(sqsService.receiveMessage(anyString(), anyInt(), anyInt(), anyInt(), eq("us-east-1")))
+ .thenReturn(List.of(msg));
+ when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1")))
+ .thenReturn("{\"systemId\":\"S1\"}");
+
+ poller.pollSqs(pipe, "us-east-1");
+
+ ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
+ verify(targetInvoker).invoke(eq(pipe), payload.capture(), eq("us-east-1"));
+ JsonNode delivered = MAPPER.readTree(payload.getValue());
+ assertFalse(delivered.isArray(),
+ "non-Lambda target must receive the raw enrichment response, not a batch array");
+ assertEquals("S1", delivered.path("systemId").asText());
+ }
+
+ @Test
+ void pollSqs_enrichmentToLambdaTargetWrapsResponseInBatchArray() throws Exception {
+ // A Lambda target expects the SQSRecord[]-style batch, so a single-object enrichment response
+ // is wrapped in a one-element array.
+ Pipe pipe = new Pipe();
+ pipe.setName("enrich-lambda");
+ pipe.setSource("arn:aws:sqs:us-east-1:000000000000:src-queue");
+ pipe.setEnrichment("arn:aws:lambda:us-east-1:000000000000:function:enrich");
+ pipe.setTarget("arn:aws:lambda:us-east-1:000000000000:function:tgt");
+
+ Message msg = new Message("{\"orderId\":\"o1\"}");
+ msg.setMessageId("m1");
+ msg.setReceiptHandle("rh1");
+ when(sqsService.receiveMessage(anyString(), anyInt(), anyInt(), anyInt(), eq("us-east-1")))
+ .thenReturn(List.of(msg));
+ when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1")))
+ .thenReturn("{\"systemId\":\"S1\"}");
+
+ poller.pollSqs(pipe, "us-east-1");
+
+ ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
+ verify(targetInvoker).invoke(eq(pipe), payload.capture(), eq("us-east-1"));
+ JsonNode delivered = MAPPER.readTree(payload.getValue());
+ assertTrue(delivered.isArray(), "Lambda target must receive the batch array shape");
+ assertEquals(1, delivered.size());
+ assertEquals("S1", delivered.get(0).path("systemId").asText());
+ }
+
@Test
void pollKafka_filtersUsingDecodedPayloadButDeliversOriginalRecord() throws Exception {
Pipe pipe = selfManagedKafkaPipe();
diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java
index 20040d4252..66ee3a4964 100644
--- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java
@@ -248,4 +248,113 @@ class PipesTargetInvokerTest {
"{\"message\": \"user registered\", \"messageType\": \"REGISTRATION\"}",
captor.getValue());
}
+
+ // --- Enrichment: AWS Pipes invokes the enrichment Lambda with the events and forwards its response ---
+
+ private Pipe enrichmentPipe(String region, String enrichmentArn) {
+ Pipe pipe = createPipe("arn:aws:states:" + region + ":000000000000:stateMachine:target", null);
+ pipe.setEnrichment(enrichmentArn);
+ return pipe;
+ }
+
+ @Test
+ void applyEnrichment_invokesLambdaAndReturnsResponse() {
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn");
+ byte[] resp = "{\"systemId\":\"S1\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, null, resp, null, "req"));
+
+ String out = invoker.applyEnrichment(pipe, "[{\"body\":\"{}\"}]", region);
+
+ assertEquals("{\"systemId\":\"S1\"}", out);
+ ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
+ verify(lambdaService).invoke(eq(region), eq("enrich-fn"), payloadCaptor.capture(), eq(InvocationType.RequestResponse));
+ assertEquals("[{\"body\":\"{}\"}]",
+ new String(payloadCaptor.getValue(), java.nio.charset.StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void applyEnrichment_qualifiedArnResolvesFunctionName() {
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn:$LATEST");
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, null, "{}".getBytes(), null, "req"));
+
+ invoker.applyEnrichment(pipe, "[]", region);
+
+ verify(lambdaService).invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void applyEnrichment_noEnrichmentReturnsPayloadUnchanged() {
+ Pipe pipe = createPipe("arn:aws:states:us-east-1:000000000000:stateMachine:target", null);
+ String out = invoker.applyEnrichment(pipe, "[{\"x\":1}]", "us-east-1");
+ assertEquals("[{\"x\":1}]", out);
+ verifyNoInteractions(lambdaService);
+ }
+
+ @Test
+ void applyEnrichment_emptyResponseReturnsNull() {
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn");
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, null, new byte[0], null, "req"));
+ assertNull(invoker.applyEnrichment(pipe, "[]", region));
+ }
+
+ @Test
+ void applyEnrichment_emptyObjectOrArrayResponseSkipsTarget() {
+ // AWS skips the target when the enrichment returns {} or [] (whitespace variants included).
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn");
+ for (String body : new String[]{"{}", "[]", " { } ", "[ ]"}) {
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(
+ 200, null, body.getBytes(java.nio.charset.StandardCharsets.UTF_8), null, "req"));
+ assertNull(invoker.applyEnrichment(pipe, "[]", region),
+ "enrichment response " + body + " should skip the target");
+ }
+ }
+
+ @Test
+ void applyEnrichment_singleElementArrayResponseInvokesTarget() {
+ // [{}] is the explicit "invoke the target with an empty-payload element" form — not skipped.
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn");
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(
+ 200, null, "[{}]".getBytes(java.nio.charset.StandardCharsets.UTF_8), null, "req"));
+ assertEquals("[{}]", invoker.applyEnrichment(pipe, "[]", region));
+ }
+
+ @Test
+ void applyEnrichment_unsupportedTypeThrows() {
+ // Non-Lambda enrichment (e.g. an API destination) is not emulated — applyEnrichment must
+ // fail so the batch is routed to the DLQ rather than delivered unenriched.
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:events:" + region + ":000000000000:api-destination/foo");
+ assertThrows(RuntimeException.class, () -> invoker.applyEnrichment(pipe, "[{\"x\":1}]", region));
+ verifyNoInteractions(lambdaService);
+ }
+
+ @Test
+ void applyEnrichment_lambdaFunctionErrorThrows() {
+ String region = "us-east-1";
+ Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn");
+ when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, "Unhandled", "boom".getBytes(), null, "req"));
+ assertThrows(RuntimeException.class, () -> invoker.applyEnrichment(pipe, "[]", region));
+ }
+
+ @Test
+ void invoke_lambdaTargetFunctionErrorThrows() {
+ // A target Lambda that returns a FunctionError is a failed delivery — invoke must throw so the
+ // poller routes the source record to the DLQ instead of silently deleting it.
+ String region = "us-east-1";
+ Pipe pipe = createPipe("arn:aws:lambda:" + region + ":000000000000:function:my-fn", null);
+ when(lambdaService.invoke(eq(region), eq("my-fn"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, "Unhandled", "boom".getBytes(), null, "req"));
+ assertThrows(RuntimeException.class, () -> invoker.invoke(pipe, "{}", region));
+ }
}