From c12db764e680ebabe669f7e0e1cfa5734a28f21a Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Mon, 16 Nov 2026 10:12:09 -0600 Subject: [PATCH] fix(pipes): share SQS records with Lambda pollers (#8604) EventBridge Pipes and Lambda event source mappings now build their SQS records through one SqsEventRecordBuilder, the record Lambda already sent. Pipes gains the FIFO attributes SequenceNumber, MessageGroupId and MessageDeduplicationId, md5OfMessageAttributes when present, and a default dataType for message attributes. A message without a first-receive timestamp takes the Pipes poller's clock instead of wall time, without writing it back to the message. Lambda's record is unchanged. Signed-off-by: Andre Kurait --- .../services/lambda/SqsEventSourcePoller.java | 48 +---------- .../floci/aws/services/pipes/PipesPoller.java | 40 +++------ .../services/sqs/SqsEventRecordBuilder.java | 65 +++++++++++++++ .../aws/services/pipes/PipesPollerTest.java | 81 +++++++++++++++++++ 4 files changed, 157 insertions(+), 77 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/sqs/SqsEventRecordBuilder.java diff --git a/src/main/java/io/floci/aws/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/floci/aws/services/lambda/SqsEventSourcePoller.java index d48b583491..74582a3bbf 100644 --- a/src/main/java/io/floci/aws/services/lambda/SqsEventSourcePoller.java +++ b/src/main/java/io/floci/aws/services/lambda/SqsEventSourcePoller.java @@ -13,6 +13,7 @@ import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.LambdaFunction; import io.floci.aws.services.pipes.PipesFilterMatcher; +import io.floci.aws.services.sqs.SqsEventRecordBuilder; import io.floci.aws.services.sqs.SqsService; import io.floci.aws.services.sqs.model.Message; import io.vertx.core.Vertx; @@ -22,7 +23,6 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; -import java.util.Base64; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; @@ -435,51 +435,7 @@ public class SqsEventSourcePoller implements Resettable { * {@code body}; the matcher auto-reparses a JSON body). */ private ObjectNode buildSqsRecordNode(Message msg, EventSourceMapping esm) { - ObjectNode record = objectMapper.createObjectNode(); - record.put("messageId", msg.getMessageId()); - record.put("receiptHandle", msg.getReceiptHandle()); - record.put("body", msg.getBody()); - ObjectNode attrs = record.putObject("attributes"); - attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount())); - attrs.put("SentTimestamp", String.valueOf(msg.getSentTimestamp().toEpochMilli())); - attrs.put("SenderId", AwsArnUtils.accountOrDefault(esm.getEventSourceArn(), "000000000000")); - attrs.put("ApproximateFirstReceiveTimestamp", - String.valueOf(msg.getFirstReceiveTimestamp() != null - ? msg.getFirstReceiveTimestamp().toEpochMilli() - : clockMs.getAsLong())); - if (msg.getSequenceNumber() > 0) { - attrs.put("SequenceNumber", String.valueOf(msg.getSequenceNumber())); - } - if (msg.getMessageGroupId() != null) { - attrs.put("MessageGroupId", msg.getMessageGroupId()); - } - if (msg.getMessageDeduplicationId() != null) { - attrs.put("MessageDeduplicationId", msg.getMessageDeduplicationId()); - } - // Populate messageAttributes from the message model - ObjectNode msgAttrs = record.putObject("messageAttributes"); - if (msg.getMessageAttributes() != null) { - msg.getMessageAttributes().forEach((name, val) -> { - ObjectNode attrNode = msgAttrs.putObject(name); - attrNode.put("dataType", val.getDataType() != null ? val.getDataType() : "String"); - if (val.getBinaryValue() != null) { - attrNode.put("binaryValue", - Base64.getEncoder().encodeToString(val.getBinaryValue())); - } else if (val.getStringValue() != null) { - attrNode.put("stringValue", val.getStringValue()); - } - attrNode.putArray("stringListValues"); - attrNode.putArray("binaryListValues"); - }); - } - record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : ""); - if (msg.getMd5OfMessageAttributes() != null) { - record.put("md5OfMessageAttributes", msg.getMd5OfMessageAttributes()); - } - record.put("eventSource", "aws:sqs"); - record.put("eventSourceARN", esm.getEventSourceArn()); - record.put("awsRegion", esm.getRegion()); - return record; + return SqsEventRecordBuilder.build(objectMapper, msg, esm.getEventSourceArn(), esm.getRegion(), clockMs); } /** 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 9868b0e8e5..abacc98954 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesPoller.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesPoller.java @@ -15,9 +15,9 @@ import io.floci.aws.services.kinesis.KinesisService; import io.floci.aws.services.kinesis.model.KinesisRecord; import io.floci.aws.services.pipes.model.DesiredState; import io.floci.aws.services.pipes.model.Pipe; +import io.floci.aws.services.sqs.SqsEventRecordBuilder; import io.floci.aws.services.sqs.SqsService; import io.floci.aws.services.sqs.model.Message; -import io.floci.aws.services.sqs.model.MessageAttributeValue; import io.vertx.core.Vertx; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -35,6 +35,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.function.LongSupplier; @ApplicationScoped public class PipesPoller implements Resettable { @@ -58,6 +59,7 @@ public class PipesPoller implements Resettable { private final ObjectMapper objectMapper; private final String baseUrl; private final String defaultRegion; + private volatile LongSupplier clockMs = System::currentTimeMillis; private final ConcurrentHashMap timerIds = new ConcurrentHashMap<>(); private final ConcurrentHashMap activePolls = new ConcurrentHashMap<>(); private final ConcurrentHashMap kinesisIterators = new ConcurrentHashMap<>(); @@ -91,6 +93,10 @@ public class PipesPoller implements Resettable { this.defaultRegion = config.defaultRegion(); } + void setClockForTest(LongSupplier clockMs) { + this.clockMs = clockMs; + } + @PreDestroy void shutdown() { pollExecutor.shutdownNow(); @@ -750,36 +756,8 @@ public class PipesPoller implements Resettable { private List buildSqsRecordNodes(List messages, Pipe pipe) { List nodes = new ArrayList<>(); for (Message msg : messages) { - ObjectNode record = objectMapper.createObjectNode(); - record.put("messageId", msg.getMessageId()); - record.put("receiptHandle", msg.getReceiptHandle()); - record.put("body", msg.getBody()); - ObjectNode attrs = record.putObject("attributes"); - attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount())); - attrs.put("SentTimestamp", String.valueOf(msg.getSentTimestamp().toEpochMilli())); - attrs.put("SenderId", AwsArnUtils.accountOrDefault(pipe.getSource(), "000000000000")); - attrs.put("ApproximateFirstReceiveTimestamp", - String.valueOf(msg.getFirstReceiveTimestamp() != null - ? msg.getFirstReceiveTimestamp().toEpochMilli() - : System.currentTimeMillis())); - ObjectNode msgAttrs = record.putObject("messageAttributes"); - for (Map.Entry entry : msg.getMessageAttributes().entrySet()) { - ObjectNode attrNode = msgAttrs.putObject(entry.getKey()); - MessageAttributeValue val = entry.getValue(); - if (val.getBinaryValue() != null) { - attrNode.put("binaryValue", Base64.getEncoder().encodeToString(val.getBinaryValue())); - } else if (val.getStringValue() != null) { - attrNode.put("stringValue", val.getStringValue()); - } - attrNode.putArray("stringListValues"); - attrNode.putArray("binaryListValues"); - attrNode.put("dataType", val.getDataType()); - } - record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : ""); - record.put("eventSource", "aws:sqs"); - record.put("eventSourceARN", pipe.getSource()); - record.put("awsRegion", extractRegionFromArn(pipe.getSource())); - nodes.add(record); + nodes.add(SqsEventRecordBuilder.build(objectMapper, msg, pipe.getSource(), + extractRegionFromArn(pipe.getSource()), clockMs)); } return nodes; } diff --git a/src/main/java/io/floci/aws/services/sqs/SqsEventRecordBuilder.java b/src/main/java/io/floci/aws/services/sqs/SqsEventRecordBuilder.java new file mode 100644 index 0000000000..9f7b46561d --- /dev/null +++ b/src/main/java/io/floci/aws/services/sqs/SqsEventRecordBuilder.java @@ -0,0 +1,65 @@ +package io.floci.aws.services.sqs; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.services.sqs.model.Message; + +import java.util.Base64; +import java.util.function.LongSupplier; + +/** The SQS record shared by Lambda event source mappings and EventBridge Pipes. */ +public final class SqsEventRecordBuilder { + + private SqsEventRecordBuilder() { + } + + public static ObjectNode build(ObjectMapper mapper, Message msg, String queueArn, + String region, LongSupplier clockMs) { + ObjectNode record = mapper.createObjectNode(); + record.put("messageId", msg.getMessageId()); + record.put("receiptHandle", msg.getReceiptHandle()); + record.put("body", msg.getBody()); + ObjectNode attrs = record.putObject("attributes"); + attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount())); + attrs.put("SentTimestamp", String.valueOf(msg.getSentTimestamp().toEpochMilli())); + attrs.put("SenderId", AwsArnUtils.accountOrDefault(queueArn, "000000000000")); + attrs.put("ApproximateFirstReceiveTimestamp", + String.valueOf(msg.getFirstReceiveTimestamp() != null + ? msg.getFirstReceiveTimestamp().toEpochMilli() + : clockMs.getAsLong())); + if (msg.getSequenceNumber() > 0) { + attrs.put("SequenceNumber", String.valueOf(msg.getSequenceNumber())); + } + if (msg.getMessageGroupId() != null) { + attrs.put("MessageGroupId", msg.getMessageGroupId()); + } + if (msg.getMessageDeduplicationId() != null) { + attrs.put("MessageDeduplicationId", msg.getMessageDeduplicationId()); + } + // Populate messageAttributes from the message model + ObjectNode msgAttrs = record.putObject("messageAttributes"); + if (msg.getMessageAttributes() != null) { + msg.getMessageAttributes().forEach((name, val) -> { + ObjectNode attrNode = msgAttrs.putObject(name); + attrNode.put("dataType", val.getDataType() != null ? val.getDataType() : "String"); + if (val.getBinaryValue() != null) { + attrNode.put("binaryValue", + Base64.getEncoder().encodeToString(val.getBinaryValue())); + } else if (val.getStringValue() != null) { + attrNode.put("stringValue", val.getStringValue()); + } + attrNode.putArray("stringListValues"); + attrNode.putArray("binaryListValues"); + }); + } + record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : ""); + if (msg.getMd5OfMessageAttributes() != null) { + record.put("md5OfMessageAttributes", msg.getMd5OfMessageAttributes()); + } + record.put("eventSource", "aws:sqs"); + record.put("eventSourceARN", queueArn); + record.put("awsRegion", region); + return record; + } +} 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 3025621aa1..fa3354607e 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java @@ -35,10 +35,12 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -183,6 +185,85 @@ class PipesPollerTest { verify(sqsService).receiveMessage(anyString(), eq(10), anyInt(), anyInt(), eq("us-east-1")); } + @Test + void sqsDeliveryIncludesFifoSystemAttributes() throws Exception { + Message message = new Message("fifo-body"); + message.setSequenceNumber(27); + message.setMessageGroupId("orders"); + message.setMessageDeduplicationId("order-42"); + + JsonNode record = deliveredSqsRecord(message); + + assertEquals("27", record.at("/attributes/SequenceNumber").asText()); + assertEquals("orders", record.at("/attributes/MessageGroupId").asText()); + assertEquals("order-42", record.at("/attributes/MessageDeduplicationId").asText()); + assertEquals("fifo-body", record.path("body").asText()); + assertEquals("aws:sqs", record.path("eventSource").asText()); + assertEquals("us-east-1", record.path("awsRegion").asText()); + } + + @Test + void sqsDeliveryOmitsAbsentFifoSystemAttributes() throws Exception { + JsonNode record = deliveredSqsRecord(new Message("standard-body")); + + assertFalse(record.path("attributes").has("SequenceNumber")); + assertFalse(record.path("attributes").has("MessageGroupId")); + assertFalse(record.path("attributes").has("MessageDeduplicationId")); + } + + @Test + void missingSqsReceiveTimestampUsesThePollerClockWithoutMutatingTheMessage() throws Exception { + AtomicLong clock = new AtomicLong(1000); + poller.setClockForTest(clock::get); + Message message = new Message("body"); + message.setFirstReceiveTimestamp(null); + Pipe pipe = sqsDeliveryPipe(message); + + poller.pollSqs(pipe, "us-east-1"); + clock.addAndGet(10); + poller.pollSqs(pipe, "us-east-1"); + + ArgumentCaptor payload = ArgumentCaptor.forClass(String.class); + verify(targetInvoker, times(2)).invoke(eq(pipe), payload.capture(), eq("us-east-1")); + assertEquals("1000", MAPPER.readTree(payload.getAllValues().get(0)) + .at("/Records/0/attributes/ApproximateFirstReceiveTimestamp").asText()); + assertEquals("1010", MAPPER.readTree(payload.getAllValues().get(1)) + .at("/Records/0/attributes/ApproximateFirstReceiveTimestamp").asText()); + assertNull(message.getFirstReceiveTimestamp()); + } + + @Test + void storedSqsReceiveTimestampDoesNotReadTheFallbackClock() throws Exception { + poller.setClockForTest(() -> { + throw new AssertionError("A stored timestamp must not read the fallback clock"); + }); + Message message = new Message("body"); + message.setFirstReceiveTimestamp(Instant.ofEpochMilli(7)); + + JsonNode record = deliveredSqsRecord(message); + + assertEquals("7", record.at("/attributes/ApproximateFirstReceiveTimestamp").asText()); + assertEquals(Instant.ofEpochMilli(7), message.getFirstReceiveTimestamp()); + } + + private Pipe sqsDeliveryPipe(Message message) { + Pipe pipe = new Pipe(); + pipe.setName("sqs-record"); + pipe.setSource("arn:aws:sqs:us-east-1:000000000000:orders.fifo"); + pipe.setTarget("arn:aws:lambda:us-east-1:000000000000:function:target"); + when(sqsService.receiveMessage(anyString(), anyInt(), anyInt(), anyInt(), eq("us-east-1"))) + .thenReturn(List.of(message)); + return pipe; + } + + private JsonNode deliveredSqsRecord(Message message) throws Exception { + Pipe pipe = sqsDeliveryPipe(message); + poller.pollSqs(pipe, "us-east-1"); + ArgumentCaptor payload = ArgumentCaptor.forClass(String.class); + verify(targetInvoker).invoke(eq(pipe), payload.capture(), eq("us-east-1")); + return MAPPER.readTree(payload.getValue()).path("Records").get(0); + } + @Test void pollSqs_enrichmentToNonLambdaTargetForwardsRawResponse() throws Exception { // A non-Lambda target (here Step Functions) must receive the raw enrichment response, not a