mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(pipes): replace kafka-clients with a Kafka REST Proxy client (#3160)
kafka-clients (plus the zstd-jni and lz4-java it pulls in transitively) was an always-on dependency for Kafka-sourced Pipes, reachable in every build regardless of whether a Pipe ever used a Kafka source: MSK-backed or self-managed. This drops the dependency entirely rather than gating it, so it is no longer reachable in either a native or a JVM build. PipesKafkaConsumerManager and PipesPoller's Kafka poll/deliver path now talk to a Karapace REST Proxy sidecar (KarapaceManager starts one on demand per distinct bootstrap.servers target, shared by every pipe that reads the same cluster) instead of embedding a native Kafka consumer. PipesKafkaRestClient speaks Karapace's REST API with the JDK HttpClient, the same approach already used elsewhere in this codebase for other REST-shaped backends. Kafka record fidelity (topic, partition, offset, timestamp, key, value, headers) is preserved; timestampType is always reported as CreateTime since the REST Proxy does not expose the real value, which only diverges from a topic explicitly configured for LogAppendTime. Validated locally against a real Redpanda + Karapace pair in Docker.
This commit is contained in:
1 parent
db6c419459
commit
cd2847dba0
20 files changed
+1141
-323
No files matched your search
@@ -2192,6 +2192,25 @@ public interface EmulatorConfig {
|
||||
interface PipesServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
KafkaRestBridgeConfig kafkaRestBridge();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Karapace sidecar Pipes launches, on demand, to poll a Kafka source over REST instead of
|
||||
* embedding kafka-clients in Floci itself. One container is started per distinct target
|
||||
* {@code bootstrap.servers} (a self-managed cluster, or an MSK cluster's Redpanda backing), and
|
||||
* reused across pipes that share the same source.
|
||||
*/
|
||||
interface KafkaRestBridgeConfig {
|
||||
@WithDefault("ghcr.io/aiven-open/karapace:latest")
|
||||
String defaultImage();
|
||||
|
||||
@WithDefault("9500")
|
||||
int hostPortBase();
|
||||
|
||||
@WithDefault("9599")
|
||||
int hostPortMax();
|
||||
}
|
||||
|
||||
interface BedrockAgentCoreControlServiceConfig {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/** A Kafka REST Proxy consumer instance: its own {@code base_uri} addresses every later call. */
|
||||
record KafkaConsumerHandle(String instanceId, URI baseUri) {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
/** One Kafka record header, as decoded from a Kafka REST Proxy record response. */
|
||||
record KafkaHeaderDto(String key, byte[] value) {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
/**
|
||||
* A partition offset to commit through a Kafka REST Proxy, in place of
|
||||
* {@code org.apache.kafka.common.TopicPartition} / {@code OffsetAndMetadata}. As with the native
|
||||
* client, {@code offset} is the next offset to consume (last delivered offset + 1), not the last
|
||||
* delivered offset itself.
|
||||
*/
|
||||
record KafkaOffsetDto(String topic, int partition, long offset) {
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* One Kafka record as returned by a Kafka REST Proxy (Karapace, Pandaproxy) consumer poll, in
|
||||
* place of {@code org.apache.kafka.clients.consumer.ConsumerRecord} so Floci's own process never
|
||||
* needs {@code kafka-clients} on its classpath. See #2916.
|
||||
*
|
||||
* <p>{@code timestampType} is not part of the REST Proxy record schema (Karapace reads it
|
||||
* internally but does not expose it), so it is always reported as {@code CreateTime}, the default
|
||||
* for any topic that does not explicitly configure {@code message.timestamp.type}. This is a
|
||||
* documented, intentional deviation from the native Kafka protocol's per-record fidelity.
|
||||
*/
|
||||
record KafkaRecordDto(
|
||||
String topic,
|
||||
int partition,
|
||||
long offset,
|
||||
long timestamp,
|
||||
String timestampType,
|
||||
byte[] key,
|
||||
byte[] value,
|
||||
List<KafkaHeaderDto> headers) {
|
||||
|
||||
static final String DEFAULT_TIMESTAMP_TYPE = "CreateTime";
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
/** A Kafka topic/partition pair, used as a map key when grouping records for delivery. */
|
||||
record KafkaTopicPartition(String topic, int partition) {
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Starts, on demand, a Karapace REST Proxy sidecar fronting a Kafka {@code bootstrap.servers}
|
||||
* target, so Pipes can poll a Kafka source over plain HTTP ({@link PipesKafkaRestClient}) instead
|
||||
* of embedding {@code kafka-clients} in Floci itself. See #2916.
|
||||
*
|
||||
* <p>One container is started per distinct target and reused for the life of this process:
|
||||
* {@link #ensureStarted} is safe to call concurrently, including repeatedly for the same target
|
||||
* (multiple Pipes reading the same cluster share one Karapace instance).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
class KarapaceManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KarapaceManager.class);
|
||||
private static final int REST_PORT = 8082;
|
||||
private static final Duration READY_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
private final PortAllocator portAllocator;
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final Duration readyTimeout;
|
||||
private final Map<String, URI> restBaseUriByTarget = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> containerIdByTarget = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
KarapaceManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
PortAllocator portAllocator,
|
||||
DockerHostResolver dockerHostResolver) {
|
||||
this(containerBuilder, lifecycleManager, containerDetector, config, portAllocator, dockerHostResolver,
|
||||
READY_TIMEOUT);
|
||||
}
|
||||
|
||||
/** Test-only: overrides the readiness timeout so a failure case does not wait the full default. */
|
||||
KarapaceManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
PortAllocator portAllocator,
|
||||
DockerHostResolver dockerHostResolver,
|
||||
Duration readyTimeout) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
this.portAllocator = portAllocator;
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.readyTimeout = readyTimeout;
|
||||
}
|
||||
|
||||
URI ensureStarted(String bootstrapServers) {
|
||||
return restBaseUriByTarget.computeIfAbsent(bootstrapServers, this::startContainer);
|
||||
}
|
||||
|
||||
private URI startContainer(String bootstrapServers) {
|
||||
EmulatorConfig.KafkaRestBridgeConfig bridgeConfig = config.services().pipes().kafkaRestBridge();
|
||||
String targetKey = targetKey(bootstrapServers);
|
||||
String containerName = ContainerStorageHelper.resourceName(config, "pipes-kafka-rest", targetKey, targetKey);
|
||||
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
List<String> env = List.of(
|
||||
"KARAPACE_HOST=0.0.0.0",
|
||||
"KARAPACE_PORT=" + REST_PORT,
|
||||
"KARAPACE_BOOTSTRAP_URI=" + resolveForContainer(bootstrapServers),
|
||||
"KARAPACE_ADVERTISED_PROTOCOL=http");
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(bridgeConfig.defaultImage())
|
||||
.withName(containerName)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
// Native Linux Docker does not auto-inject host.docker.internal the way Docker
|
||||
// Desktop does, and resolveForContainer rewrites a host-local broker to exactly
|
||||
// that alias, so the sidecar needs the host-gateway mapping to resolve it.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withLogRotation()
|
||||
// The image's default entrypoint (plain `python3`) does nothing; karapace_rest_proxy
|
||||
// is the REST Proxy's own dedicated process, config-driven entirely by KARAPACE_* env.
|
||||
.withEntrypoint(List.of("/venv/bin/karapace_rest_proxy"))
|
||||
.withEnv(env)
|
||||
.withLabels(Map.of("floci.component", "pipes-kafka-rest-bridge"));
|
||||
|
||||
int hostPort = 0;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
hostPort = portAllocator.allocate(bridgeConfig.hostPortBase(), bridgeConfig.hostPortMax());
|
||||
specBuilder.withPortBinding(REST_PORT, hostPort);
|
||||
} else {
|
||||
specBuilder.withExposedPort(REST_PORT);
|
||||
}
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
ContainerInfo info;
|
||||
try {
|
||||
info = lifecycleManager.createAndStart(spec);
|
||||
} catch (RuntimeException e) {
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
portAllocator.release(hostPort);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
try {
|
||||
containerIdByTarget.put(bootstrapServers, info.containerId());
|
||||
EndpointInfo endpoint = info.getEndpoint(REST_PORT);
|
||||
URI restBaseUri = URI.create("http://" + endpoint.host() + ":" + endpoint.port() + "/");
|
||||
waitUntilReady(restBaseUri);
|
||||
LOG.infov("Karapace REST Proxy {0} started for bootstrap {1}", info.containerId(), bootstrapServers);
|
||||
return restBaseUri;
|
||||
} catch (RuntimeException e) {
|
||||
containerIdByTarget.remove(bootstrapServers);
|
||||
lifecycleManager.stopAndRemove(info.containerId(), null);
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
portAllocator.release(hostPort);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a host-local address (localhost/127.0.0.1) so the sidecar, in its own network
|
||||
* namespace, can reach a broker on the Floci host instead of trying to reach itself. Applies
|
||||
* to both self-managed sources given as {@code smk://localhost:9092} and, in native mode, an
|
||||
* MSK-backed Redpanda cluster whose advertised address is also {@code localhost:<port>}.
|
||||
*/
|
||||
private String resolveForContainer(String bootstrapServers) {
|
||||
return Arrays.stream(bootstrapServers.split(","))
|
||||
.map(this::resolveHostLocalAddress)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
private String resolveHostLocalAddress(String hostPort) {
|
||||
int colonIndex = hostPort.lastIndexOf(':');
|
||||
if (colonIndex < 0) {
|
||||
return hostPort;
|
||||
}
|
||||
String host = hostPort.substring(0, colonIndex);
|
||||
if (host.equals("localhost") || host.equals("127.0.0.1")) {
|
||||
return dockerHostResolver.resolve() + hostPort.substring(colonIndex);
|
||||
}
|
||||
return hostPort;
|
||||
}
|
||||
|
||||
private void waitUntilReady(URI restBaseUri) {
|
||||
long deadline = System.nanoTime() + readyTimeout.toNanos();
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (isReady(restBaseUri)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.min(200, Math.max(1, readyTimeout.toMillis() / 4)));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted waiting for Karapace to become ready at " + restBaseUri, e);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Karapace REST Proxy at " + restBaseUri + " did not become ready within "
|
||||
+ readyTimeout.toMillis() + "ms");
|
||||
}
|
||||
|
||||
private boolean isReady(URI restBaseUri) {
|
||||
try {
|
||||
HttpURLConnection conn = (HttpURLConnection) restBaseUri.resolve("_health").toURL().openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(1000);
|
||||
conn.setReadTimeout(1000);
|
||||
return conn.getResponseCode() == 200;
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Karapace not ready yet at {0}: {1}", restBaseUri, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String targetKey(String bootstrapServers) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest(bootstrapServers.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(hash, 0, 8);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
containerIdByTarget.values().forEach(containerId -> {
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Failed to stop Karapace container {0}: {1}", containerId, e.getMessage());
|
||||
}
|
||||
});
|
||||
containerIdByTarget.clear();
|
||||
restBaseUriByTarget.clear();
|
||||
}
|
||||
}
|
||||
+42
-60
@@ -8,22 +8,21 @@ 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.net.URI;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Polls Kafka pipe sources (MSK and self-managed, {@code smk://}) over a Kafka REST Proxy
|
||||
* (Karapace) instead of embedding {@code kafka-clients} directly: see #2916, where kafka-clients
|
||||
* and the zstd-jni/lz4-java it pulls in were reachable in every build regardless of whether a
|
||||
* Pipe ever used a Kafka source. {@link KarapaceManager} starts a Karapace sidecar per distinct
|
||||
* target on demand, and {@link PipesKafkaRestClient} speaks its REST API.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PipesKafkaConsumerManager {
|
||||
|
||||
@@ -32,11 +31,16 @@ public class PipesKafkaConsumerManager {
|
||||
private static final String DEFAULT_STARTING_POSITION = "LATEST";
|
||||
|
||||
private final MskService mskService;
|
||||
private final ConcurrentHashMap<String, KafkaConsumer<byte[], byte[]>> consumers = new ConcurrentHashMap<>();
|
||||
private final KarapaceManager karapaceManager;
|
||||
private final PipesKafkaRestClient restClient;
|
||||
private final ConcurrentHashMap<String, KafkaConsumerHandle> consumers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public PipesKafkaConsumerManager(MskService mskService) {
|
||||
public PipesKafkaConsumerManager(MskService mskService, KarapaceManager karapaceManager,
|
||||
PipesKafkaRestClient restClient) {
|
||||
this.mskService = mskService;
|
||||
this.karapaceManager = karapaceManager;
|
||||
this.restClient = restClient;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -45,39 +49,26 @@ public class PipesKafkaConsumerManager {
|
||||
consumers.clear();
|
||||
}
|
||||
|
||||
public ConsumerRecords<byte[], byte[]> poll(Pipe pipe) {
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.computeIfAbsent(pipe.getArn(), ignored -> createConsumer(pipe));
|
||||
public List<KafkaRecordDto> poll(Pipe pipe) {
|
||||
KafkaConsumerHandle consumer = consumers.computeIfAbsent(pipe.getArn(), ignored -> createConsumer(pipe));
|
||||
try {
|
||||
return consumer.poll(POLL_TIMEOUT);
|
||||
return restClient.poll(consumer, 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) {
|
||||
public void commit(Pipe pipe, List<KafkaOffsetDto> offsets) {
|
||||
if (offsets.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.get(pipe.getArn());
|
||||
KafkaConsumerHandle consumer = consumers.get(pipe.getArn());
|
||||
if (consumer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
consumer.commitSync(offsets);
|
||||
restClient.commit(consumer, offsets);
|
||||
} catch (RuntimeException e) {
|
||||
close(pipe);
|
||||
throw e;
|
||||
@@ -85,7 +76,7 @@ public class PipesKafkaConsumerManager {
|
||||
}
|
||||
|
||||
public void close(Pipe pipe) {
|
||||
KafkaConsumer<byte[], byte[]> consumer = consumers.remove(pipe.getArn());
|
||||
KafkaConsumerHandle consumer = consumers.remove(pipe.getArn());
|
||||
if (consumer != null) {
|
||||
closeQuietly(consumer);
|
||||
}
|
||||
@@ -131,34 +122,25 @@ public class PipesKafkaConsumerManager {
|
||||
return resolveConsumerGroupId(pipe, kafkaParameters(pipe));
|
||||
}
|
||||
|
||||
/** Package-private so {@code PipesKafkaNativeSupportTest} guards the real settings, not a copy. */
|
||||
Properties consumerProperties(Pipe pipe) {
|
||||
JsonNode params = kafkaParameters(pipe);
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, resolveBootstrapServers(pipe));
|
||||
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)));
|
||||
// On by default (KIP-714). Floci has no reason to push metrics to a user's broker, and it
|
||||
// makes the shaded protobuf serializer reflectively reachable on a path no broker we test
|
||||
// against exercises.
|
||||
properties.put(ConsumerConfig.ENABLE_METRICS_PUSH_CONFIG, "false");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private KafkaConsumer<byte[], byte[]> createConsumer(Pipe pipe) {
|
||||
Properties properties = consumerProperties(pipe);
|
||||
private KafkaConsumerHandle createConsumer(Pipe pipe) {
|
||||
String bootstrapServers = resolveBootstrapServers(pipe);
|
||||
String topicName = resolveTopicName(pipe);
|
||||
String groupId = resolveConsumerGroupId(pipe);
|
||||
String offsetReset = resolveOffsetReset(kafkaParameters(pipe));
|
||||
|
||||
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, properties.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG));
|
||||
URI restBaseUri = karapaceManager.ensureStarted(bootstrapServers);
|
||||
KafkaConsumerHandle consumer = restClient.createConsumer(restBaseUri, groupId, offsetReset);
|
||||
try {
|
||||
restClient.subscribe(consumer, List.of(topicName));
|
||||
} catch (RuntimeException e) {
|
||||
// The consumer already exists server-side; this method's caller only learns about it
|
||||
// through the returned handle, so a failure here must delete it itself or it is never
|
||||
// reachable again to close, and every retry creates another orphaned server consumer.
|
||||
closeQuietly(consumer);
|
||||
throw e;
|
||||
}
|
||||
LOG.infov("Pipe {0}: subscribed Kafka REST consumer to topic {1} via {2}",
|
||||
pipe.getName(), topicName, bootstrapServers);
|
||||
return consumer;
|
||||
}
|
||||
|
||||
@@ -210,11 +192,11 @@ public class PipesKafkaConsumerManager {
|
||||
throw new AwsException("ValidationException", "Unsupported Kafka source: " + pipe.getSource(), 400);
|
||||
}
|
||||
|
||||
private void closeQuietly(KafkaConsumer<byte[], byte[]> consumer) {
|
||||
private void closeQuietly(KafkaConsumerHandle consumer) {
|
||||
try {
|
||||
consumer.close();
|
||||
restClient.close(consumer);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Ignoring Kafka consumer close error: {0}", e.getMessage());
|
||||
LOG.debugv("Ignoring Kafka REST consumer close error: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.apache.kafka.clients.consumer.CooperativeStickyAssignor;
|
||||
import org.apache.kafka.clients.consumer.RangeAssignor;
|
||||
import org.apache.kafka.common.metrics.JmxReporter;
|
||||
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
|
||||
|
||||
/**
|
||||
* Registers the kafka-clients classes that GraalVM cannot discover statically.
|
||||
*
|
||||
* <p>kafka-clients ships no native-image metadata and Floci uses it directly rather than through
|
||||
* the Quarkus Kafka extension. {@code AbstractConfig} resolves {@code CLASS}-typed settings by
|
||||
* name, so without these a native build cannot construct a consumer — which {@link PipesPoller}
|
||||
* swallows per poll cycle, leaving the pipe RUNNING and delivering nothing.
|
||||
*
|
||||
* <p>Entries are exactly what {@link PipesKafkaConsumerManager#consumerProperties} resolves, and
|
||||
* {@code PipesKafkaNativeSupportTest} reads that same method, so the two cannot drift.
|
||||
*
|
||||
* <p>SASL and SSL defaults are excluded: Floci is PLAINTEXT-only, and {@code DefaultJwtValidator}
|
||||
* fails the native build by referencing jose4j, an optional dependency Floci omits.
|
||||
*/
|
||||
@RegisterForReflection(targets = {
|
||||
// key.deserializer / value.deserializer — set explicitly by PipesKafkaConsumerManager
|
||||
ByteArrayDeserializer.class,
|
||||
// partition.assignment.strategy — ConsumerConfig defaults
|
||||
RangeAssignor.class,
|
||||
CooperativeStickyAssignor.class,
|
||||
// metric.reporters — ConsumerConfig default
|
||||
JmxReporter.class
|
||||
})
|
||||
public class PipesKafkaNativeSupport {
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.NullNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Thin REST client for the subset of the Kafka REST Proxy v2 API (Karapace, Redpanda's
|
||||
* Pandaproxy) that Pipes needs to consume a Kafka topic: create a consumer instance, subscribe,
|
||||
* poll for records, commit offsets, close. Uses the JDK {@link HttpClient}, the same approach
|
||||
* Floci already uses for other REST-shaped backends (e.g. {@code KubernetesApiClient}), instead
|
||||
* of embedding {@code kafka-clients} directly: see #2916, where kafka-clients (and the
|
||||
* zstd-jni/lz4-java it pulls in) was reachable in every native image regardless of whether a Pipe
|
||||
* ever used a Kafka source.
|
||||
*
|
||||
* <p>Every consumer instance lives on exactly one REST Proxy process for its whole lifetime (the
|
||||
* proxy holds the actual Kafka client state), so all calls for a given {@link KafkaConsumerHandle}
|
||||
* must keep going to the {@code base_uri} that instance's creation call returned.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
class PipesKafkaRestClient {
|
||||
|
||||
private static final String CONSUMER_CONTENT_TYPE = "application/vnd.kafka.v2+json";
|
||||
private static final String BINARY_RECORDS_ACCEPT = "application/vnd.kafka.binary.v2+json";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
PipesKafkaRestClient(ObjectMapper objectMapper) {
|
||||
this(objectMapper, HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.executor(Executors.newVirtualThreadPerTaskExecutor())
|
||||
.build());
|
||||
}
|
||||
|
||||
/** Test-only: injects an explicit client, e.g. one pointed at a fake REST Proxy server. */
|
||||
PipesKafkaRestClient(ObjectMapper objectMapper, HttpClient httpClient) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
KafkaConsumerHandle createConsumer(URI restBaseUri, String groupId, String offsetReset) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("format", "binary");
|
||||
body.put("auto.offset.reset", offsetReset);
|
||||
body.put("auto.commit.enable", "false");
|
||||
|
||||
JsonNode response = send("POST", restBaseUri.resolve("consumers/" + urlEncode(groupId)), body);
|
||||
// Karapace returns base_uri as a path relative to the proxy root, not an absolute URL,
|
||||
// unlike the Confluent REST Proxy reference spec; resolve() handles both correctly.
|
||||
return new KafkaConsumerHandle(
|
||||
response.path("instance_id").asText(),
|
||||
restBaseUri.resolve(response.path("base_uri").asText()));
|
||||
}
|
||||
|
||||
void subscribe(KafkaConsumerHandle consumer, List<String> topics) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
ArrayNode topicsNode = body.putArray("topics");
|
||||
topics.forEach(topicsNode::add);
|
||||
send("POST", instanceUri(consumer, "subscription"), body);
|
||||
}
|
||||
|
||||
List<KafkaRecordDto> poll(KafkaConsumerHandle consumer, Duration timeout) {
|
||||
URI uri = URI.create(instanceUri(consumer, "records") + "?timeout=" + timeout.toMillis());
|
||||
JsonNode response = sendWithAccept("GET", uri, null, BINARY_RECORDS_ACCEPT);
|
||||
|
||||
List<KafkaRecordDto> records = new ArrayList<>();
|
||||
response.forEach(node -> records.add(toRecord(node)));
|
||||
return records;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits the given offsets. Karapace requires an explicit offsets list (unlike the Confluent
|
||||
* REST Proxy reference spec, an empty body is rejected with 400 rather than committing
|
||||
* everything consumed), so callers always compute what to commit themselves.
|
||||
*/
|
||||
void commit(KafkaConsumerHandle consumer, List<KafkaOffsetDto> offsets) {
|
||||
if (offsets.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
ArrayNode offsetsNode = body.putArray("offsets");
|
||||
for (KafkaOffsetDto offset : offsets) {
|
||||
ObjectNode offsetNode = offsetsNode.addObject();
|
||||
offsetNode.put("topic", offset.topic());
|
||||
offsetNode.put("partition", offset.partition());
|
||||
offsetNode.put("offset", offset.offset());
|
||||
}
|
||||
send("POST", instanceUri(consumer, "offsets"), body);
|
||||
}
|
||||
|
||||
/** No-op if the consumer instance is already gone (e.g. the REST Proxy container restarted). */
|
||||
void close(KafkaConsumerHandle consumer) {
|
||||
try {
|
||||
send("DELETE", consumer.baseUri(), null);
|
||||
} catch (PipesKafkaRestClientException e) {
|
||||
if (e.getStatusCode() != 404) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private KafkaRecordDto toRecord(JsonNode node) {
|
||||
List<KafkaHeaderDto> headers = new ArrayList<>();
|
||||
for (JsonNode headerNode : node.path("headers")) {
|
||||
headers.add(new KafkaHeaderDto(
|
||||
headerNode.path("name").asText(),
|
||||
base64Decode(headerNode.path("value"))));
|
||||
}
|
||||
return new KafkaRecordDto(
|
||||
node.path("topic").asText(),
|
||||
node.path("partition").asInt(),
|
||||
node.path("offset").asLong(),
|
||||
node.path("timestamp").asLong(0),
|
||||
KafkaRecordDto.DEFAULT_TIMESTAMP_TYPE,
|
||||
base64Decode(node.path("key")),
|
||||
base64Decode(node.path("value")),
|
||||
headers);
|
||||
}
|
||||
|
||||
private static byte[] base64Decode(JsonNode value) {
|
||||
if (value == null || value.isNull() || value.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getDecoder().decode(value.asText());
|
||||
}
|
||||
|
||||
private URI instanceUri(KafkaConsumerHandle consumer, String segment) {
|
||||
String base = consumer.baseUri().toString();
|
||||
return URI.create((base.endsWith("/") ? base : base + "/") + segment);
|
||||
}
|
||||
|
||||
private JsonNode send(String method, URI uri, JsonNode body) {
|
||||
return sendWithAccept(method, uri, body, CONSUMER_CONTENT_TYPE);
|
||||
}
|
||||
|
||||
private JsonNode sendWithAccept(String method, URI uri, JsonNode body, String accept) {
|
||||
try {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(uri)
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Accept", accept);
|
||||
if (body != null) {
|
||||
builder.header("Content-Type", CONSUMER_CONTENT_TYPE)
|
||||
.method(method, HttpRequest.BodyPublishers.ofByteArray(objectMapper.writeValueAsBytes(body)));
|
||||
} else {
|
||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
}
|
||||
|
||||
HttpResponse<byte[]> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() / 100 != 2) {
|
||||
throw new PipesKafkaRestClientException(method, uri.toString(), response.statusCode(),
|
||||
new String(response.body(), StandardCharsets.UTF_8));
|
||||
}
|
||||
return response.body().length == 0 ? NullNode.getInstance() : objectMapper.readTree(response.body());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(
|
||||
"Kafka REST Proxy " + method + " " + uri + " failed: " + e.getMessage(), e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted calling Kafka REST Proxy " + method + " " + uri, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String urlEncode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
/** A Kafka REST Proxy (Karapace) response outside the expected 2xx status for its call. */
|
||||
class PipesKafkaRestClientException extends RuntimeException {
|
||||
|
||||
private final int statusCode;
|
||||
|
||||
PipesKafkaRestClientException(String method, String path, int statusCode, String body) {
|
||||
super("Kafka REST Proxy " + method + " " + path + " failed: HTTP " + statusCode
|
||||
+ (body == null || body.isBlank() ? "" : " " + body));
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,6 @@ 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;
|
||||
@@ -341,20 +336,41 @@ public class PipesPoller implements Resettable {
|
||||
}
|
||||
|
||||
void pollKafka(Pipe pipe, String region) {
|
||||
ConsumerRecords<byte[], byte[]> records = kafkaConsumerManager.poll(pipe);
|
||||
List<KafkaRecordDto> 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(), records.size());
|
||||
int batchSize = kafkaConsumerManager.resolveBatchSize(pipe, DEFAULT_BATCH_SIZE);
|
||||
Set<KafkaTopicPartition> blockedPartitions = new HashSet<>();
|
||||
for (List<KafkaRecordDto> batch : partition(records, batchSize)) {
|
||||
deliverKafkaBatch(pipe, region, batch, blockedPartitions);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
/**
|
||||
* A REST Proxy poll can return more records than one Pipe {@code BatchSize} worth (unlike the
|
||||
* native consumer, it has no per-call record cap), so one poll cycle may deliver several
|
||||
* batches in sequence. {@code blockedPartitions} is shared across that whole sequence: once a
|
||||
* partition fails delivery in one batch, its records in every later batch this cycle are left
|
||||
* uncommitted too, so a later batch's success can never commit past an earlier record that is
|
||||
* still awaiting redelivery.
|
||||
*/
|
||||
private void deliverKafkaBatch(Pipe pipe, String region, List<KafkaRecordDto> batch,
|
||||
Set<KafkaTopicPartition> blockedPartitions) {
|
||||
List<KafkaRecordDto> deliverable = batch.stream()
|
||||
.filter(record -> !blockedPartitions.contains(new KafkaTopicPartition(record.topic(), record.partition())))
|
||||
.toList();
|
||||
if (deliverable.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<ObjectNode> deliveryNodes = buildKafkaRecordNodes(deliverable, pipe);
|
||||
List<ObjectNode> filterNodes = buildKafkaFilterNodes(deliveryNodes, deliverable);
|
||||
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(new ArrayList<>(filterNodes), pipe.getSourceParameters());
|
||||
if (filtered.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe);
|
||||
commitWholeBatch(pipe, deliverable);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -371,13 +387,13 @@ public class PipesPoller implements Resettable {
|
||||
}
|
||||
}
|
||||
if (deliveryRecords.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe);
|
||||
commitWholeBatch(pipe, deliverable);
|
||||
return;
|
||||
}
|
||||
|
||||
int failed = isLambdaTarget(pipe)
|
||||
? deliverKafkaLambdaRecords(pipe, region, batch, deliveryRecordsByIdentity, filtered)
|
||||
: deliverKafkaRecords(pipe, region, batch, deliveryRecordsByIdentity, filtered);
|
||||
? deliverKafkaLambdaRecords(pipe, region, deliverable, deliveryRecordsByIdentity, filtered, blockedPartitions)
|
||||
: deliverKafkaRecords(pipe, region, deliverable, deliveryRecordsByIdentity, filtered, blockedPartitions);
|
||||
if (failed == 0) {
|
||||
return;
|
||||
}
|
||||
@@ -388,48 +404,51 @@ public class PipesPoller implements Resettable {
|
||||
|
||||
private int deliverKafkaLambdaRecords(Pipe pipe,
|
||||
String region,
|
||||
List<ConsumerRecord<byte[], byte[]>> batch,
|
||||
List<KafkaRecordDto> batch,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
List<JsonNode> filtered) {
|
||||
List<JsonNode> filtered,
|
||||
Set<KafkaTopicPartition> blockedPartitions) {
|
||||
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);
|
||||
Map<KafkaTopicPartition, Long> offsetsToCommit = new HashMap<>();
|
||||
Map<KafkaTopicPartition, List<KafkaRecordDto>> 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(),
|
||||
for (Map.Entry<KafkaTopicPartition, List<KafkaRecordDto>> entry : recordsByPartition.entrySet()) {
|
||||
int partitionFailed = deliverKafkaLambdaPartition(pipe, region, entry.getKey(), entry.getValue(),
|
||||
deliveryRecordsByIdentity, matchedIdentities, offsetsToCommit);
|
||||
if (partitionFailed > 0) {
|
||||
blockedPartitions.add(entry.getKey());
|
||||
}
|
||||
failed += partitionFailed;
|
||||
}
|
||||
|
||||
if (!offsetsToCommit.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe, offsetsToCommit);
|
||||
}
|
||||
commitOffsets(pipe, offsetsToCommit);
|
||||
return failed;
|
||||
}
|
||||
|
||||
private int deliverKafkaLambdaPartition(Pipe pipe,
|
||||
String region,
|
||||
TopicPartition partition,
|
||||
List<ConsumerRecord<byte[], byte[]>> partitionRecords,
|
||||
KafkaTopicPartition partition,
|
||||
List<KafkaRecordDto> partitionRecords,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
Set<String> matchedIdentities,
|
||||
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit) {
|
||||
Map<KafkaTopicPartition, Long> offsetsToCommit) {
|
||||
List<JsonNode> pendingBatch = new ArrayList<>();
|
||||
long pendingOffset = -1L;
|
||||
|
||||
for (ConsumerRecord<byte[], byte[]> record : partitionRecords) {
|
||||
for (KafkaRecordDto 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));
|
||||
offsetsToCommit.put(partition, pendingOffset);
|
||||
pendingBatch.clear();
|
||||
}
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(record.offset() + 1));
|
||||
offsetsToCommit.put(partition, record.offset() + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -444,38 +463,38 @@ public class PipesPoller implements Resettable {
|
||||
if (!invokeWithDlq(pipe, wrapRecords(pendingBatch), region)) {
|
||||
return pendingBatch.size();
|
||||
}
|
||||
offsetsToCommit.put(partition, new OffsetAndMetadata(pendingOffset));
|
||||
offsetsToCommit.put(partition, pendingOffset);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int deliverKafkaRecords(Pipe pipe,
|
||||
String region,
|
||||
List<ConsumerRecord<byte[], byte[]>> batch,
|
||||
List<KafkaRecordDto> batch,
|
||||
Map<String, JsonNode> deliveryRecordsByIdentity,
|
||||
List<JsonNode> filtered) {
|
||||
List<JsonNode> filtered,
|
||||
Set<KafkaTopicPartition> blockedPartitions) {
|
||||
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<>();
|
||||
Map<KafkaTopicPartition, Long> offsetsToCommit = new HashMap<>();
|
||||
int failed = 0;
|
||||
|
||||
for (ConsumerRecord<byte[], byte[]> record : batch) {
|
||||
TopicPartition partition = new TopicPartition(record.topic(), record.partition());
|
||||
for (KafkaRecordDto record : batch) {
|
||||
KafkaTopicPartition partition = new KafkaTopicPartition(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));
|
||||
offsetsToCommit.put(partition, 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));
|
||||
offsetsToCommit.put(partition, record.offset() + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -483,9 +502,7 @@ public class PipesPoller implements Resettable {
|
||||
failed++;
|
||||
}
|
||||
|
||||
if (!offsetsToCommit.isEmpty()) {
|
||||
kafkaConsumerManager.commit(pipe, offsetsToCommit);
|
||||
}
|
||||
commitOffsets(pipe, offsetsToCommit);
|
||||
return failed;
|
||||
}
|
||||
|
||||
@@ -722,11 +739,11 @@ public class PipesPoller implements Resettable {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private List<ObjectNode> buildKafkaRecordNodes(List<ConsumerRecord<byte[], byte[]>> records, Pipe pipe) {
|
||||
private List<ObjectNode> buildKafkaRecordNodes(List<KafkaRecordDto> 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) {
|
||||
for (KafkaRecordDto record : records) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("eventSource", eventSource);
|
||||
if (pipe.getSource().contains(":kafka:")) {
|
||||
@@ -738,12 +755,12 @@ public class PipesPoller implements Resettable {
|
||||
node.put("partition", record.partition());
|
||||
node.put("offset", record.offset());
|
||||
node.put("timestamp", record.timestamp());
|
||||
node.put("timestampType", record.timestampType().name());
|
||||
node.put("timestampType", record.timestampType());
|
||||
putKafkaBinaryField(node, "key", record.key());
|
||||
putKafkaBinaryField(node, "value", record.value());
|
||||
|
||||
var headersNode = node.putArray("headers");
|
||||
for (Header header : record.headers()) {
|
||||
for (KafkaHeaderDto header : record.headers()) {
|
||||
ObjectNode headerNode = objectMapper.createObjectNode();
|
||||
byte[] headerValue = header.value();
|
||||
if (headerValue == null) {
|
||||
@@ -761,12 +778,11 @@ public class PipesPoller implements Resettable {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private List<ObjectNode> buildKafkaFilterNodes(List<ObjectNode> deliveryNodes,
|
||||
List<ConsumerRecord<byte[], byte[]>> records) {
|
||||
private List<ObjectNode> buildKafkaFilterNodes(List<ObjectNode> deliveryNodes, List<KafkaRecordDto> 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);
|
||||
KafkaRecordDto record = records.get(i);
|
||||
applyDecodedKafkaField(node, "key", record.key());
|
||||
applyDecodedKafkaField(node, "value", record.value());
|
||||
nodes.add(node);
|
||||
@@ -795,7 +811,7 @@ public class PipesPoller implements Resettable {
|
||||
+ record.path("offset").asText();
|
||||
}
|
||||
|
||||
private static String kafkaRecordIdentity(ConsumerRecord<byte[], byte[]> record) {
|
||||
private static String kafkaRecordIdentity(KafkaRecordDto record) {
|
||||
return record.topic() + ":" + record.partition() + ":" + record.offset();
|
||||
}
|
||||
|
||||
@@ -822,16 +838,49 @@ public class PipesPoller implements Resettable {
|
||||
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());
|
||||
private Map<KafkaTopicPartition, List<KafkaRecordDto>> groupKafkaRecordsByPartition(List<KafkaRecordDto> records) {
|
||||
Map<KafkaTopicPartition, List<KafkaRecordDto>> recordsByPartition = new HashMap<>();
|
||||
for (KafkaRecordDto record : records) {
|
||||
KafkaTopicPartition partition = new KafkaTopicPartition(record.topic(), record.partition());
|
||||
recordsByPartition.computeIfAbsent(partition, ignored -> new ArrayList<>()).add(record);
|
||||
}
|
||||
return recordsByPartition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits past every record in {@code batch}, for when none of them are being delivered (no
|
||||
* filter match). The REST Proxy has no "commit everything consumed" shortcut (unlike the
|
||||
* native consumer's no-args {@code commitSync()}), so this computes the equivalent explicitly:
|
||||
* the highest offset seen per partition, plus one.
|
||||
*/
|
||||
private void commitWholeBatch(Pipe pipe, List<KafkaRecordDto> batch) {
|
||||
Map<KafkaTopicPartition, Long> offsetsToCommit = new HashMap<>();
|
||||
for (KafkaRecordDto record : batch) {
|
||||
KafkaTopicPartition partition = new KafkaTopicPartition(record.topic(), record.partition());
|
||||
offsetsToCommit.merge(partition, record.offset() + 1, Math::max);
|
||||
}
|
||||
commitOffsets(pipe, offsetsToCommit);
|
||||
}
|
||||
|
||||
private void commitOffsets(Pipe pipe, Map<KafkaTopicPartition, Long> offsetsToCommit) {
|
||||
if (offsetsToCommit.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<KafkaOffsetDto> offsets = new ArrayList<>(offsetsToCommit.size());
|
||||
offsetsToCommit.forEach((partition, offset) ->
|
||||
offsets.add(new KafkaOffsetDto(partition.topic(), partition.partition(), offset)));
|
||||
kafkaConsumerManager.commit(pipe, offsets);
|
||||
}
|
||||
|
||||
private static <T> List<List<T>> partition(List<T> list, int size) {
|
||||
int step = Math.max(1, size);
|
||||
List<List<T>> partitions = new ArrayList<>();
|
||||
for (int i = 0; i < list.size(); i += step) {
|
||||
partitions.add(list.subList(i, Math.min(i + step, list.size())));
|
||||
}
|
||||
return partitions;
|
||||
}
|
||||
|
||||
private static String pipeKey(Pipe pipe) {
|
||||
return pipe.getArn();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user