mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
refactor(kafka): share the Kafka REST Proxy bridge and add partition assignment and seeking (#9170)
Move KarapaceManager and the Kafka REST Proxy v2 client out of the package-private services/pipes into core/common/kafka so other services can consume Kafka topics. Pipes behavior, the floci.services.pipes.kafka-rest-bridge.* config keys and the container naming and labels are unchanged.
Extend the client with the operations Redshift streaming ingestion needs: topic partition discovery (a missing topic raises KafkaTopicNotFoundException, distinct from broker or proxy failures), manual partition assignment, and explicit per-partition offset seeking. Partitions are listed through GET /topics/{topic}/partitions, where Karapace answers a missing topic with error_code 40401.
Part of #7814
This commit is contained in:
1 parent
f41fad028c
commit
351973d3f8
19 files changed
+412
-64
No files matched your search
+2
-2
@@ -1,7 +1,7 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
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) {
|
||||
public record KafkaConsumerHandle(String instanceId, URI baseUri) {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
/** One Kafka record header, as decoded from a Kafka REST Proxy record response. */
|
||||
public record KafkaHeaderDto(String key, byte[] value) {
|
||||
}
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
/**
|
||||
* A partition offset to commit through a Kafka REST Proxy, in place of
|
||||
@@ -6,5 +6,5 @@ package io.floci.aws.services.pipes;
|
||||
* 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) {
|
||||
public record KafkaOffsetDto(String topic, int partition, long offset) {
|
||||
}
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -12,7 +12,7 @@ import java.util.List;
|
||||
* 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(
|
||||
public record KafkaRecordDto(
|
||||
String topic,
|
||||
int partition,
|
||||
long offset,
|
||||
@@ -22,5 +22,5 @@ record KafkaRecordDto(
|
||||
byte[] value,
|
||||
List<KafkaHeaderDto> headers) {
|
||||
|
||||
static final String DEFAULT_TIMESTAMP_TYPE = "CreateTime";
|
||||
public static final String DEFAULT_TIMESTAMP_TYPE = "CreateTime";
|
||||
}
|
||||
+107
-15
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -24,28 +24,30 @@ 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
|
||||
* Pandaproxy) that Floci services need to consume a Kafka topic: discover a topic's partitions,
|
||||
* create a consumer instance, subscribe or assign partitions manually, seek, 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.
|
||||
* zstd-jni/lz4-java it pulls in) was reachable in every native image regardless of whether a Kafka
|
||||
* consumer was ever used.
|
||||
*
|
||||
* <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 {
|
||||
public class KafkaRestClient {
|
||||
|
||||
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 static final int ERROR_CODE_TOPIC_NOT_FOUND = 40401;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
PipesKafkaRestClient(ObjectMapper objectMapper) {
|
||||
KafkaRestClient(ObjectMapper objectMapper) {
|
||||
this(objectMapper, HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.executor(Executors.newVirtualThreadPerTaskExecutor())
|
||||
@@ -53,12 +55,12 @@ class PipesKafkaRestClient {
|
||||
}
|
||||
|
||||
/** Test-only: injects an explicit client, e.g. one pointed at a fake REST Proxy server. */
|
||||
PipesKafkaRestClient(ObjectMapper objectMapper, HttpClient httpClient) {
|
||||
KafkaRestClient(ObjectMapper objectMapper, HttpClient httpClient) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
KafkaConsumerHandle createConsumer(URI restBaseUri, String groupId, String offsetReset) {
|
||||
public KafkaConsumerHandle createConsumer(URI restBaseUri, String groupId, String offsetReset) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("format", "binary");
|
||||
body.put("auto.offset.reset", offsetReset);
|
||||
@@ -72,14 +74,104 @@ class PipesKafkaRestClient {
|
||||
restBaseUri.resolve(response.path("base_uri").asText()));
|
||||
}
|
||||
|
||||
void subscribe(KafkaConsumerHandle consumer, List<String> topics) {
|
||||
public 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) {
|
||||
/**
|
||||
* Lists the partition ids of a topic ({@code GET /topics/{topic}/partitions}). A topic the broker
|
||||
* does not know raises {@link KafkaTopicNotFoundException}, distinct from the
|
||||
* {@link KafkaRestClientException} / {@link UncheckedIOException} a broker or proxy failure raises,
|
||||
* so a caller can tell a missing topic from an unreachable cluster.
|
||||
*
|
||||
* <p>{@code /topics/{topic}/partitions} is used rather than {@code /topics/{topic}} because Karapace
|
||||
* answers a missing topic on the latter with 40403 (from the admin metadata lookup), while the
|
||||
* former maps it to 40401 and returns the partition array directly.
|
||||
*/
|
||||
public List<Integer> listPartitions(URI restBaseUri, String topic) {
|
||||
JsonNode response;
|
||||
try {
|
||||
response = send("GET", restBaseUri.resolve("topics/" + urlEncode(topic) + "/partitions"), null);
|
||||
} catch (KafkaRestClientException e) {
|
||||
if (e.getStatusCode() == 404 && isTopicNotFoundError(e.getResponseBody())) {
|
||||
throw new KafkaTopicNotFoundException(topic, e);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
List<Integer> partitions = new ArrayList<>();
|
||||
for (JsonNode partitionNode : response) {
|
||||
partitions.add(partitionNode.path("partition").asInt());
|
||||
}
|
||||
partitions.sort(Integer::compare);
|
||||
return partitions;
|
||||
}
|
||||
|
||||
private boolean isTopicNotFoundError(String responseBody) {
|
||||
if (responseBody == null || responseBody.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(responseBody);
|
||||
if (root == null) {
|
||||
return false;
|
||||
}
|
||||
JsonNode errorCode = root.path("error_code");
|
||||
return errorCode.isIntegralNumber() && errorCode.asInt() == ERROR_CODE_TOPIC_NOT_FOUND;
|
||||
} catch (IOException ignored) {
|
||||
// Non-JSON 404 body (e.g. wrong base path or reverse proxy page) is not a Karapace topic-not-found error.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns partitions manually instead of {@link #subscribe}, so a poll covers exactly these
|
||||
* partitions with no group rebalance deciding which ones this consumer owns.
|
||||
*/
|
||||
public void assign(KafkaConsumerHandle consumer, List<KafkaTopicPartition> partitions) {
|
||||
send("POST", instanceUri(consumer, "assignments"), partitionsBody(partitions));
|
||||
}
|
||||
|
||||
/**
|
||||
* Positions each partition at the given offset, which is the next offset to read, so the caller
|
||||
* controls where a poll resumes instead of relying on broker-side committed group offsets.
|
||||
*/
|
||||
public void seek(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, "positions"), body);
|
||||
}
|
||||
|
||||
public void seekToBeginning(KafkaConsumerHandle consumer, List<KafkaTopicPartition> partitions) {
|
||||
if (partitions.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
send("POST", instanceUri(consumer, "positions/beginning"), partitionsBody(partitions));
|
||||
}
|
||||
|
||||
private ObjectNode partitionsBody(List<KafkaTopicPartition> partitions) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
ArrayNode partitionsNode = body.putArray("partitions");
|
||||
for (KafkaTopicPartition partition : partitions) {
|
||||
ObjectNode partitionNode = partitionsNode.addObject();
|
||||
partitionNode.put("topic", partition.topic());
|
||||
partitionNode.put("partition", partition.partition());
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
public 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);
|
||||
|
||||
@@ -93,7 +185,7 @@ class PipesKafkaRestClient {
|
||||
* 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) {
|
||||
public void commit(KafkaConsumerHandle consumer, List<KafkaOffsetDto> offsets) {
|
||||
if (offsets.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -109,10 +201,10 @@ class PipesKafkaRestClient {
|
||||
}
|
||||
|
||||
/** No-op if the consumer instance is already gone (e.g. the REST Proxy container restarted). */
|
||||
void close(KafkaConsumerHandle consumer) {
|
||||
public void close(KafkaConsumerHandle consumer) {
|
||||
try {
|
||||
send("DELETE", consumer.baseUri(), null);
|
||||
} catch (PipesKafkaRestClientException e) {
|
||||
} catch (KafkaRestClientException e) {
|
||||
if (e.getStatusCode() != 404) {
|
||||
throw e;
|
||||
}
|
||||
@@ -167,7 +259,7 @@ class PipesKafkaRestClient {
|
||||
|
||||
HttpResponse<byte[]> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() / 100 != 2) {
|
||||
throw new PipesKafkaRestClientException(method, uri.toString(), response.statusCode(),
|
||||
throw new KafkaRestClientException(method, uri.toString(), response.statusCode(),
|
||||
new String(response.body(), StandardCharsets.UTF_8));
|
||||
}
|
||||
return response.body().length == 0 ? NullNode.getInstance() : objectMapper.readTree(response.body());
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
/** A Kafka REST Proxy (Karapace) response outside the expected 2xx status for its call. */
|
||||
public class KafkaRestClientException extends RuntimeException {
|
||||
|
||||
private final int statusCode;
|
||||
private final String responseBody;
|
||||
|
||||
public KafkaRestClientException(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;
|
||||
this.responseBody = body;
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public String getResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
/** The Kafka REST Proxy reported the requested topic does not exist on the broker. */
|
||||
public class KafkaTopicNotFoundException extends RuntimeException {
|
||||
|
||||
private final String topic;
|
||||
|
||||
public KafkaTopicNotFoundException(String topic, Throwable cause) {
|
||||
super("Kafka topic " + topic + " does not exist", cause);
|
||||
this.topic = topic;
|
||||
}
|
||||
|
||||
public String getTopic() {
|
||||
return topic;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
/** A Kafka topic/partition pair, used as a map key when grouping records for delivery. */
|
||||
public record KafkaTopicPartition(String topic, int partition) {
|
||||
}
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
package io.floci.aws.core.common.kafka;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
@@ -29,7 +29,7 @@ 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
|
||||
* target, so Pipes can poll a Kafka source over plain HTTP ({@link KafkaRestClient}) 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:
|
||||
@@ -37,7 +37,7 @@ import java.util.stream.Collectors;
|
||||
* (multiple Pipes reading the same cluster share one Karapace instance).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
class KarapaceManager implements ContainerTeardown {
|
||||
public class KarapaceManager implements ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KarapaceManager.class);
|
||||
private static final int REST_PORT = 8082;
|
||||
@@ -88,7 +88,7 @@ class KarapaceManager implements ContainerTeardown {
|
||||
this.readyTimeout = readyTimeout;
|
||||
}
|
||||
|
||||
URI ensureStarted(String bootstrapServers) {
|
||||
public URI ensureStarted(String bootstrapServers) {
|
||||
synchronized (lifecycleLock) {
|
||||
if (teardown != null) {
|
||||
throw new IllegalStateException("Karapace containers are being stopped");
|
||||
@@ -1,5 +0,0 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
|
||||
/** One Kafka record header, as decoded from a Kafka REST Proxy record response. */
|
||||
record KafkaHeaderDto(String key, byte[] value) {
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
|
||||
/** A Kafka topic/partition pair, used as a map key when grouping records for delivery. */
|
||||
record KafkaTopicPartition(String topic, int partition) {
|
||||
}
|
||||
@@ -3,6 +3,11 @@ package io.floci.aws.services.pipes;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.kafka.KafkaConsumerHandle;
|
||||
import io.floci.aws.core.common.kafka.KafkaOffsetDto;
|
||||
import io.floci.aws.core.common.kafka.KafkaRecordDto;
|
||||
import io.floci.aws.core.common.kafka.KafkaRestClient;
|
||||
import io.floci.aws.core.common.kafka.KarapaceManager;
|
||||
import io.floci.aws.services.msk.MskService;
|
||||
import io.floci.aws.services.pipes.model.Pipe;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
@@ -21,7 +26,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
* (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.
|
||||
* target on demand, and {@link KafkaRestClient} speaks its REST API.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PipesKafkaConsumerManager {
|
||||
@@ -32,12 +37,12 @@ public class PipesKafkaConsumerManager {
|
||||
|
||||
private final MskService mskService;
|
||||
private final KarapaceManager karapaceManager;
|
||||
private final PipesKafkaRestClient restClient;
|
||||
private final KafkaRestClient restClient;
|
||||
private final ConcurrentHashMap<String, KafkaConsumerHandle> consumers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public PipesKafkaConsumerManager(MskService mskService, KarapaceManager karapaceManager,
|
||||
PipesKafkaRestClient restClient) {
|
||||
KafkaRestClient restClient) {
|
||||
this.mskService = mskService;
|
||||
this.karapaceManager = karapaceManager;
|
||||
this.restClient = restClient;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package io.floci.aws.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;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.kafka.KafkaHeaderDto;
|
||||
import io.floci.aws.core.common.kafka.KafkaOffsetDto;
|
||||
import io.floci.aws.core.common.kafka.KafkaRecordDto;
|
||||
import io.floci.aws.core.common.kafka.KafkaTopicPartition;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbTtlIdentity;
|
||||
import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader;
|
||||
import io.floci.aws.services.kinesis.KinesisService;
|
||||
|
||||
Reference in new issue
Block a user