fix(pipes): apply an enrichment on a DynamoDB stream source and deliver its events as AWS does (#7055)

* fix(pipes): apply an enrichment on a DynamoDB stream source and deliver its events as AWS does

A pipe with a DynamoDB stream source, a Lambda enrichment and an event bus target put nothing on the
bus a rule could use: the stream path skipped the enrichment, an array answer reached the target as
one payload, Source and DetailType written as JSON paths went out as the literal text, and a template
of one placeholder naming a string put that string on the bus in quotes.

- The stream path runs the enrichment through the SQS path's step, once per filtered batch. Disposal
  stays each source's: SQS deletes its messages, a stream commits its position.
- An array answer reaches an event bus, SQS queue or SNS topic one element at a time. A Lambda or a
  state machine takes it whole. EventBridge User Guide, "Amazon EventBridge Pipes batching and
  concurrency": "Input transformers are applied separately on each individual JSON record in the
  array", and a target with no batch API, "such as Lambda and Step Functions", gets "the entire JSON
  array". https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes-batching-concurrency.html
- An event bus target's Source and DetailType, written as a JSON path, are read off the event before
  the template renders. "Amazon EventBridge Pipes event bus target": they "support dynamic JSON path
  syntax" and "can't reference new or transformed values resulting from input transformation". A path
  naming nothing fails the delivery, so no event reaches a rule under a literal or empty type.
  https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes-event-target.html
- A template of exactly one placeholder renders a string verbatim, which is what AWS does with
  <$.Detail> naming a serialized object; quotes added here made PutEvents refuse it as MalformedDetail.
  A placeholder inside a larger template renders as before.

Kinesis and Kafka sources still deliver straight to the target, as docs/services/pipes.md says.

Test: PipesStreamEnrichmentDockerIntegrationTest runs a real function behind a table's stream, with a
filter, and a rule on the bus matching a field of the detail reaches a queue. Without the fix it times
out with no event on the queue. PipesPollerTest and PipesTargetInvokerTest pin each rule.

* fix(pipes): fail an enrichment batch past the target's limit, and share the dynamic parameter resolver

An enrichment answering more than 10 events for an event bus, queue or topic
fails the batch without invoking the target, as AWS does, since 10 is what
those targets take in one request; the batch goes to the dead-letter queue
or is read again. The event bus Source and DetailType resolve through the
same method as a Redshift parameter, so a value counts as a path only when
the whole of it is one. pollSqs deletes a delivered batch's messages in one
place, and the Docker test uses SqsTestQueue and DynamoDbRequests.

* fix(pipes): deliver an enrichment array to Redshift whole, and skip the target on an empty string

Redshift has no batch API, so an enrichment's array reaches it in one BatchExecuteStatement as
before; only an event bus, queue or topic takes one event per element under the limit of 10. An
enrichment Lambda answering "" is an empty response, as AWS lists it, and invokes no target.
This commit is contained in:
Charles Swanberg authored and GitHub committed 2026-11-10 13:49:49 -04:00
1 parent 6038fe7fc9
commit a5ab677d6b
6 files changed
+695 -66

No files matched your search

@@ -42,6 +42,11 @@ public class PipesPoller implements Resettable {
private static final Logger LOG = Logger.getLogger(PipesPoller.class);
private static final long POLL_INTERVAL_MS = 1000;
private static final int DEFAULT_BATCH_SIZE = 10;
/**
* An event bus, queue or topic takes at most this many events in one request, and AWS does not
* invoke such a target with an enrichment's array past it: the batch fails instead.
*/
private static final int ENRICHED_BATCH_LIMIT = 10;
private final Vertx vertx;
private final SqsService sqsService;
@@ -205,24 +210,16 @@ public class PipesPoller implements Resettable {
// 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);
if (deliverEnrichedBatch(pipe, filtered, region)) {
deleteMatchedMessages(pipe, queueUrl, messages, matchedMessageIds, region);
}
return;
}
if (isLambdaTarget(pipe)) {
String eventJson = wrapRecords(filtered);
boolean delivered = invokeWithDlq(pipe, eventJson, 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());
}
}
}
if (invokeWithDlq(pipe, eventJson, region)) {
deleteMatchedMessages(pipe, queueUrl, messages, matchedMessageIds, region);
}
} else {
Map<String, Message> messagesById = new HashMap<>();
@@ -246,6 +243,21 @@ public class PipesPoller implements Resettable {
}
}
/** Deletes the messages a delivered batch consumed, the ones the filter admitted. */
private void deleteMatchedMessages(Pipe pipe, String queueUrl, List<Message> messages,
Set<String> matchedMessageIds, String region) {
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());
}
}
}
}
void pollKinesis(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamName = kinesisStreamName(pipe.getSource());
@@ -380,7 +392,7 @@ public class PipesPoller implements Resettable {
}
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(recordNodes, pipe.getSourceParameters());
// ponytail: a partially delivered non-Lambda batch is redelivered whole (at-least-once).
if (!filtered.isEmpty() && deliverRecords(pipe, filtered, region) > 0) {
if (!filtered.isEmpty() && !disposeDynamoDbBatch(pipe, filtered, region)) {
LOG.warnv("Pipe {0}: DynamoDB Stream batch on {1} was neither delivered nor sent to a DLQ, "
+ "retrying it next poll", pipe.getName(), shardId);
return;
@@ -388,6 +400,12 @@ public class PipesPoller implements Resettable {
committed.put(shardId, records.get(records.size() - 1).sequenceNumber());
}
private boolean disposeDynamoDbBatch(Pipe pipe, List<JsonNode> filtered, String region) {
return hasEnrichment(pipe)
? deliverEnrichedBatch(pipe, filtered, region)
: deliverRecords(pipe, filtered, region) == 0;
}
void pollKafka(Pipe pipe, String region) {
List<KafkaRecordDto> records = kafkaConsumerManager.poll(pipe);
if (records.isEmpty()) {
@@ -562,10 +580,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.
// Enrichment (source → filter → ENRICHMENT → target) is applied on the SQS and DynamoDB Streams
// source paths (see deliverEnrichedBatch). Kinesis 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();
}
@@ -594,44 +612,61 @@ public class PipesPoller implements Resettable {
}
/**
* 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.
* Runs the pipe enrichment once over the filtered batch and forwards its response to the target.
* The enrichment Lambda receives the events as a bare JSON array; a null/empty enrichment response
* skips the target (AWS behavior) while the batch still counts as delivered. A failure sends the
* batch to the DLQ. Returns whether the batch is disposed of, which the source acts on in its own
* way: SQS deletes its messages and a stream commits its position.
*/
private void deliverEnrichedBatch(Pipe pipe, List<JsonNode> filtered, List<Message> messages,
Set<String> matchedMessageIds, String queueUrl, String region) {
private boolean deliverEnrichedBatch(Pipe pipe, List<JsonNode> filtered, 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);
for (String targetPayload : enrichedTargetPayloads(pipe, enriched)) {
targetInvoker.invoke(pipe, targetPayload, region);
}
}
delivered = true;
return 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);
return 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());
}
}
}
}
/**
* What each target invocation takes of an enrichment's response. A target with no batch API, Lambda,
* Step Functions or Redshift, gets the entire JSON array in one request; an event bus, queue or topic
* gets one event per element, each rendered through the target's template apart, and an array past
* the target's batch limit fails the batch, as AWS invokes no target with it. A response that is no
* array is one event, raw, and only a Lambda target expects it in the batch (JSON array) shape.
*/
private List<String> enrichedTargetPayloads(Pipe pipe, String enriched) {
if (isLambdaTarget(pipe)) {
return List.of(asEventArray(objectMapper, enriched));
}
if (isStateMachineTarget(pipe) || PipesTargetInvoker.isRedshiftTarget(pipe.getTarget())) {
return List.of(enriched);
}
JsonNode response;
try {
response = objectMapper.readTree(enriched);
} catch (JsonProcessingException e) {
LOG.debugv("Pipe enrichment response was not JSON, forwarding it as one event: {0}",
e.getOriginalMessage());
return List.of(enriched);
}
if (!response.isArray()) {
return List.of(enriched);
}
if (response.size() > ENRICHED_BATCH_LIMIT) {
throw new AwsException("InternalException", "Pipe enrichment answered " + response.size()
+ " events, more than the " + ENRICHED_BATCH_LIMIT + " the target takes in one batch", 500);
}
List<String> elements = new ArrayList<>(response.size());
response.forEach(element -> elements.add(element.toString()));
return elements;
}
private String bareArray(List<JsonNode> records) {
@@ -833,6 +868,10 @@ public class PipesPoller implements Resettable {
return targetArn.contains(":lambda:") || targetArn.contains(":function:");
}
private static boolean isStateMachineTarget(Pipe pipe) {
return pipe.getTarget().contains(":states:");
}
private static boolean isKafkaSource(String sourceArn) {
return sourceArn.startsWith("smk://") || sourceArn.contains(":kafka:");
}
@@ -95,6 +95,8 @@ public class PipesTargetInvoker {
}
JsonNode tp = pipe.getTargetParameters();
// A target's dynamic parameters read the event as it arrived, never what the template renders.
String event = payload;
if (tp != null && tp.has("InputTemplate")) {
payload = applyInputTemplate(tp.get("InputTemplate").asText(), payload);
}
@@ -106,7 +108,7 @@ public class PipesTargetInvoker {
} else if (targetArn.contains(":sns:")) {
invokeSns(targetArn, payload, region);
} else if (targetArn.contains(":events:")) {
invokeEventBridge(targetArn, payload, region, tp);
invokeEventBridge(targetArn, payload, region, tp, event);
} else if (targetArn.contains(":states:")) {
invokeStepFunctions(targetArn, payload, region);
} else {
@@ -144,12 +146,15 @@ public class PipesTargetInvoker {
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.
// AWS also skips the target when the enrichment returns an empty string "", an empty
// object {} or an 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()) {
boolean empty = node.isTextual()
? node.asText().isEmpty()
: node.isContainerNode() && node.isEmpty();
if (empty) {
return null;
}
} catch (JsonProcessingException e) {
@@ -205,7 +210,7 @@ public class PipesTargetInvoker {
LOG.debugv("Pipe delivered to SNS: {0}", arn);
}
private void invokeEventBridge(String arn, String payload, String region, JsonNode tp) {
private void invokeEventBridge(String arn, String payload, String region, JsonNode tp, String event) {
String busName = AwsArnUtils.resourceIfArnFor(arn, "events")
.filter(resource -> resource.startsWith("event-bus/"))
.map(resource -> resource.substring("event-bus/".length()))
@@ -216,10 +221,11 @@ public class PipesTargetInvoker {
if (tp != null) {
JsonNode ebParams = tp.path("EventBridgeEventBusParameters");
if (ebParams.has("Source")) {
source = ebParams.get("Source").asText();
source = resolveDynamicParameter(ebParams.get("Source").asText(), event, "target parameter Source");
}
if (ebParams.has("DetailType")) {
detailType = ebParams.get("DetailType").asText();
detailType = resolveDynamicParameter(ebParams.get("DetailType").asText(), event,
"target parameter DetailType");
}
}
Map<String, Object> entry = Map.of(
@@ -278,7 +284,7 @@ public class PipesTargetInvoker {
null, sqls, text(parameters, "StatementName"),
parameters.path("WithEvent").isBoolean() ? parameters.get("WithEvent").asBoolean() : null);
redshiftSubmitter.submit(targetArn, statement, pipe.getRoleArn(), account, targetRegion,
value -> resolveRedshiftParameter(value, payload),
value -> resolveDynamicParameter(value, payload, "Redshift target path"),
permissions -> redshiftTargetAuthorizer.refusal(
PIPES_PRINCIPAL, pipe.getRoleArn(), account, pipe.getArn(), permissions));
LOG.debugv("Pipe delivered to Redshift Data API: {0}", targetArn);
@@ -289,14 +295,24 @@ public class PipesTargetInvoker {
return node.isTextual() ? node.asText() : null;
}
private String resolveRedshiftParameter(String value, String payload) {
/**
* A dynamic target parameter's value: as written, or where the whole value is a JSON path, what
* that path names in {@code payload}, a JSON string as its text. A path naming nothing fails the
* delivery, named as {@code what}, so nothing reaches the target under a literal or empty value.
*/
private String resolveDynamicParameter(String value, String payload, String what) {
if (value == null || !DYNAMIC_PARAMETER_PATH.matcher(value).matches()) {
return value;
}
String extracted = extractJsonPath(value, payload);
if (extracted == null) {
throw new AwsException("ValidationException", "Cannot resolve Redshift target path: " + value, 400);
throw new AwsException("ValidationException", "Cannot resolve " + what + ": " + value, 400);
}
return unquoted(extracted);
}
/** The text of a JSON string as {@link #extractJsonPath} gives it; any other JSON as it is. */
private String unquoted(String extracted) {
try {
JsonNode node = objectMapper.readTree(extracted);
return node.isTextual() ? node.asText() : node.toString();
@@ -307,6 +323,10 @@ public class PipesTargetInvoker {
String applyInputTemplate(String template, String payload) {
Matcher m = TEMPLATE_PLACEHOLDER.matcher(template);
// A template that is one placeholder substitutes a string verbatim: <$.Detail> naming a serialized
// object puts that object on the bus, where added quotes would be refused as MalformedDetail.
boolean wholeTemplate = m.matches();
m.reset();
String ingestionTime = objectMapper.valueToTree(Instant.now().toString()).toString();
StringBuilder sb = new StringBuilder();
while (m.find()) {
@@ -317,6 +337,8 @@ public class PipesTargetInvoker {
: extractJsonPath(jsonPath, payload);
if (value == null) {
value = quoted ? "" : objectMapper.valueToTree("").toString();
} else if (wholeTemplate) {
value = unquoted(value);
} else if (quoted && value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
// A JSON string placeholder already has quotes from extractJsonPath. The
// surrounding template quotes must remain the only pair of quotes.