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:
Vũ Thế Huy authored and GitHub committed 2026-11-22 08:08:34 -04:00
1 parent f41fad028c
commit 351973d3f8
19 files changed
+412 -64

No files matched your search

@@ -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) {
}
@@ -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) {
}
@@ -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";
}
@@ -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) {
}
@@ -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;
@@ -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<String> lastRequestBody = new AtomicReference<>();
private final AtomicReference<String> lastRequestMethod = new AtomicReference<>();
private final AtomicReference<String> 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<Integer> 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());
}
}
@@ -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<String> lastRequestBody = new AtomicReference<>();
private final AtomicReference<String> lastRequestMethod = new AtomicReference<>();
private final AtomicReference<String> 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
@@ -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;
@@ -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);
}
@@ -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;