mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
6038fe7fc9
commit
a5ab677d6b
6 files changed
+695
-66
No files matched your search
@@ -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<String> 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<String> 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<String> 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<String> enrichmentInputs(Pipe pipe) {
|
||||
ArgumentCaptor<String> 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<String> targetPayloads(Pipe pipe) {
|
||||
ArgumentCaptor<String> 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);
|
||||
|
||||
+205
@@ -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<JsonNode> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1"));
|
||||
Map<String, Object> 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<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1"));
|
||||
Map<String, Object> 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<List<Map<String, Object>>> 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"));
|
||||
|
||||
Reference in new issue
Block a user