mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
1c87c2aa47
commit
86c4aae2e2
9 files changed
+951
-2
No files matched your search
+211
@@ -0,0 +1,211 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.msk.MskService;
|
||||
import io.github.hectorvent.floci.services.pipes.model.Pipe;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
|
||||
import org.apache.kafka.common.TopicPartition;
|
||||
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@ApplicationScoped
|
||||
public class PipesKafkaConsumerManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(PipesKafkaConsumerManager.class);
|
||||
private static final Duration POLL_TIMEOUT = Duration.ofMillis(100);
|
||||
private static final String DEFAULT_STARTING_POSITION = "LATEST";
|
||||
|
||||
private final MskService mskService;
|
||||
private final ConcurrentHashMap<String, KafkaConsumer<byte[], byte[]>> consumers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public PipesKafkaConsumerManager(MskService mskService) {
|
||||
this.mskService = mskService;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
consumers.values().forEach(this::closeQuietly);
|
||||
consumers.clear();
|
||||
}
|
||||
|
||||
public ConsumerRecords<byte[], byte[]> poll(Pipe pipe) {
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.computeIfAbsent(pipe.getArn(), ignored -> createConsumer(pipe));
|
||||
try {
|
||||
return consumer.poll(POLL_TIMEOUT);
|
||||
} catch (RuntimeException e) {
|
||||
close(pipe);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public void commit(Pipe pipe) {
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.get(pipe.getArn());
|
||||
if (consumer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
consumer.commitSync();
|
||||
} catch (RuntimeException e) {
|
||||
close(pipe);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public void commit(Pipe pipe, Map<TopicPartition, OffsetAndMetadata> offsets) {
|
||||
if (offsets.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.get(pipe.getArn());
|
||||
if (consumer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
consumer.commitSync(offsets);
|
||||
} catch (RuntimeException e) {
|
||||
close(pipe);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public void close(Pipe pipe) {
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.remove(pipe.getArn());
|
||||
if (consumer != null) {
|
||||
closeQuietly(consumer);
|
||||
}
|
||||
}
|
||||
|
||||
String resolveBootstrapServers(Pipe pipe) {
|
||||
if (isSelfManagedSource(pipe)) {
|
||||
List<String> servers = new ArrayList<>();
|
||||
servers.add(pipe.getSource().substring("smk://".length()));
|
||||
JsonNode additionalServers = kafkaParameters(pipe).path("AdditionalBootstrapServers");
|
||||
if (additionalServers.isArray()) {
|
||||
additionalServers.forEach(node -> {
|
||||
String server = node.asText(null);
|
||||
if (server != null && !server.isBlank()) {
|
||||
servers.add(server);
|
||||
}
|
||||
});
|
||||
}
|
||||
return String.join(",", servers);
|
||||
}
|
||||
if (isManagedSource(pipe)) {
|
||||
return mskService.getBootstrapBrokers(pipe.getSource());
|
||||
}
|
||||
throw new AwsException("ValidationException", "Unsupported Kafka source: " + pipe.getSource(), 400);
|
||||
}
|
||||
|
||||
String resolveTopicName(Pipe pipe) {
|
||||
JsonNode params = kafkaParameters(pipe);
|
||||
String topic = params.path("TopicName").asText(null);
|
||||
if (topic == null || topic.isBlank()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SourceParameters." + parameterBlockName(pipe) + ".TopicName is required", 400);
|
||||
}
|
||||
return topic;
|
||||
}
|
||||
|
||||
int resolveBatchSize(Pipe pipe, int defaultBatchSize) {
|
||||
JsonNode params = kafkaParameters(pipe);
|
||||
return params.path("BatchSize").asInt(defaultBatchSize);
|
||||
}
|
||||
|
||||
String resolveConsumerGroupId(Pipe pipe) {
|
||||
return resolveConsumerGroupId(pipe, kafkaParameters(pipe));
|
||||
}
|
||||
|
||||
private KafkaConsumer<byte[], byte[]> createConsumer(Pipe pipe) {
|
||||
String bootstrapServers = resolveBootstrapServers(pipe);
|
||||
String topicName = resolveTopicName(pipe);
|
||||
JsonNode params = kafkaParameters(pipe);
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
|
||||
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName());
|
||||
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName());
|
||||
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
|
||||
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, resolveOffsetReset(params));
|
||||
properties.put(ConsumerConfig.GROUP_ID_CONFIG, resolveConsumerGroupId(pipe, params));
|
||||
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, "floci-pipes-" + UUID.randomUUID());
|
||||
properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, Integer.toString(resolveBatchSize(pipe, 100)));
|
||||
|
||||
KafkaConsumer<byte[], byte[]> consumer = new KafkaConsumer<>(properties);
|
||||
consumer.subscribe(List.of(topicName));
|
||||
LOG.infov("Pipe {0}: subscribed Kafka consumer to topic {1} via {2}",
|
||||
pipe.getName(), topicName, bootstrapServers);
|
||||
return consumer;
|
||||
}
|
||||
|
||||
private JsonNode kafkaParameters(Pipe pipe) {
|
||||
JsonNode sourceParameters = pipe.getSourceParameters();
|
||||
if (sourceParameters == null) {
|
||||
throw new AwsException("ValidationException", "Kafka pipe SourceParameters are required", 400);
|
||||
}
|
||||
JsonNode parameters = sourceParameters.path(parameterBlockName(pipe));
|
||||
if (parameters.isMissingNode()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SourceParameters." + parameterBlockName(pipe) + " is required", 400);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private String resolveOffsetReset(JsonNode params) {
|
||||
String startingPosition = params.path("StartingPosition").asText(DEFAULT_STARTING_POSITION);
|
||||
return "TRIM_HORIZON".equalsIgnoreCase(startingPosition) ? "earliest" : "latest";
|
||||
}
|
||||
|
||||
private String resolveConsumerGroupId(Pipe pipe, JsonNode params) {
|
||||
String configured = params.path("ConsumerGroupID").asText(null);
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
String sourceFingerprint = isSelfManagedSource(pipe)
|
||||
? pipe.getSource().substring("smk://".length())
|
||||
: AwsArnUtils.parse(pipe.getSource()).resource();
|
||||
return "floci-pipes-" + pipe.getName() + "-" + Integer.toUnsignedString(sourceFingerprint.hashCode());
|
||||
}
|
||||
|
||||
private static boolean isManagedSource(Pipe pipe) {
|
||||
return pipe.getSource().contains(":kafka:");
|
||||
}
|
||||
|
||||
private static boolean isSelfManagedSource(Pipe pipe) {
|
||||
return pipe.getSource().startsWith("smk://");
|
||||
}
|
||||
|
||||
private static String parameterBlockName(Pipe pipe) {
|
||||
if (isManagedSource(pipe)) {
|
||||
return "ManagedStreamingKafkaParameters";
|
||||
}
|
||||
if (isSelfManagedSource(pipe)) {
|
||||
return "SelfManagedKafkaParameters";
|
||||
}
|
||||
throw new AwsException("ValidationException", "Unsupported Kafka source: " + pipe.getSource(), 400);
|
||||
}
|
||||
|
||||
private void closeQuietly(KafkaConsumer<byte[], byte[]> consumer) {
|
||||
try {
|
||||
consumer.close();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Ignoring Kafka consumer close error: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
@@ -17,8 +18,14 @@ import io.vertx.core.Vertx;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
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.apache.kafka.common.header.Header;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -41,6 +48,7 @@ public class PipesPoller {
|
||||
private final SqsService sqsService;
|
||||
private final KinesisService kinesisService;
|
||||
private final DynamoDbStreamService dynamoDbStreamService;
|
||||
private final PipesKafkaConsumerManager kafkaConsumerManager;
|
||||
private final PipesTargetInvoker targetInvoker;
|
||||
private final PipesFilterMatcher filterMatcher;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -60,6 +68,7 @@ public class PipesPoller {
|
||||
SqsService sqsService,
|
||||
KinesisService kinesisService,
|
||||
DynamoDbStreamService dynamoDbStreamService,
|
||||
PipesKafkaConsumerManager kafkaConsumerManager,
|
||||
PipesTargetInvoker targetInvoker,
|
||||
PipesFilterMatcher filterMatcher,
|
||||
ObjectMapper objectMapper,
|
||||
@@ -68,6 +77,7 @@ public class PipesPoller {
|
||||
this.sqsService = sqsService;
|
||||
this.kinesisService = kinesisService;
|
||||
this.dynamoDbStreamService = dynamoDbStreamService;
|
||||
this.kafkaConsumerManager = kafkaConsumerManager;
|
||||
this.targetInvoker = targetInvoker;
|
||||
this.filterMatcher = filterMatcher;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -99,6 +109,7 @@ public class PipesPoller {
|
||||
vertx.cancelTimer(timerId);
|
||||
kinesisIterators.remove(pipeKey);
|
||||
dynamoDbIterators.remove(pipeKey);
|
||||
kafkaConsumerManager.close(pipe);
|
||||
LOG.infov("Pipe {0}: stopped polling", pipe.getName());
|
||||
}
|
||||
}
|
||||
@@ -125,6 +136,8 @@ public class PipesPoller {
|
||||
pollKinesis(pipe, region);
|
||||
} else if (sourceArn.contains(":dynamodb:")) {
|
||||
pollDynamoDbStreams(pipe, region);
|
||||
} else if (isKafkaSource(sourceArn)) {
|
||||
pollKafka(pipe, region);
|
||||
} else {
|
||||
LOG.warnv("Pipe {0}: unsupported source type: {1}", pipe.getName(), sourceArn);
|
||||
}
|
||||
@@ -310,6 +323,155 @@ public class PipesPoller {
|
||||
}
|
||||
}
|
||||
|
||||
void pollKafka(Pipe pipe, String region) {
|
||||
ConsumerRecords<byte[], byte[]> records = kafkaConsumerManager.poll(pipe);
|
||||
if (records.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<ConsumerRecord<byte[], byte[]>> batch = new ArrayList<>(records.count());
|
||||
records.forEach(batch::add);
|
||||
|
||||
LOG.infov("Pipe {0}: received {1} Kafka record(s)", pipe.getName(), batch.size());
|
||||
List<ObjectNode> deliveryNodes = buildKafkaRecordNodes(batch, pipe);
|
||||
List<ObjectNode> filterNodes = buildKafkaFilterNodes(deliveryNodes, batch);
|
||||
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(new ArrayList<>(filterNodes), pipe.getSourceParameters());
|
||||
if (filtered.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity = new HashMap<>();
|
||||
for (JsonNode record : deliveryNodes) {
|
||||
deliveryRecordsByIdentity.put(kafkaRecordIdentity(record), record);
|
||||
}
|
||||
|
||||
List<JsonNode> deliveryRecords = new ArrayList<>(filtered.size());
|
||||
for (JsonNode record : filtered) {
|
||||
JsonNode deliveryRecord = deliveryRecordsByIdentity.get(kafkaRecordIdentity(record));
|
||||
if (deliveryRecord != null) {
|
||||
deliveryRecords.add(deliveryRecord);
|
||||
}
|
||||
}
|
||||
if (deliveryRecords.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe);
|
||||
return;
|
||||
}
|
||||
|
||||
int failed = isLambdaTarget(pipe)
|
||||
? deliverKafkaLambdaRecords(pipe, region, batch, deliveryRecordsByIdentity, filtered)
|
||||
: deliverKafkaRecords(pipe, region, batch, deliveryRecordsByIdentity, filtered);
|
||||
if (failed == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.warnv("Pipe {0}: {1} Kafka record(s) not committed because delivery failed",
|
||||
pipe.getName(), failed);
|
||||
}
|
||||
|
||||
private int deliverKafkaLambdaRecords(Pipe pipe,
|
||||
String region,
|
||||
List<ConsumerRecord<byte[], byte[]>> batch,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
List<JsonNode> filtered) {
|
||||
Set<String> matchedIdentities = new HashSet<>(filtered.size());
|
||||
filtered.forEach(record -> matchedIdentities.add(kafkaRecordIdentity(record)));
|
||||
|
||||
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
|
||||
Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> recordsByPartition = groupKafkaRecordsByPartition(batch);
|
||||
int failed = 0;
|
||||
|
||||
for (Map.Entry<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> entry : recordsByPartition.entrySet()) {
|
||||
failed += deliverKafkaLambdaPartition(pipe, region, entry.getKey(), entry.getValue(),
|
||||
deliveryRecordsByIdentity, matchedIdentities, offsetsToCommit);
|
||||
}
|
||||
|
||||
if (!offsetsToCommit.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe, offsetsToCommit);
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
private int deliverKafkaLambdaPartition(Pipe pipe,
|
||||
String region,
|
||||
TopicPartition partition,
|
||||
List<ConsumerRecord<byte[], byte[]>> partitionRecords,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
Set<String> matchedIdentities,
|
||||
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit) {
|
||||
List<JsonNode> pendingBatch = new ArrayList<>();
|
||||
long pendingOffset = -1L;
|
||||
|
||||
for (ConsumerRecord<byte[], byte[]> record : partitionRecords) {
|
||||
String identity = kafkaRecordIdentity(record);
|
||||
if (!matchedIdentities.contains(identity)) {
|
||||
if (!pendingBatch.isEmpty()) {
|
||||
if (!invokeWithDlq(pipe, wrapRecords(pendingBatch), region)) {
|
||||
return pendingBatch.size();
|
||||
}
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(pendingOffset));
|
||||
pendingBatch.clear();
|
||||
}
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(record.offset() + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
JsonNode deliveryRecord = deliveryRecordsByIdentity.get(identity);
|
||||
if (deliveryRecord != null) {
|
||||
pendingBatch.add(deliveryRecord);
|
||||
pendingOffset = record.offset() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pendingBatch.isEmpty()) {
|
||||
if (!invokeWithDlq(pipe, wrapRecords(pendingBatch), region)) {
|
||||
return pendingBatch.size();
|
||||
}
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(pendingOffset));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int deliverKafkaRecords(Pipe pipe,
|
||||
String region,
|
||||
List<ConsumerRecord<byte[], byte[]>> batch,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
List<JsonNode> filtered) {
|
||||
Set<String> matchedIdentities = new HashSet<>(filtered.size());
|
||||
filtered.forEach(record -> matchedIdentities.add(kafkaRecordIdentity(record)));
|
||||
|
||||
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
|
||||
Set<TopicPartition> blockedPartitions = new HashSet<>();
|
||||
int failed = 0;
|
||||
|
||||
for (ConsumerRecord<byte[], byte[]> record : batch) {
|
||||
TopicPartition partition = new TopicPartition(record.topic(), record.partition());
|
||||
if (blockedPartitions.contains(partition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String identity = kafkaRecordIdentity(record);
|
||||
if (!matchedIdentities.contains(identity)) {
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(record.offset() + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
JsonNode deliveryRecord = deliveryRecordsByIdentity.get(identity);
|
||||
if (deliveryRecord != null && invokeWithDlq(pipe, deliveryRecord.toString(), region)) {
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(record.offset() + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
blockedPartitions.add(partition);
|
||||
failed++;
|
||||
}
|
||||
|
||||
if (!offsetsToCommit.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe, offsetsToCommit);
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
private String initDynamoDbIterator(String streamArn) {
|
||||
try {
|
||||
return dynamoDbStreamService.getShardIterator(
|
||||
@@ -469,6 +631,58 @@ public class PipesPoller {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private List<ObjectNode> buildKafkaRecordNodes(List<ConsumerRecord<byte[], byte[]>> records, Pipe pipe) {
|
||||
List<ObjectNode> nodes = new ArrayList<>();
|
||||
String eventSource = pipe.getSource().contains(":kafka:") ? "aws:kafka" : "SelfManagedKafka";
|
||||
String bootstrapServers = kafkaConsumerManager.resolveBootstrapServers(pipe);
|
||||
for (ConsumerRecord<byte[], byte[]> record : records) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("eventSource", eventSource);
|
||||
if (pipe.getSource().contains(":kafka:")) {
|
||||
node.put("eventSourceArn", pipe.getSource());
|
||||
} else {
|
||||
node.put("bootstrapServers", bootstrapServers);
|
||||
}
|
||||
node.put("topic", record.topic());
|
||||
node.put("partition", record.partition());
|
||||
node.put("offset", record.offset());
|
||||
node.put("timestamp", record.timestamp());
|
||||
node.put("timestampType", record.timestampType().name());
|
||||
putKafkaBinaryField(node, "key", record.key());
|
||||
putKafkaBinaryField(node, "value", record.value());
|
||||
|
||||
var headersNode = node.putArray("headers");
|
||||
for (Header header : record.headers()) {
|
||||
ObjectNode headerNode = objectMapper.createObjectNode();
|
||||
byte[] headerValue = header.value();
|
||||
if (headerValue == null) {
|
||||
headerNode.putNull(header.key());
|
||||
} else {
|
||||
var values = headerNode.putArray(header.key());
|
||||
for (byte b : headerValue) {
|
||||
values.add(b & 0xFF);
|
||||
}
|
||||
}
|
||||
headersNode.add(headerNode);
|
||||
}
|
||||
nodes.add(node);
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private List<ObjectNode> buildKafkaFilterNodes(List<ObjectNode> deliveryNodes,
|
||||
List<ConsumerRecord<byte[], byte[]>> records) {
|
||||
List<ObjectNode> nodes = new ArrayList<>(deliveryNodes.size());
|
||||
for (int i = 0; i < deliveryNodes.size(); i++) {
|
||||
ObjectNode node = deliveryNodes.get(i).deepCopy();
|
||||
ConsumerRecord<byte[], byte[]> record = records.get(i);
|
||||
applyDecodedKafkaField(node, "key", record.key());
|
||||
applyDecodedKafkaField(node, "value", record.value());
|
||||
nodes.add(node);
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Utilities ────────────────────────────
|
||||
|
||||
private static boolean isLambdaTarget(Pipe pipe) {
|
||||
@@ -476,6 +690,57 @@ public class PipesPoller {
|
||||
return targetArn.contains(":lambda:") || targetArn.contains(":function:");
|
||||
}
|
||||
|
||||
private static boolean isKafkaSource(String sourceArn) {
|
||||
return sourceArn.startsWith("smk://") || sourceArn.contains(":kafka:");
|
||||
}
|
||||
|
||||
private static String base64(byte[] value) {
|
||||
return Base64.getEncoder().encodeToString(value);
|
||||
}
|
||||
|
||||
private static String kafkaRecordIdentity(JsonNode record) {
|
||||
return record.path("topic").asText() + ":"
|
||||
+ record.path("partition").asText() + ":"
|
||||
+ record.path("offset").asText();
|
||||
}
|
||||
|
||||
private static String kafkaRecordIdentity(ConsumerRecord<byte[], byte[]> record) {
|
||||
return record.topic() + ":" + record.partition() + ":" + record.offset();
|
||||
}
|
||||
|
||||
private void applyDecodedKafkaField(ObjectNode node, String fieldName, byte[] value) {
|
||||
if (value == null) {
|
||||
node.putNull(fieldName);
|
||||
return;
|
||||
}
|
||||
String decoded = new String(value, StandardCharsets.UTF_8);
|
||||
try {
|
||||
JsonNode parsed = objectMapper.readTree(decoded);
|
||||
node.set(fieldName, parsed);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.debugv("Kafka {0} is not valid JSON: {1}", fieldName, e.getOriginalMessage());
|
||||
node.put(fieldName, decoded);
|
||||
}
|
||||
}
|
||||
|
||||
private void putKafkaBinaryField(ObjectNode node, String fieldName, byte[] value) {
|
||||
if (value == null) {
|
||||
node.putNull(fieldName);
|
||||
return;
|
||||
}
|
||||
node.put(fieldName, base64(value));
|
||||
}
|
||||
|
||||
private Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> groupKafkaRecordsByPartition(
|
||||
List<ConsumerRecord<byte[], byte[]>> records) {
|
||||
Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> recordsByPartition = new HashMap<>();
|
||||
for (ConsumerRecord<byte[], byte[]> record : records) {
|
||||
TopicPartition partition = new TopicPartition(record.topic(), record.partition());
|
||||
recordsByPartition.computeIfAbsent(partition, ignored -> new ArrayList<>()).add(record);
|
||||
}
|
||||
return recordsByPartition;
|
||||
}
|
||||
|
||||
private static String pipeKey(Pipe pipe) {
|
||||
return pipe.getArn();
|
||||
}
|
||||
|
||||
@@ -72,6 +72,8 @@ public class PipesService implements TagHandler {
|
||||
throw new AwsException("ValidationException", "RoleArn is required", 400);
|
||||
}
|
||||
|
||||
validateSourceConfiguration(source, sourceParameters);
|
||||
|
||||
String key = region + "::" + name;
|
||||
if (storage.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException",
|
||||
@@ -125,6 +127,8 @@ public class PipesService implements TagHandler {
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Pipe " + name + " does not exist.", 404));
|
||||
|
||||
validateSourceConfiguration(pipe.getSource(), sourceParameters != null ? sourceParameters : pipe.getSourceParameters());
|
||||
|
||||
if (target != null) pipe.setTarget(target);
|
||||
if (roleArn != null) pipe.setRoleArn(roleArn);
|
||||
if (description != null) pipe.setDescription(description);
|
||||
@@ -240,4 +244,29 @@ public class PipesService implements TagHandler {
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Resource " + arn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
private void validateSourceConfiguration(String source, JsonNode sourceParameters) {
|
||||
if (source == null) {
|
||||
return;
|
||||
}
|
||||
if (source.startsWith("smk://")) {
|
||||
requireKafkaParameters(sourceParameters, "SelfManagedKafkaParameters");
|
||||
return;
|
||||
}
|
||||
if (source.contains(":kafka:")) {
|
||||
requireKafkaParameters(sourceParameters, "ManagedStreamingKafkaParameters");
|
||||
}
|
||||
}
|
||||
|
||||
private void requireKafkaParameters(JsonNode sourceParameters, String parameterBlock) {
|
||||
if (sourceParameters == null || sourceParameters.path(parameterBlock).isMissingNode()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SourceParameters." + parameterBlock + " is required", 400);
|
||||
}
|
||||
String topicName = sourceParameters.path(parameterBlock).path("TopicName").asText(null);
|
||||
if (topicName == null || topicName.isBlank()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SourceParameters." + parameterBlock + ".TopicName is required", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user