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

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

PipesPoller delivered the raw source record straight to the target; pipe.getEnrichment() was
stored but never invoked. Implement the AWS Pipes source->filter->ENRICHMENT->target flow: when an
enrichment Lambda is configured, invoke it once with the filtered events (bare JSON array) and
forward its response to the target (null/empty response skips the target, per AWS). Also resolve
qualified Lambda ARNs (:$LATEST) in PipesTargetInvoker. Covered by PipesTargetInvokerTest.

* fix(pipes): deliver enrichment result to the target as an event array

EventBridge Pipes delivers events to a target as a batch (JSON array). The
enrichment path forwarded a single-object enrichment response verbatim, so a
target expecting an array (e.g. a Step Functions state machine with
InputPath "$.[0]") received an object and resolved null. Wrap a non-array
enrichment response in a one-element array before target delivery. Covered by
PipesPollerTest.asEventArray*.

(cherry picked from commit f160f66857c2362e3f1bad3bbfdb025396b281a0)

* fix(pipes): treat a target/enrichment Lambda FunctionError as failed delivery

invokeLambda (the Lambda target path) discarded the InvokeResult, so a target
Lambda that returned a FunctionError (unhandled exception, throttle) was treated
as a successful delivery and the source record was consumed. Surface it (throw)
so the caller routes the record to the DLQ. Also switch applyEnrichment's
FunctionError failure from a bare RuntimeException to AwsException, per the
service-layer convention. Covered by PipesTargetInvokerTest.invoke_lambdaTargetFunctionErrorThrows.

* fix(pipes): only array-wrap the enrichment response for Lambda targets

deliverEnrichedBatch wrapped the enrichment response in a JSON batch array before invoking
the target unconditionally. That is correct for a Lambda target (which expects an
SQSRecord[]-style batch) but corrupts every other target — a Step Functions execution, SQS
message, SNS publish or EventBridge event must receive the raw enrichment response. Gate the
wrapping on isLambdaTarget, matching the non-enrichment delivery path. Adds pollSqs tests for
both a non-Lambda (raw) and a Lambda (wrapped) target.

* fix(pipes): align enrichment empty/unsupported handling with AWS + document SQS-only wiring

Review feedback:
- applyEnrichment now also skips the target when the Lambda enrichment returns an
  empty object {} or empty array [] (whitespace variants included), matching AWS;
  a non-empty array such as [{}] still invokes the target.
- A non-Lambda enrichment type (API destination, API Gateway, SFN Express) now
  fails the batch to the DLQ instead of silently delivering the unenriched payload.
- Documented that enrichment is currently applied only on the SQS source path
  (Kinesis/DynamoDB Streams/Kafka bypass it) in code and docs/services/pipes.md.
- Generalized a comment that named a specific downstream consumer.
- Tests: empty {}/[] skip, [{}] invokes, unsupported type throws.

* docs: regenerate action tables
This commit is contained in:
Alex Banna authored and GitHub committed 2026-07-09 00:14:53 -05:00
1 parent 45ed00ebc7
commit 0e85ac92c7
5 files changed
+383 -3

No files matched your search

@@ -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) {
@@ -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);