feat(pipes): support Kafka pipe sources and polling (#1260)

* feat(pipes): support Kafka pipe sources and polling

Add EventBridge Pipes support for Amazon MSK and self-managed Kafka sources exposed via `smk://`.

Introduce Kafka consumer management for bootstrap resolution, consumer group selection, topic validation, and safe reuse across poll cycles.

Extend the Pipes poller and tests to filter decoded Kafka payloads, deliver the expected record shape, and commit offsets only after successful delivery.

* fix(pipes): tighten Kafka validation and commit handling

Clarify Kafka validation errors, avoid duplicate Kafka record transformation, commit delivered Kafka offsets per partition for non-Lambda targets, and remove reflective poller test access.

* fix(pipes): stabilise Kafka poller event handling

Use a consistent Kafka partition type, narrow JSON decode error handling, remove reflection from manager tests, and tighten no-commit assertions for failed Kafka delivery paths.

* fix(pipes): preserve Kafka nulls and commit progress

Preserve null Kafka key and value fields, encode Kafka headers consistently, and commit Lambda Kafka progress per partition so successfully processed records are not replayed after later failures.

* fix(msk): align broker metadata and Kafka event payloads
This commit is contained in:
Liam MacPherson authored and GitHub committed 2026-06-25 19:59:38 -05:00
1 parent 1c87c2aa47
commit 86c4aae2e2
9 files changed
+951 -2

No files matched your search

@@ -101,6 +101,28 @@ class PipesFilterMatcherTest {
assertFalse(matcher.matchesRecord(record, "{\"detail\": {\"status\": [\"inactive\"]}}"));
}
@Test
void kafkaDecodedValueCanBeFilteredAsJson() throws Exception {
JsonNode record = MAPPER.readTree("""
{
"eventSource": "aws:kafka",
"topic": "orders",
"value": {"status": "active", "id": "order-1"}
}
""");
assertTrue(matcher.matchesRecord(record, "{\"value\": {\"status\": [\"active\"]}}"));
assertFalse(matcher.matchesRecord(record, "{\"value\": {\"status\": [\"inactive\"]}}"));
}
@Test
void kafkaDecodedKeyCanBeFilteredAsString() throws Exception {
JsonNode record = MAPPER.readTree("{\"key\": \"customer-123\", \"topic\": \"orders\"}");
assertTrue(matcher.matchesRecord(record, "{\"key\": [{\"prefix\": \"customer-\"}]}"));
assertFalse(matcher.matchesRecord(record, "{\"key\": [\"customer-999\"]}"));
}
// ──────────────────────────── Operators ────────────────────────────
@Test
@@ -0,0 +1,164 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.msk.MskService;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
class PipesKafkaConsumerManagerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private MskService mskService;
private PipesKafkaConsumerManager manager;
@BeforeEach
void setUp() {
mskService = Mockito.mock(MskService.class);
manager = new PipesKafkaConsumerManager(mskService);
}
@Test
void resolveBootstrapServersForSelfManagedKafkaIncludesAdditionalServers() throws Exception {
Pipe pipe = new Pipe();
pipe.setSource("smk://broker-1:9092");
pipe.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {
"TopicName": "orders",
"AdditionalBootstrapServers": ["broker-2:9092", "broker-3:9092"]
}
}
"""));
assertEquals("broker-1:9092,broker-2:9092,broker-3:9092", manager.resolveBootstrapServers(pipe));
}
@Test
void resolveBootstrapServersForManagedKafkaUsesMskService() throws Exception {
Pipe pipe = new Pipe();
pipe.setSource("arn:aws:kafka:us-east-1:000000000000:cluster/demo/uuid");
pipe.setSourceParameters(MAPPER.readTree("""
{
"ManagedStreamingKafkaParameters": {
"TopicName": "orders"
}
}
"""));
when(mskService.getBootstrapBrokers(pipe.getSource())).thenReturn("localhost:19092");
assertEquals("localhost:19092", manager.resolveBootstrapServers(pipe));
}
@Test
void resolveTopicNameUsesMatchingParameterBlock() throws Exception {
Pipe managed = new Pipe();
managed.setSource("arn:aws:kafka:us-east-1:000000000000:cluster/demo/uuid");
managed.setSourceParameters(MAPPER.readTree("""
{
"ManagedStreamingKafkaParameters": {
"TopicName": "managed-topic"
}
}
"""));
Pipe selfManaged = new Pipe();
selfManaged.setSource("smk://localhost:9092");
selfManaged.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {
"TopicName": "self-topic"
}
}
"""));
assertEquals("managed-topic", manager.resolveTopicName(managed));
assertEquals("self-topic", manager.resolveTopicName(selfManaged));
}
@Test
@DisplayName("resolveTopicName reports the matching parameter block")
void resolveTopicNameReportsMatchingParameterBlock() throws Exception {
Pipe managed = new Pipe();
managed.setSource("arn:aws:kafka:us-east-1:000000000000:cluster/demo/uuid");
managed.setSourceParameters(MAPPER.readTree("""
{
"ManagedStreamingKafkaParameters": {}
}
"""));
Pipe selfManaged = new Pipe();
selfManaged.setSource("smk://localhost:9092");
selfManaged.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {}
}
"""));
assertEquals("SourceParameters.ManagedStreamingKafkaParameters.TopicName is required",
assertThrows(io.github.hectorvent.floci.core.common.AwsException.class,
() -> manager.resolveTopicName(managed)).getMessage());
assertEquals("SourceParameters.SelfManagedKafkaParameters.TopicName is required",
assertThrows(io.github.hectorvent.floci.core.common.AwsException.class,
() -> manager.resolveTopicName(selfManaged)).getMessage());
}
@Test
void resolveTopicNameReportsMissingParameterBlock() {
Pipe managed = new Pipe();
managed.setSource("arn:aws:kafka:us-east-1:000000000000:cluster/demo/uuid");
managed.setSourceParameters(MAPPER.createObjectNode());
Pipe selfManaged = new Pipe();
selfManaged.setSource("smk://localhost:9092");
selfManaged.setSourceParameters(MAPPER.createObjectNode());
assertEquals("SourceParameters.ManagedStreamingKafkaParameters is required",
assertThrows(io.github.hectorvent.floci.core.common.AwsException.class,
() -> manager.resolveTopicName(managed)).getMessage());
assertEquals("SourceParameters.SelfManagedKafkaParameters is required",
assertThrows(io.github.hectorvent.floci.core.common.AwsException.class,
() -> manager.resolveTopicName(selfManaged)).getMessage());
}
@Test
void resolveConsumerGroupIdUsesConfiguredValueOrStableFallback() throws Exception {
Pipe configured = new Pipe();
configured.setName("orders-pipe");
configured.setSource("smk://broker-1:9092");
configured.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {
"TopicName": "orders",
"ConsumerGroupID": "custom-group"
}
}
"""));
Pipe fallback = new Pipe();
fallback.setName("orders-pipe");
fallback.setSource("arn:aws:kafka:us-east-1:000000000000:cluster/demo/uuid");
fallback.setSourceParameters(MAPPER.readTree("""
{
"ManagedStreamingKafkaParameters": {
"TopicName": "orders"
}
}
"""));
assertEquals("custom-group", manager.resolveConsumerGroupId(configured));
String fallbackGroupId = manager.resolveConsumerGroupId(fallback);
assertEquals(fallbackGroupId, manager.resolveConsumerGroupId(fallback));
org.junit.jupiter.api.Assertions.assertTrue(
fallbackGroupId.startsWith("floci-pipes-orders-pipe-"),
"Expected generated consumer group id prefix, got: " + fallbackGroupId);
}
}
@@ -0,0 +1,224 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.vertx.core.Vertx;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
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.assertTrue;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class PipesPollerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Mock private Vertx vertx;
@Mock private SqsService sqsService;
@Mock private KinesisService kinesisService;
@Mock private DynamoDbStreamService dynamoDbStreamService;
@Mock private PipesKafkaConsumerManager kafkaConsumerManager;
@Mock private PipesTargetInvoker targetInvoker;
@Mock private EmulatorConfig config;
private PipesPoller poller;
@BeforeEach
void setUp() {
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
poller = new PipesPoller(vertx, sqsService, kinesisService, dynamoDbStreamService,
kafkaConsumerManager, targetInvoker, new PipesFilterMatcher(MAPPER), MAPPER, config);
}
@Test
void pollKafka_filtersUsingDecodedPayloadButDeliversOriginalRecord() throws Exception {
Pipe pipe = selfManagedKafkaPipe();
byte[] key = "customer-123".getBytes(StandardCharsets.UTF_8);
byte[] value = "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8);
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("orders", 0, 42L, key, value);
record.headers().add("traceId", "abc123".getBytes(StandardCharsets.UTF_8));
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
poller.pollKafka(pipe, "us-east-1");
ArgumentCaptor<String> payloadCaptor = ArgumentCaptor.forClass(String.class);
verify(targetInvoker).invoke(eq(pipe), payloadCaptor.capture(), eq("us-east-1"));
verify(kafkaConsumerManager).commit(eq(pipe), anyMap());
JsonNode delivered = MAPPER.readTree(payloadCaptor.getValue());
assertEquals("orders", delivered.path("topic").asText());
assertTrue(delivered.path("partition").isInt());
assertEquals("broker-1:9092", delivered.path("bootstrapServers").asText());
assertEquals("Y3VzdG9tZXItMTIz", delivered.path("key").asText());
assertEquals("eyJzdGF0dXMiOiJhY3RpdmUiLCJpZCI6Im9yZGVyLTEifQ==", delivered.path("value").asText());
assertTrue(delivered.path("headers").get(0).path("traceId").isArray());
assertEquals(List.of(97, 98, 99, 49, 50, 51),
MAPPER.convertValue(delivered.path("headers").get(0).path("traceId"), List.class));
assertFalse(delivered.has("eventSourceKey"));
assertTrue(delivered.path("value").isTextual());
}
@Test
void pollKafka_doesNotCommitWhenDeliveryFails() throws Exception {
Pipe pipe = selfManagedKafkaPipe();
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>(
"orders", 0, 7L, null, "{\"status\":\"active\"}".getBytes(StandardCharsets.UTF_8));
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
org.mockito.Mockito.doThrow(new RuntimeException("boom"))
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
poller.pollKafka(pipe, "us-east-1");
verify(kafkaConsumerManager, never()).commit(pipe);
verify(kafkaConsumerManager, never()).commit(eq(pipe), anyMap());
}
@Test
void pollKafka_commitsDeliveredPrefixWhenLaterRecordFails() throws Exception {
Pipe pipe = selfManagedKafkaPipe();
ConsumerRecord<byte[], byte[]> first = new ConsumerRecord<>(
"orders", 0, 0L, null, "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8));
ConsumerRecord<byte[], byte[]> second = new ConsumerRecord<>(
"orders", 0, 1L, null, "{\"status\":\"active\",\"id\":\"order-2\"}".getBytes(StandardCharsets.UTF_8));
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(first, second));
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
org.mockito.Mockito.doNothing()
.doThrow(new RuntimeException("boom"))
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
poller.pollKafka(pipe, "us-east-1");
ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> offsetsCaptor = ArgumentCaptor.forClass(Map.class);
verify(kafkaConsumerManager).commit(eq(pipe), offsetsCaptor.capture());
assertEquals(1L, offsetsCaptor.getValue().get(new TopicPartition("orders", 0)).offset());
}
@Test
void pollKafka_representsNullKeyAndValueAsJsonNull() throws Exception {
Pipe pipe = nullableSelfManagedKafkaPipe();
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("orders", 0, 3L, null, null);
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
poller.pollKafka(pipe, "us-east-1");
ArgumentCaptor<String> payloadCaptor = ArgumentCaptor.forClass(String.class);
verify(targetInvoker).invoke(eq(pipe), payloadCaptor.capture(), eq("us-east-1"));
JsonNode delivered = MAPPER.readTree(payloadCaptor.getValue());
assertTrue(delivered.path("key").isNull());
assertTrue(delivered.path("value").isNull());
}
@Test
void pollKafka_lambdaCommitsSuccessfulPrefixBeforeLaterFailure() throws Exception {
Pipe pipe = lambdaSelfManagedKafkaPipe();
ConsumerRecord<byte[], byte[]> first = new ConsumerRecord<>(
"orders", 0, 0L, null, "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8));
ConsumerRecord<byte[], byte[]> skipped = new ConsumerRecord<>(
"orders", 0, 1L, null, "{\"status\":\"inactive\",\"id\":\"order-2\"}".getBytes(StandardCharsets.UTF_8));
ConsumerRecord<byte[], byte[]> failing = new ConsumerRecord<>(
"orders", 0, 2L, null, "{\"status\":\"active\",\"id\":\"order-3\"}".getBytes(StandardCharsets.UTF_8));
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(first, skipped, failing));
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
org.mockito.Mockito.doNothing()
.doThrow(new RuntimeException("boom"))
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
poller.pollKafka(pipe, "us-east-1");
ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> offsetsCaptor = ArgumentCaptor.forClass(Map.class);
verify(kafkaConsumerManager).commit(eq(pipe), offsetsCaptor.capture());
assertEquals(2L, offsetsCaptor.getValue().get(new TopicPartition("orders", 0)).offset());
}
private Pipe selfManagedKafkaPipe() throws Exception {
Pipe pipe = new Pipe();
pipe.setName("orders-pipe");
pipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/orders-pipe");
pipe.setSource("smk://broker-1:9092");
pipe.setTarget("arn:aws:sqs:us-east-1:000000000000:orders-target");
pipe.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {
"TopicName": "orders"
},
"FilterCriteria": {
"Filters": [
{"Pattern": "{\\\"value\\\": {\\\"status\\\": [\\\"active\\\"]}}"}
]
}
}
"""));
return pipe;
}
private Pipe nullableSelfManagedKafkaPipe() throws Exception {
Pipe pipe = new Pipe();
pipe.setName("nullable-orders-pipe");
pipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/nullable-orders-pipe");
pipe.setSource("smk://broker-1:9092");
pipe.setTarget("arn:aws:sqs:us-east-1:000000000000:orders-target");
pipe.setSourceParameters(MAPPER.readTree("""
{
"SelfManagedKafkaParameters": {
"TopicName": "orders"
},
"FilterCriteria": {
"Filters": [
{"Pattern": "{\\\"key\\\": [{\\\"exists\\\": false}]}"}
]
}
}
"""));
return pipe;
}
private Pipe lambdaSelfManagedKafkaPipe() throws Exception {
Pipe pipe = selfManagedKafkaPipe();
pipe.setTarget("arn:aws:lambda:us-east-1:000000000000:function:orders-target");
return pipe;
}
private ConsumerRecords<byte[], byte[]> records(ConsumerRecord<byte[], byte[]>... records) {
Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> byPartition = new java.util.LinkedHashMap<>();
for (ConsumerRecord<byte[], byte[]> record : records) {
TopicPartition topicPartition = new TopicPartition(record.topic(), record.partition());
byPartition.computeIfAbsent(topicPartition, ignored -> new java.util.ArrayList<>()).add(record);
}
return new ConsumerRecords<>(byPartition);
}
}
@@ -107,6 +107,33 @@ class PipesServiceTest {
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void createPipeWithManagedKafkaSourceRequiresTopicParameters() {
AwsException ex = assertThrows(AwsException.class, () ->
pipesService.createPipe("msk-pipe",
"arn:aws:kafka:us-east-1:000000000000:cluster/test/uuid",
"arn:aws:sqs:us-east-1:000000000000:target",
"arn:aws:iam::000000000000:role/role",
null, null, null, null, null, null, null, "us-east-1"));
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void createPipeWithSelfManagedKafkaSourceRequiresTopicParameters() throws Exception {
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
AwsException ex = assertThrows(AwsException.class, () ->
pipesService.createPipe("smk-pipe",
"smk://localhost:9092",
"arn:aws:sqs:us-east-1:000000000000:target",
"arn:aws:iam::000000000000:role/role",
null, null, null,
mapper.readTree("{\"SelfManagedKafkaParameters\":{}}"),
null, null, null, "us-east-1"));
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void describePipe() {
pipesService.createPipe("my-pipe",