From 351973d3f84d414bafb0a256aefb2e8ef0b7cd9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:34 +0700 Subject: [PATCH] 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 --- .../common/kafka}/KafkaConsumerHandle.java | 4 +- .../aws/core/common/kafka/KafkaHeaderDto.java | 5 + .../common/kafka}/KafkaOffsetDto.java | 4 +- .../common/kafka}/KafkaRecordDto.java | 6 +- .../common/kafka/KafkaRestClient.java} | 122 ++++++++-- .../kafka/KafkaRestClientException.java | 23 ++ .../kafka/KafkaTopicNotFoundException.java | 16 ++ .../common/kafka/KafkaTopicPartition.java | 5 + .../common/kafka}/KarapaceManager.java | 8 +- .../aws/services/pipes/KafkaHeaderDto.java | 5 - .../services/pipes/KafkaTopicPartition.java | 5 - .../pipes/PipesKafkaConsumerManager.java | 11 +- .../pipes/PipesKafkaRestClientException.java | 17 -- .../floci/aws/services/pipes/PipesPoller.java | 4 + .../kafka/KafkaRestClientAssignmentTest.java | 219 ++++++++++++++++++ .../common/kafka/KafkaRestClientTest.java} | 10 +- .../common/kafka}/KarapaceManagerTest.java | 2 +- .../pipes/PipesKafkaConsumerManagerTest.java | 7 +- .../aws/services/pipes/PipesPollerTest.java | 3 + 19 files changed, 412 insertions(+), 64 deletions(-) rename src/main/java/io/floci/aws/{services/pipes => core/common/kafka}/KafkaConsumerHandle.java (53%) create mode 100644 src/main/java/io/floci/aws/core/common/kafka/KafkaHeaderDto.java rename src/main/java/io/floci/aws/{services/pipes => core/common/kafka}/KafkaOffsetDto.java (73%) rename src/main/java/io/floci/aws/{services/pipes => core/common/kafka}/KafkaRecordDto.java (86%) rename src/main/java/io/floci/aws/{services/pipes/PipesKafkaRestClient.java => core/common/kafka/KafkaRestClient.java} (58%) create mode 100644 src/main/java/io/floci/aws/core/common/kafka/KafkaRestClientException.java create mode 100644 src/main/java/io/floci/aws/core/common/kafka/KafkaTopicNotFoundException.java create mode 100644 src/main/java/io/floci/aws/core/common/kafka/KafkaTopicPartition.java rename src/main/java/io/floci/aws/{services/pipes => core/common/kafka}/KarapaceManager.java (98%) delete mode 100644 src/main/java/io/floci/aws/services/pipes/KafkaHeaderDto.java delete mode 100644 src/main/java/io/floci/aws/services/pipes/KafkaTopicPartition.java delete mode 100644 src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClientException.java create mode 100644 src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java rename src/test/java/io/floci/aws/{services/pipes/PipesKafkaRestClientTest.java => core/common/kafka/KafkaRestClientTest.java} (95%) rename src/test/java/io/floci/aws/{services/pipes => core/common/kafka}/KarapaceManagerTest.java (99%) diff --git a/src/main/java/io/floci/aws/services/pipes/KafkaConsumerHandle.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaConsumerHandle.java similarity index 53% rename from src/main/java/io/floci/aws/services/pipes/KafkaConsumerHandle.java rename to src/main/java/io/floci/aws/core/common/kafka/KafkaConsumerHandle.java index 141f90668f..4b6b2582d0 100644 --- a/src/main/java/io/floci/aws/services/pipes/KafkaConsumerHandle.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaConsumerHandle.java @@ -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) { } diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaHeaderDto.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaHeaderDto.java new file mode 100644 index 0000000000..c2172233ee --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaHeaderDto.java @@ -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) { +} diff --git a/src/main/java/io/floci/aws/services/pipes/KafkaOffsetDto.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaOffsetDto.java similarity index 73% rename from src/main/java/io/floci/aws/services/pipes/KafkaOffsetDto.java rename to src/main/java/io/floci/aws/core/common/kafka/KafkaOffsetDto.java index f5033cfbae..6b62db416c 100644 --- a/src/main/java/io/floci/aws/services/pipes/KafkaOffsetDto.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaOffsetDto.java @@ -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) { } diff --git a/src/main/java/io/floci/aws/services/pipes/KafkaRecordDto.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaRecordDto.java similarity index 86% rename from src/main/java/io/floci/aws/services/pipes/KafkaRecordDto.java rename to src/main/java/io/floci/aws/core/common/kafka/KafkaRecordDto.java index 3062c4901d..591e595f60 100644 --- a/src/main/java/io/floci/aws/services/pipes/KafkaRecordDto.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaRecordDto.java @@ -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 headers) { - static final String DEFAULT_TIMESTAMP_TYPE = "CreateTime"; + public static final String DEFAULT_TIMESTAMP_TYPE = "CreateTime"; } diff --git a/src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClient.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java similarity index 58% rename from src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClient.java rename to src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java index b110ed69a5..99ca0eae69 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClient.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java @@ -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. * *

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 topics) { + public void subscribe(KafkaConsumerHandle consumer, List topics) { ObjectNode body = objectMapper.createObjectNode(); ArrayNode topicsNode = body.putArray("topics"); topics.forEach(topicsNode::add); send("POST", instanceUri(consumer, "subscription"), body); } - List 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. + * + *

{@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 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 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 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 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 partitions) { + if (partitions.isEmpty()) { + return; + } + send("POST", instanceUri(consumer, "positions/beginning"), partitionsBody(partitions)); + } + + private ObjectNode partitionsBody(List 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 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 offsets) { + public void commit(KafkaConsumerHandle consumer, List 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 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()); diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClientException.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClientException.java new file mode 100644 index 0000000000..9b4c15e794 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClientException.java @@ -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; + } +} diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicNotFoundException.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicNotFoundException.java new file mode 100644 index 0000000000..704cbd3602 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicNotFoundException.java @@ -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; + } +} diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicPartition.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicPartition.java new file mode 100644 index 0000000000..d6b1e8946a --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaTopicPartition.java @@ -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) { +} diff --git a/src/main/java/io/floci/aws/services/pipes/KarapaceManager.java b/src/main/java/io/floci/aws/core/common/kafka/KarapaceManager.java similarity index 98% rename from src/main/java/io/floci/aws/services/pipes/KarapaceManager.java rename to src/main/java/io/floci/aws/core/common/kafka/KarapaceManager.java index c29dfda738..4bef8f1115 100644 --- a/src/main/java/io/floci/aws/services/pipes/KarapaceManager.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KarapaceManager.java @@ -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. * *

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"); diff --git a/src/main/java/io/floci/aws/services/pipes/KafkaHeaderDto.java b/src/main/java/io/floci/aws/services/pipes/KafkaHeaderDto.java deleted file mode 100644 index 225d6369b5..0000000000 --- a/src/main/java/io/floci/aws/services/pipes/KafkaHeaderDto.java +++ /dev/null @@ -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) { -} diff --git a/src/main/java/io/floci/aws/services/pipes/KafkaTopicPartition.java b/src/main/java/io/floci/aws/services/pipes/KafkaTopicPartition.java deleted file mode 100644 index f20819a2fc..0000000000 --- a/src/main/java/io/floci/aws/services/pipes/KafkaTopicPartition.java +++ /dev/null @@ -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) { -} diff --git a/src/main/java/io/floci/aws/services/pipes/PipesKafkaConsumerManager.java b/src/main/java/io/floci/aws/services/pipes/PipesKafkaConsumerManager.java index 7edcfecfa2..f9778da4af 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesKafkaConsumerManager.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesKafkaConsumerManager.java @@ -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 consumers = new ConcurrentHashMap<>(); @Inject public PipesKafkaConsumerManager(MskService mskService, KarapaceManager karapaceManager, - PipesKafkaRestClient restClient) { + KafkaRestClient restClient) { this.mskService = mskService; this.karapaceManager = karapaceManager; this.restClient = restClient; diff --git a/src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClientException.java b/src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClientException.java deleted file mode 100644 index b6b905b5b1..0000000000 --- a/src/main/java/io/floci/aws/services/pipes/PipesKafkaRestClientException.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/io/floci/aws/services/pipes/PipesPoller.java b/src/main/java/io/floci/aws/services/pipes/PipesPoller.java index 376a5ee416..5deaf0bcc5 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesPoller.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesPoller.java @@ -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; diff --git a/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java new file mode 100644 index 0000000000..303eef73a2 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java @@ -0,0 +1,219 @@ +package io.floci.aws.core.common.kafka; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Exercises the partition discovery, manual assignment and offset seeking calls of + * {@link KafkaRestClient} against a fake server speaking Karapace's REST Proxy API. + */ +class KafkaRestClientAssignmentTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String INSTANCE_PATH = "/consumers/refresh-group/instances/rest-consumer-1"; + + private HttpServer fakeServer; + private KafkaRestClient client; + private final AtomicReference lastRequestBody = new AtomicReference<>(); + private final AtomicReference lastRequestMethod = new AtomicReference<>(); + private final AtomicReference lastRequestPath = new AtomicReference<>(); + + @BeforeEach + void setUp() throws Exception { + fakeServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0); + + fakeServer.createContext("/topics/orders/partitions", exchange -> { + record(exchange); + respond(exchange, 200, """ + [ + {"partition": 2, "leader": 1, "replicas": []}, + {"partition": 0, "leader": 1, "replicas": []}, + {"partition": 1, "leader": 1, "replicas": []} + ] + """); + }); + // Karapace answers a missing topic with 40401 on /partitions but 40403 on /topics/{topic} + fakeServer.createContext("/topics/missing/partitions", exchange -> { + record(exchange); + respond(exchange, 404, "{\"error_code\":40401,\"message\":\"Topic missing not found\"}"); + }); + fakeServer.createContext("/topics/missing", exchange -> { + record(exchange); + respond(exchange, 404, "{\"error_code\":40403,\"message\":\"Unknown topic or partition\"}"); + }); + fakeServer.createContext("/topics/other-404-code/partitions", exchange -> { + record(exchange); + respond(exchange, 404, "{\"error_code\":40402,\"message\":\"Partition not found\"}"); + }); + fakeServer.createContext("/topics/broken/partitions", exchange -> { + record(exchange); + respond(exchange, 503, "{\"error_code\":50301,\"message\":\"broker unavailable\"}"); + }); + fakeServer.createContext("/consumers/refresh-group", exchange -> { + record(exchange); + respond(exchange, 200, "{\"instance_id\":\"rest-consumer-1\"," + + "\"base_uri\":\"consumers/refresh-group/instances/rest-consumer-1\"}"); + }); + fakeServer.createContext(INSTANCE_PATH + "/assignments", exchange -> { + record(exchange); + respond(exchange, 204, ""); + }); + fakeServer.createContext(INSTANCE_PATH + "/positions", exchange -> { + record(exchange); + respond(exchange, 204, ""); + }); + + fakeServer.start(); + client = new KafkaRestClient(MAPPER, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); + } + + @AfterEach + void tearDown() { + fakeServer.stop(0); + } + + private URI restBaseUri() { + return URI.create("http://localhost:" + fakeServer.getAddress().getPort() + "/"); + } + + private KafkaConsumerHandle newConsumer() { + return client.createConsumer(restBaseUri(), "refresh-group", "earliest"); + } + + private void record(HttpExchange exchange) throws IOException { + lastRequestMethod.set(exchange.getRequestMethod()); + lastRequestPath.set(exchange.getRequestURI().toString()); + lastRequestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + } + + private static void respond(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length); + if (bytes.length > 0) { + exchange.getResponseBody().write(bytes); + } + exchange.close(); + } + + @Test + void listPartitionsReturnsSortedPartitionIds() { + List partitions = client.listPartitions(restBaseUri(), "orders"); + + assertEquals(List.of(0, 1, 2), partitions); + assertEquals("GET", lastRequestMethod.get()); + assertEquals("/topics/orders/partitions", lastRequestPath.get()); + } + + @Test + void listPartitionsOfMissingTopicRaisesTopicNotFound() { + KafkaTopicNotFoundException thrown = assertThrows(KafkaTopicNotFoundException.class, + () -> client.listPartitions(restBaseUri(), "missing")); + + assertEquals("missing", thrown.getTopic()); + } + + @Test + void listPartitionsReportsUnrelated404AsRestClientFailureNotMissingTopic() { + URI wrongPrefix = URI.create(restBaseUri() + "wrong-prefix/"); + + KafkaRestClientException thrown = assertThrows(KafkaRestClientException.class, + () -> client.listPartitions(wrongPrefix, "orders")); + + assertEquals(404, thrown.getStatusCode()); + } + + @Test + void listPartitionsReports404WithOtherErrorCodeAsRestClientFailureNotMissingTopic() { + KafkaRestClientException thrown = assertThrows(KafkaRestClientException.class, + () -> client.listPartitions(restBaseUri(), "other-404-code")); + + assertEquals(404, thrown.getStatusCode()); + } + + @Test + void listPartitionsReportsBrokerErrorAsRestClientFailureNotMissingTopic() { + KafkaRestClientException thrown = assertThrows(KafkaRestClientException.class, + () -> client.listPartitions(restBaseUri(), "broken")); + + assertEquals(503, thrown.getStatusCode()); + } + + @Test + void listPartitionsAgainstStoppedProxyRaisesConnectivityError() { + URI deadUri = restBaseUri(); + fakeServer.stop(0); + + assertThrows(UncheckedIOException.class, () -> client.listPartitions(deadUri, "orders")); + } + + @Test + void assignSendsEveryTopicPartition() throws Exception { + KafkaConsumerHandle consumer = newConsumer(); + + client.assign(consumer, List.of(new KafkaTopicPartition("orders", 0), new KafkaTopicPartition("orders", 1))); + + assertEquals("POST", lastRequestMethod.get()); + assertTrue(lastRequestPath.get().endsWith("/assignments")); + JsonNode partitions = MAPPER.readTree(lastRequestBody.get()).path("partitions"); + assertEquals(2, partitions.size()); + assertEquals("orders", partitions.get(1).path("topic").asText()); + assertEquals(1, partitions.get(1).path("partition").asInt()); + } + + @Test + void seekSendsExplicitOffsetPerPartition() throws Exception { + KafkaConsumerHandle consumer = newConsumer(); + + client.seek(consumer, List.of(new KafkaOffsetDto("orders", 0, 11L), new KafkaOffsetDto("orders", 1, 5L))); + + assertTrue(lastRequestPath.get().endsWith("/positions")); + JsonNode offsets = MAPPER.readTree(lastRequestBody.get()).path("offsets"); + assertEquals(2, offsets.size()); + assertEquals(11L, offsets.get(0).path("offset").asLong()); + assertEquals(1, offsets.get(1).path("partition").asInt()); + assertEquals(5L, offsets.get(1).path("offset").asLong()); + } + + @Test + void seekToBeginningTargetsTheBeginningPositionsResource() throws Exception { + KafkaConsumerHandle consumer = newConsumer(); + + client.seekToBeginning(consumer, List.of(new KafkaTopicPartition("orders", 2))); + + assertTrue(lastRequestPath.get().endsWith("/positions/beginning")); + JsonNode partition = MAPPER.readTree(lastRequestBody.get()).path("partitions").get(0); + assertEquals("orders", partition.path("topic").asText()); + assertEquals(2, partition.path("partition").asInt()); + } + + @Test + void seekWithNothingToPositionSendsNoRequest() { + KafkaConsumerHandle consumer = newConsumer(); + lastRequestPath.set(null); + + client.seek(consumer, List.of()); + client.seekToBeginning(consumer, List.of()); + + assertNull(lastRequestPath.get()); + } +} diff --git a/src/test/java/io/floci/aws/services/pipes/PipesKafkaRestClientTest.java b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientTest.java similarity index 95% rename from src/test/java/io/floci/aws/services/pipes/PipesKafkaRestClientTest.java rename to src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientTest.java index 0799f43ae6..9b15d03a58 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesKafkaRestClientTest.java +++ b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientTest.java @@ -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; @@ -22,13 +22,13 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -/** Exercises {@link PipesKafkaRestClient} against a fake server speaking Karapace's REST Proxy API. */ -class PipesKafkaRestClientTest { +/** Exercises {@link KafkaRestClient} against a fake server speaking Karapace's REST Proxy API. */ +class KafkaRestClientTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private HttpServer fakeServer; - private PipesKafkaRestClient client; + private KafkaRestClient client; private final AtomicReference lastRequestBody = new AtomicReference<>(); private final AtomicReference lastRequestMethod = new AtomicReference<>(); private final AtomicReference lastRequestPath = new AtomicReference<>(); @@ -88,7 +88,7 @@ class PipesKafkaRestClientTest { }); fakeServer.start(); - client = new PipesKafkaRestClient(MAPPER, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); + client = new KafkaRestClient(MAPPER, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); } @AfterEach diff --git a/src/test/java/io/floci/aws/services/pipes/KarapaceManagerTest.java b/src/test/java/io/floci/aws/core/common/kafka/KarapaceManagerTest.java similarity index 99% rename from src/test/java/io/floci/aws/services/pipes/KarapaceManagerTest.java rename to src/test/java/io/floci/aws/core/common/kafka/KarapaceManagerTest.java index c29397dc20..eb43d5d17c 100644 --- a/src/test/java/io/floci/aws/services/pipes/KarapaceManagerTest.java +++ b/src/test/java/io/floci/aws/core/common/kafka/KarapaceManagerTest.java @@ -1,4 +1,4 @@ -package io.floci.aws.services.pipes; +package io.floci.aws.core.common.kafka; import com.sun.net.httpserver.HttpServer; import io.floci.aws.config.EmulatorConfig; diff --git a/src/test/java/io/floci/aws/services/pipes/PipesKafkaConsumerManagerTest.java b/src/test/java/io/floci/aws/services/pipes/PipesKafkaConsumerManagerTest.java index 579097f5d9..5a3f902575 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesKafkaConsumerManagerTest.java +++ b/src/test/java/io/floci/aws/services/pipes/PipesKafkaConsumerManagerTest.java @@ -2,6 +2,9 @@ package io.floci.aws.services.pipes; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.kafka.KafkaConsumerHandle; +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 org.junit.jupiter.api.BeforeEach; @@ -28,14 +31,14 @@ class PipesKafkaConsumerManagerTest { private MskService mskService; private KarapaceManager karapaceManager; - private PipesKafkaRestClient restClient; + private KafkaRestClient restClient; private PipesKafkaConsumerManager manager; @BeforeEach void setUp() { mskService = mock(MskService.class); karapaceManager = mock(KarapaceManager.class); - restClient = mock(PipesKafkaRestClient.class); + restClient = mock(KafkaRestClient.class); manager = new PipesKafkaConsumerManager(mskService, karapaceManager, restClient); } diff --git a/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java b/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java index 10626d1e97..573ae884b0 100644 --- a/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/floci/aws/services/pipes/PipesPollerTest.java @@ -6,6 +6,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +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.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader;