From a5ab677d6bdeb93b0c090b27fb2e8e304cebe8ac Mon Sep 17 00:00:00 2001 From: Charles Swanberg Date: Tue, 10 Nov 2026 12:49:49 -0500 Subject: [PATCH] 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. --- docs/services/pipes.md | 45 +++- .../floci/aws/services/pipes/PipesPoller.java | 129 +++++---- .../services/pipes/PipesTargetInvoker.java | 44 ++- .../aws/services/pipes/PipesPollerTest.java | 250 ++++++++++++++++++ ...StreamEnrichmentDockerIntegrationTest.java | 205 ++++++++++++++ .../pipes/PipesTargetInvokerTest.java | 88 +++++- 6 files changed, 695 insertions(+), 66 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/pipes/PipesStreamEnrichmentDockerIntegrationTest.java diff --git a/docs/services/pipes.md b/docs/services/pipes.md index a9f5cdf795..cb2c688afb 100644 --- a/docs/services/pipes.md +++ b/docs/services/pipes.md @@ -92,6 +92,7 @@ Floci emulates EventBridge Pipes with the following supported source and target - Lambda functions - SQS queues - SNS topics +- EventBridge event buses - Kinesis streams - Step Functions state machines - Amazon Redshift clusters and Redshift Serverless workgroups, through the Data API (see below) @@ -174,17 +175,45 @@ the field on a source its parameter block does not describe, for example ## 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. +**Lambda** enrichments on **SQS** and **DynamoDB Streams** sources: the filtered batch is invoked +synchronously (`RequestResponse`), once per batch, as a bare JSON array, 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 +- **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). +- **An array response is delivered by target.** An event bus, SQS queue or SNS topic takes one event + per element, with the target's `InputTemplate` rendered on each element apart. A Lambda function, a + Step Functions state machine or a Redshift target takes the whole response in one request. An array + of more than 10 elements for an event bus, queue or topic fails the batch without invoking the + target, as on AWS, where 10 is what those targets take in one request. A failure on any element + fails the batch, and a retried batch runs through the enrichment again, so elements already + delivered are delivered again. - **A Lambda enrichment `FunctionError` fails the batch** — the source records are routed to the - pipe's dead-letter queue rather than silently consumed. + pipe's dead-letter queue rather than silently consumed. Where the pipe has no dead-letter queue or + the queue refuses them, an SQS message becomes visible again and a DynamoDB stream batch is read + again on the next poll. +- **A batch in flight when Floci stops is not finished.** A stop interrupts a running enrichment, + which counts as a function error, so the batch goes to the dead-letter queue where the queue still + takes it; elements already delivered stay delivered. Nothing else of the batch is kept: a DynamoDB + stream's progress is held in memory, so after a restart under persistent storage a `TRIM_HORIZON` + pipe reads the stream's retained records again, enrichment included, and a `LATEST` pipe pins past + them, so records it had not delivered are not delivered. An SQS message not yet deleted comes back + once its visibility timeout ends. Under `memory` storage the sources go with the process. - **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. +- **Kinesis and Kafka sources do not apply an enrichment.** They deliver filtered records straight to + the target; an enrichment configured on those sources is not yet applied. + +## Target Parameters + +- An event bus target's `EventBridgeEventBusParameters` `Source` and `DetailType`, written as a JSON + path (`$.Source`), are read off the event the target receives, the enrichment's element where the + pipe has an enrichment, before the `InputTemplate` renders. A value that is not wholly a JSON path + stays as written. A path that names nothing fails the delivery, which is retried or sent to the + dead-letter queue like any other failure. +- An `InputTemplate` that is exactly one placeholder, such as `<$.Detail>`, renders a string as its + own text with no quotes added, so a serialized object reaches an event bus as that object. A + placeholder inside a larger template renders a string with quotes where the template gives none: + `{"id": <$.messageId>}` renders as `{"id": "m1"}`. diff --git a/src/main/java/io/floci/aws/services/pipes/PipesPoller.java b/src/main/java/io/floci/aws/services/pipes/PipesPoller.java index b92c76e461..9868b0e8e5 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesPoller.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesPoller.java @@ -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 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 messages, + Set 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 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 filtered, String region) { + return hasEnrichment(pipe) + ? deliverEnrichedBatch(pipe, filtered, region) + : deliverRecords(pipe, filtered, region) == 0; + } + void pollKafka(Pipe pipe, String region) { List records = kafkaConsumerManager.poll(pipe); if (records.isEmpty()) { @@ -562,10 +580,10 @@ public class PipesPoller implements Resettable { // ──────────────────────────── Invocation & DLQ ──────────────────────────── private int deliverRecords(Pipe pipe, List 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 filtered, List messages, - Set matchedMessageIds, String queueUrl, String region) { + private boolean deliverEnrichedBatch(Pipe pipe, List 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 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 elements = new ArrayList<>(response.size()); + response.forEach(element -> elements.add(element.toString())); + return elements; } private String bareArray(List 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:"); } diff --git a/src/main/java/io/floci/aws/services/pipes/PipesTargetInvoker.java b/src/main/java/io/floci/aws/services/pipes/PipesTargetInvoker.java index 25a8cac50a..e0309469ba 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesTargetInvoker.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesTargetInvoker.java @@ -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 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. diff --git a/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java b/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java index b286b13345..3025621aa1 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java @@ -67,6 +67,8 @@ class PipesPollerTest { "arn:aws:dynamodb:us-east-1:000000000000:table/orders/stream/2026-09-01T00:00:00.000"; private static final String SHARD_ID = "shardId-0000000001-00000000001"; private static final String DLQ_ARN = "arn:aws:sqs:us-east-1:000000000000:pipe-dlq"; + private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/orders-bus"; + private static final String ENRICHMENT_ARN = "arn:aws:lambda:us-east-1:000000000000:function:enrich"; @Mock private Vertx vertx; @Mock private SqsService sqsService; @@ -237,6 +239,59 @@ class PipesPollerTest { assertEquals("S1", delivered.get(0).path("systemId").asText()); } + @Test + void pollSqs_enrichmentArrayReachesAnEventBusOneElementAtATime() throws Exception { + Pipe pipe = enrichedSqsPipe("arn:aws:events:us-east-1:000000000000:event-bus/orders-bus"); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2},{\"n\":3}]"); + + poller.pollSqs(pipe, "us-east-1"); + + assertEquals(List.of("{\"n\":1}", "{\"n\":2}", "{\"n\":3}"), targetPayloads(pipe)); + verify(sqsService).deleteMessage(anyString(), eq("rh1"), eq("us-east-1")); + } + + @Test + void pollSqs_enrichmentArrayReachesAQueueAndATopicOneElementAtATime() throws Exception { + for (String target : List.of("arn:aws:sqs:us-east-1:000000000000:tgt", "arn:aws:sns:us-east-1:000000000000:tgt")) { + Pipe pipe = enrichedSqsPipe(target); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2}]"); + + poller.pollSqs(pipe, "us-east-1"); + + assertEquals(List.of("{\"n\":1}", "{\"n\":2}"), targetPayloads(pipe), target); + } + } + + @Test + void pollSqs_enrichmentArrayReachesALambdaOrAStateMachineWhole() throws Exception { + for (String target : List.of("arn:aws:lambda:us-east-1:000000000000:function:tgt", + "arn:aws:states:us-east-1:000000000000:stateMachine:tgt")) { + Pipe pipe = enrichedSqsPipe(target); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2}]"); + + poller.pollSqs(pipe, "us-east-1"); + + assertEquals(List.of("[{\"n\":1},{\"n\":2}]"), targetPayloads(pipe), target); + } + } + + @Test + void pollSqs_enrichmentArrayReachesRedshiftWholeHoweverLongItIs() throws Exception { + for (String target : List.of("arn:aws:redshift:us-east-1:000000000000:cluster:warehouse", + "arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/warehouse")) { + Pipe pipe = enrichedSqsPipe(target); + String eleven = elements(11); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))).thenReturn(eleven); + + poller.pollSqs(pipe, "us-east-1"); + + assertEquals(List.of(eleven), targetPayloads(pipe), target); + } + } + @Test void pollKafka_filtersUsingDecodedPayloadButDeliversOriginalRecord() throws Exception { Pipe pipe = selfManagedKafkaPipe(); @@ -638,6 +693,155 @@ class PipesPollerTest { } } + @Test + void aStreamBatchIsEnrichedOnceWithItsFilteredRecords() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + pipe.setSourceParameters(MAPPER.readTree(""" + {"DynamoDBStreamParameters":{"StartingPosition":"TRIM_HORIZON"}, + "FilterCriteria":{"Filters":[ + {"Pattern":"{\\"dynamodb\\":{\\"NewImage\\":{\\"status\\":{\\"S\\":[\\"active\\"]}}}}"}]}}""")); + streams.shard.add(ddbRecord("001", "active")); + streams.shard.add(ddbRecord("002", "inactive")); + streams.shard.add(ddbRecord("003", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))).thenReturn("{\"n\":1}"); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + JsonNode events = MAPPER.readTree(enrichmentInputs(pipe).get(0)); + assertEquals(1, enrichmentInputs(pipe).size()); + assertTrue(events.isArray(), "the enrichment takes a bare array"); + assertEquals(2, events.size()); + for (JsonNode event : events) { + assertEquals("INSERT", event.path("eventName").asText()); + assertEquals("order-1", event.at("/dynamodb/Keys/pk/S").asText()); + assertEquals(STREAM_ARN, event.path("eventSourceARN").asText()); + } + assertEquals("001", events.get(0).at("/dynamodb/SequenceNumber").asText()); + assertEquals("003", events.get(1).at("/dynamodb/SequenceNumber").asText()); + assertEquals(List.of("{\"n\":1}"), targetPayloads(pipe)); + } + + @Test + void anEnrichmentArrayOfThreeReachesAnEventBusAsThreeInvocations() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2},{\"n\":3}]"); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + assertEquals(List.of("{\"n\":1}", "{\"n\":2}", "{\"n\":3}"), targetPayloads(pipe)); + assertEquals(1, enrichmentInputs(pipe).size(), "a delivered batch is committed"); + } + + @Test + void anEnrichmentArrayOnAStreamReachesALambdaOrAStateMachineWhole() throws Exception { + for (String target : List.of("arn:aws:lambda:us-east-1:000000000000:function:tgt", + "arn:aws:states:us-east-1:000000000000:stateMachine:tgt")) { + FakeStreamReader shard = new FakeStreamReader(); + PipesPoller streamPoller = pollerOver(shard); + Pipe pipe = enrichedDynamoDbPipe(target); + shard.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2}]"); + + streamPoller.startPolling(pipe); + streamPoller.pollDynamoDbStreams(pipe, "us-east-1"); + + assertEquals(List.of("[{\"n\":1},{\"n\":2}]"), targetPayloads(pipe), target); + } + } + + @Test + void anEmptyEnrichmentAnswerInvokesNoTargetAndCommitsTheBatch() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))).thenReturn(null); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + verify(targetInvoker, never()).invoke(any(), anyString(), anyString()); + assertEquals(1, enrichmentInputs(pipe).size(), "the stream's position moved past the batch"); + } + + @Test + void anEnrichmentFunctionErrorWithNoDeadLetterQueueRereadsTheBatch() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenThrow(new RuntimeException("function error")) + .thenReturn(null); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + verify(targetInvoker, never()).invoke(any(), anyString(), anyString()); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + List inputs = enrichmentInputs(pipe); + assertEquals(2, inputs.size(), "read once more after the error, then committed"); + assertEquals(inputs.get(0), inputs.get(1)); + } + + @Test + void anEnrichmentFunctionErrorSendsTheBatchToTheDeadLetterQueueAndCommits() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + pipe.setSourceParameters(MAPPER.readTree( + "{\"DynamoDBStreamParameters\":{\"DeadLetterConfig\":{\"Arn\":\"" + DLQ_ARN + "\"}}}")); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenThrow(new RuntimeException("function error")); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + List inputs = enrichmentInputs(pipe); + assertEquals(1, inputs.size(), "a batch the queue took is committed"); + verify(sqsService).sendMessage(contains("pipe-dlq"), eq(inputs.get(0)), eq(0), eq("us-east-1")); + verify(targetInvoker, never()).invoke(any(), anyString(), anyString()); + } + + @Test + void anEnrichmentArrayPastTheTargetsBatchLimitFailsTheBatchWithoutInvokingTheTarget() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + pipe.setSourceParameters(MAPPER.readTree( + "{\"DynamoDBStreamParameters\":{\"DeadLetterConfig\":{\"Arn\":\"" + DLQ_ARN + "\"}}}")); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))).thenReturn(elements(11)); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + verify(targetInvoker, never()).invoke(any(), anyString(), anyString()); + List inputs = enrichmentInputs(pipe); + assertEquals(1, inputs.size(), "the batch the queue took is committed"); + verify(sqsService).sendMessage(contains("pipe-dlq"), eq(inputs.get(0)), eq(0), eq("us-east-1")); + } + + @Test + void aFailedElementFailsTheBatchAndItsRetryRunsThroughTheEnrichmentAgain() throws Exception { + Pipe pipe = enrichedDynamoDbPipe(BUS_ARN); + streams.shard.add(ddbRecord("001", "active")); + when(targetInvoker.applyEnrichment(eq(pipe), anyString(), eq("us-east-1"))) + .thenReturn("[{\"n\":1},{\"n\":2}]"); + doNothing().doThrow(new RuntimeException("target down")).doNothing() + .when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1")); + + poller.startPolling(pipe); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + poller.pollDynamoDbStreams(pipe, "us-east-1"); + + assertEquals(2, enrichmentInputs(pipe).size()); + assertEquals(List.of("{\"n\":1}", "{\"n\":2}", "{\"n\":1}", "{\"n\":2}"), targetPayloads(pipe)); + } + private Pipe dynamoDbPipe(String dynamoDbStreamParameters) throws Exception { Pipe pipe = new Pipe(); pipe.setName("orders-stream-pipe"); @@ -664,6 +868,51 @@ class PipesPollerTest { null, null, null, "us-east-1"); } + private Pipe enrichedDynamoDbPipe(String target) throws Exception { + Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"TRIM_HORIZON\"}"); + pipe.setEnrichment(ENRICHMENT_ARN); + pipe.setTarget(target); + return pipe; + } + + private Pipe enrichedSqsPipe(String target) { + Pipe pipe = new Pipe(); + pipe.setName("enrich-sqs"); + pipe.setSource("arn:aws:sqs:us-east-1:000000000000:src-queue"); + pipe.setEnrichment(ENRICHMENT_ARN); + pipe.setTarget(target); + + 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)); + return pipe; + } + + /** An enrichment response of {@code count} events, {@code [{"n":1},...]}. */ + private static String elements(int count) { + StringBuilder array = new StringBuilder("["); + for (int n = 1; n <= count; n++) { + array.append(n > 1 ? "," : "").append("{\"n\":").append(n).append("}"); + } + return array.append("]").toString(); + } + + /** What the enrichment was invoked with, in invocation order. */ + private List enrichmentInputs(Pipe pipe) { + ArgumentCaptor inputs = ArgumentCaptor.forClass(String.class); + verify(targetInvoker, atLeastOnce()).applyEnrichment(eq(pipe), inputs.capture(), eq("us-east-1")); + return inputs.getAllValues(); + } + + /** What the target was invoked with, in invocation order. */ + private List targetPayloads(Pipe pipe) { + ArgumentCaptor payloads = ArgumentCaptor.forClass(String.class); + verify(targetInvoker, atLeastOnce()).invoke(eq(pipe), payloads.capture(), eq("us-east-1")); + return payloads.getAllValues(); + } + /** A GetRecords {@code Records[]} element as the native engine returns it. */ private static DynamoDbStreamReader.Record ddbRecord(String sequenceNumber, String status) { ObjectNode awsRecord = MAPPER.createObjectNode() @@ -673,6 +922,7 @@ class PipesPollerTest { .put("eventSource", "aws:dynamodb") .put("awsRegion", "us-east-1"); ObjectNode dynamodb = awsRecord.putObject("dynamodb"); + dynamodb.putObject("Keys").putObject("pk").put("S", "order-1"); dynamodb.putObject("NewImage").putObject("status").put("S", status); dynamodb.put("SequenceNumber", sequenceNumber).put("SizeBytes", 50).put("StreamViewType", "NEW_IMAGE"); return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord); diff --git a/src/test/java/io/floci/aws/services/pipes/PipesStreamEnrichmentDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/pipes/PipesStreamEnrichmentDockerIntegrationTest.java new file mode 100644 index 0000000000..afc23d3ad8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/pipes/PipesStreamEnrichmentDockerIntegrationTest.java @@ -0,0 +1,205 @@ +package io.floci.aws.services.pipes; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.sqs.SqsService; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.DynamoDbRequests; +import io.floci.aws.testing.SqsTestQueue; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A table's stream through a real enrichment function onto an event bus: a row the Pipe's filter admits + * becomes the two events the function answers, each with the source and detail type it named and its + * serialized detail an object a rule can match on, as the Pipes pages describe. + */ +@QuarkusTest +class PipesStreamEnrichmentDockerIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/pipe-role"; + private static final Duration DEADLINE = Duration.ofSeconds(90); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Inject + SqsService sqsService; + + @BeforeEach + void requireDocker() throws Exception { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), + "Docker daemon must be available for the enrichment function"); + } + + @Test + void aRowBecomesTheEventsItsEnrichmentAnswers() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String table = "pipe-stream-" + suffix; + String function = "pipe-enrich-" + suffix; + String bus = "pipe-bus-" + suffix; + String rule = "pipe-rule-" + suffix; + String pipe = "pipe-stream-enrich-" + suffix; + SqsTestQueue matched = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "pipe-matched-"); + SqsTestQueue deadLetters = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "pipe-dlq-"); + try { + String streamArn = DynamoDbRequests.ddb("CreateTable", """ + { + "TableName": "%s", + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"} + ], + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ], + "BillingMode": "PAY_PER_REQUEST", + "StreamSpecification": {"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"} + } + """.formatted(table)).statusCode(200).extract().jsonPath().getString("TableDescription.LatestStreamArn"); + createFunction(function); + events("CreateEventBus", "{\"Name\": \"%s\"}".formatted(bus)); + events("PutRule", """ + { + "Name": "%s", + "EventBusName": "%s", + "EventPattern": "{\\"source\\":[\\"orders\\"],\\"detail\\":{\\"rowId\\":[\\"r1\\"]}}", + "State": "ENABLED" + } + """.formatted(rule, bus)); + events("PutTargets", """ + { + "Rule": "%s", + "EventBusName": "%s", + "Targets": [{"Id": "1", "Arn": "%s"}] + } + """.formatted(rule, bus, matched.arn())); + createPipe(pipe, streamArn, function, bus, deadLetters.arn()); + + putItem(table, "EVENT#r1"); + putItem(table, "OTHER#r2"); + + List events = List.of(matched.awaitJson(DEADLINE), matched.awaitJson(DEADLINE)); + + for (JsonNode event : events) { + assertEquals("orders", event.path("source").asText(), event.toString()); + assertEquals("Order Written", event.path("detail-type").asText(), event.toString()); + assertTrue(event.path("detail").isObject(), event.toString()); + assertEquals("r1", event.at("/detail/rowId").asText(), event.toString()); + } + assertEquals(3, events.get(0).at("/detail/part").asInt() + events.get(1).at("/detail/part").asInt(), + "one event per entry the function answered"); + assertTrue(matched.receive().isEmpty(), "the filter keeps the other row out"); + assertTrue(deadLetters.receive().isEmpty(), "nothing failed"); + } finally { + given().when().delete("/v1/pipes/" + pipe); + given().when().delete("/2015-03-31/functions/" + function); + matched.delete(); + deadLetters.delete(); + } + } + + private void createPipe(String pipe, String streamArn, String function, String bus, String deadLetterArn) { + given() + .contentType("application/json") + .body(""" + { + "Source": "%s", + "Enrichment": "arn:aws:lambda:%s:%s:function:%s", + "Target": "arn:aws:events:%s:%s:event-bus/%s", + "RoleArn": "%s", + "DesiredState": "RUNNING", + "SourceParameters": { + "DynamoDBStreamParameters": { + "StartingPosition": "TRIM_HORIZON", + "BatchSize": 10, + "DeadLetterConfig": {"Arn": "%s"} + }, + "FilterCriteria": { + "Filters": [{"Pattern": "{\\"dynamodb\\":{\\"Keys\\":{\\"sk\\":{\\"S\\":[{\\"prefix\\":\\"EVENT#\\"}]}}}}"}] + } + }, + "TargetParameters": { + "EventBridgeEventBusParameters": {"Source": "$.Source", "DetailType": "$.DetailType"}, + "InputTemplate": "<$.Detail>" + } + } + """.formatted(streamArn, REGION, ACCOUNT, function, REGION, ACCOUNT, bus, ROLE, deadLetterArn)) + .when() + .post("/v1/pipes/" + pipe) + .then() + .statusCode(200); + } + + private void createFunction(String function) throws Exception { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Role": "%s", + "Handler": "index.handler", + "Timeout": 10, + "Code": {"ZipFile": "%s"} + } + """.formatted(function, ROLE, enrichmentZipBase64())) + .when() + .post("/2015-03-31/functions") + .then() + .statusCode(201); + } + + private static String enrichmentZipBase64() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(bytes)) { + zip.putNextEntry(new ZipEntry("index.js")); + zip.write(""" + exports.handler = async (records) => records.flatMap((record) => { + const rowId = record.dynamodb.Keys.sk.S.split('#')[1]; + return [1, 2].map((part) => ({ + Source: 'orders', + DetailType: 'Order Written', + Detail: JSON.stringify({rowId, part}), + })); + }); + """.getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + return Base64.getEncoder().encodeToString(bytes.toByteArray()); + } + + private static void putItem(String table, String sortKey) { + DynamoDbRequests.ddb("PutItem", """ + {"TableName": "%s", "Item": {"pk": {"S": "orders"}, "sk": {"S": "%s"}}} + """.formatted(table, sortKey)).statusCode(200); + } + + private static void events(String action, String body) { + given() + .header("X-Amz-Target", "AWSEvents." + action) + .contentType("application/x-amz-json-1.1") + .body(body.getBytes(StandardCharsets.UTF_8)) + .when() + .post("/") + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/floci/aws/services/pipes/PipesTargetInvokerTest.java b/src/test/java/io/floci/aws/services/pipes/PipesTargetInvokerTest.java index 29ff3ca67e..439a6c1c73 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesTargetInvokerTest.java +++ b/src/test/java/io/floci/aws/services/pipes/PipesTargetInvokerTest.java @@ -40,6 +40,7 @@ import static org.mockito.Mockito.*; class PipesTargetInvokerTest { private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/orders-bus"; @Mock private LambdaService lambdaService; @Mock private SqsService sqsService; @@ -217,6 +218,14 @@ class PipesTargetInvokerTest { verifyNoInteractions(redshiftSubmitter); } + private ObjectNode eventBusParameters(String source, String detailType) { + ObjectNode tp = MAPPER.createObjectNode(); + ObjectNode ebParams = tp.putObject("EventBridgeEventBusParameters"); + ebParams.put("Source", source); + ebParams.put("DetailType", detailType); + return tp; + } + private Pipe createPipe(String targetArn, ObjectNode targetParameters) { Pipe pipe = new Pipe(); pipe.setName("test-pipe"); @@ -379,6 +388,81 @@ class PipesTargetInvokerTest { assertEquals("PipeForwarded", entry.get("DetailType")); } + @Test + @SuppressWarnings("unchecked") + void eventBridge_readsSourceAndDetailTypeOffThePayload() { + Pipe pipe = createPipe(BUS_ARN, eventBusParameters("$.Source", "$.DetailType")); + + invoker.invoke(pipe, "{\"Source\":\"orders\",\"DetailType\":\"Order Placed\",\"id\":1}", "us-east-1"); + + ArgumentCaptor>> captor = ArgumentCaptor.forClass(List.class); + verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1")); + Map entry = captor.getValue().get(0); + assertEquals("orders", entry.get("Source")); + assertEquals("Order Placed", entry.get("DetailType")); + assertEquals("{\"Source\":\"orders\",\"DetailType\":\"Order Placed\",\"id\":1}", entry.get("Detail")); + } + + @Test + @SuppressWarnings("unchecked") + void eventBridge_readsTheParametersOffThePayloadBeforeTheTemplateRenders() { + ObjectNode tp = eventBusParameters("$.Source", "$.DetailType"); + tp.put("InputTemplate", "<$.Detail>"); + Pipe pipe = createPipe(BUS_ARN, tp); + + invoker.invoke(pipe, """ + {"Source":"orders","DetailType":"Order Placed","Detail":"{\\"id\\":\\"k1\\"}"}""", "us-east-1"); + + ArgumentCaptor>> captor = ArgumentCaptor.forClass(List.class); + verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1")); + Map entry = captor.getValue().get(0); + assertEquals("orders", entry.get("Source")); + assertEquals("Order Placed", entry.get("DetailType")); + assertEquals("{\"id\":\"k1\"}", entry.get("Detail")); + } + + @Test + @SuppressWarnings("unchecked") + void eventBridge_aStaticValueStaysAsWritten() { + Pipe pipe = createPipe(BUS_ARN, eventBusParameters("orders", "$.DetailType")); + + invoker.invoke(pipe, "{\"Source\":\"ignored\",\"DetailType\":\"Order Placed\"}", "us-east-1"); + + ArgumentCaptor>> captor = ArgumentCaptor.forClass(List.class); + verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1")); + assertEquals("orders", captor.getValue().get(0).get("Source")); + assertEquals("Order Placed", captor.getValue().get(0).get("DetailType")); + } + + @Test + void eventBridge_aPathNamingNothingThrowsAndPutsNoEvent() { + Pipe pipe = createPipe(BUS_ARN, eventBusParameters("$.Source", "$.DetailType")); + + RuntimeException ex = assertThrows(RuntimeException.class, + () -> invoker.invoke(pipe, "{\"Source\":\"orders\"}", "us-east-1")); + + assertTrue(ex.getMessage().contains("$.DetailType"), ex.getMessage()); + verifyNoInteractions(eventBridgeService); + } + + @Test + void inputTemplate_ofOnePlaceholderNamingAStringRendersItVerbatim() { + assertEquals("{\"id\":\"k1\"}", invoker.applyInputTemplate("<$.Detail>", + "{\"Detail\":\"{\\\"id\\\":\\\"k1\\\"}\"}")); + assertEquals("plain text", invoker.applyInputTemplate("<$.Detail>", "{\"Detail\":\"plain text\"}")); + } + + @Test + void inputTemplate_ofOnePlaceholderNamingANonStringStaysAsItIs() { + assertEquals("42", invoker.applyInputTemplate("<$.count>", "{\"count\":42}")); + assertEquals("{\"id\":1}", invoker.applyInputTemplate("<$.nested>", "{\"nested\":{\"id\":1}}")); + } + + @Test + void inputTemplate_aPlaceholderAsAValueStillTakesQuotes() { + assertEquals("{\"id\": \"m1\"}", invoker.applyInputTemplate("{\"id\": <$.messageId>}", "{\"messageId\":\"m1\"}")); + } + @Test void inputTemplate_numericNotQuoted() { String result = invoker.applyInputTemplate("{\"count\": <$.count>}", "{\"count\": 42}"); @@ -571,10 +655,10 @@ class PipesTargetInvokerTest { @Test void applyEnrichment_emptyObjectOrArrayResponseSkipsTarget() { - // AWS skips the target when the enrichment returns {} or [] (whitespace variants included). + // 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[]{"{}", "[]", " { } ", "[ ]"}) { + for (String body : new String[]{"{}", "[]", " { } ", "[ ]", "\"\""}) { when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse))) .thenReturn(new InvokeResult( 200, null, body.getBytes(StandardCharsets.UTF_8), null, "req"));