mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -0,0 +1,193 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
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.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KarapaceManagerTest {
|
||||
|
||||
private static final int REST_PORT = 8082;
|
||||
|
||||
@Mock private ContainerLifecycleManager lifecycleManager;
|
||||
@Mock private ContainerDetector containerDetector;
|
||||
@Mock private PortAllocator portAllocator;
|
||||
@Mock private EmulatorConfig config;
|
||||
@Mock private DockerHostResolver dockerHostResolver;
|
||||
@Mock private EmbeddedDnsServer embeddedDnsServer;
|
||||
|
||||
private KarapaceManager manager;
|
||||
private HttpServer fakeRestServer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.PipesServiceConfig pipes = mock(EmulatorConfig.PipesServiceConfig.class);
|
||||
EmulatorConfig.KafkaRestBridgeConfig bridge = mock(EmulatorConfig.KafkaRestBridgeConfig.class);
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
|
||||
lenient().when(config.services()).thenReturn(services);
|
||||
lenient().when(services.pipes()).thenReturn(pipes);
|
||||
lenient().when(services.dockerNetwork()).thenReturn(Optional.empty());
|
||||
lenient().when(pipes.kafkaRestBridge()).thenReturn(bridge);
|
||||
lenient().when(bridge.defaultImage()).thenReturn("ghcr.io/aiven-open/karapace:latest");
|
||||
lenient().when(bridge.hostPortBase()).thenReturn(9500);
|
||||
lenient().when(bridge.hostPortMax()).thenReturn(9599);
|
||||
lenient().when(config.docker()).thenReturn(docker);
|
||||
lenient().when(docker.logMaxSize()).thenReturn("10m");
|
||||
lenient().when(docker.logMaxFile()).thenReturn("3");
|
||||
|
||||
lenient().when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
|
||||
|
||||
ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);
|
||||
manager = new KarapaceManager(containerBuilder, lifecycleManager, containerDetector, config, portAllocator,
|
||||
dockerHostResolver, java.time.Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (fakeRestServer != null) {
|
||||
fakeRestServer.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Stands in for Karapace's own {@code GET /_health}, which {@code isReady} polls. */
|
||||
private int startFakeRestServer() throws Exception {
|
||||
fakeRestServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||
fakeRestServer.createContext("/_health", exchange -> {
|
||||
byte[] body = "{}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
fakeRestServer.start();
|
||||
return fakeRestServer.getAddress().getPort();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedConfiguresBootstrapUriAndPublishesRestPort() throws Exception {
|
||||
int hostPort = startFakeRestServer();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-1",
|
||||
Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
URI restBaseUri = manager.ensureStarted("broker-1:9092");
|
||||
|
||||
assertEquals("http://localhost:" + hostPort + "/", restBaseUri.toString());
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
ContainerSpec spec = specCaptor.getValue();
|
||||
assertTrue(spec.env().contains("KARAPACE_BOOTSTRAP_URI=broker-1:9092"),
|
||||
"Karapace must be pointed at the target cluster's bootstrap servers");
|
||||
assertEquals(Integer.valueOf(hostPort), spec.portBindings().get(REST_PORT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedReusesTheSameContainerForTheSameTarget() throws Exception {
|
||||
int hostPort = startFakeRestServer();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-1",
|
||||
Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
URI first = manager.ensureStarted("broker-1:9092");
|
||||
URI second = manager.ensureStarted("broker-1:9092");
|
||||
|
||||
assertSame(first, second, "multiple pipes reading the same broker must share one Karapace instance");
|
||||
verify(lifecycleManager, times(1)).createAndStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedRewritesHostLocalBrokerForTheSidecar() throws Exception {
|
||||
int hostPort = startFakeRestServer();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-1",
|
||||
Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.ensureStarted("localhost:9092");
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
assertTrue(specCaptor.getValue().env().contains("KARAPACE_BOOTSTRAP_URI=host.docker.internal:9092"),
|
||||
"a host-local broker address must be rewritten so the sidecar, in its own network "
|
||||
+ "namespace, reaches the Floci host instead of itself");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedAddsTheLinuxHostGatewayAliasSoRewrittenAddressesResolve() throws Exception {
|
||||
int hostPort = startFakeRestServer();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
when(dockerHostResolver.isLinuxHost()).thenReturn(true);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-1",
|
||||
Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.ensureStarted("localhost:9092");
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
assertTrue(specCaptor.getValue().extraHosts().contains("host.docker.internal:host-gateway"),
|
||||
"native Linux Docker does not auto-inject host.docker.internal, so the sidecar needs "
|
||||
+ "the host-gateway mapping to resolve the address resolveForContainer rewrote to it");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedCleansUpWhenReadinessNeverArrives() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(portAllocator.allocate(9500, 9599)).thenReturn(54321);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-1",
|
||||
Map.of(REST_PORT, new EndpointInfo("localhost", 1)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class,
|
||||
() -> manager.ensureStarted("broker-1:9092"));
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("container-1", null);
|
||||
verify(portAllocator).release(54321);
|
||||
}
|
||||
}
|
||||
+41
-1
@@ -8,8 +8,15 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PipesKafkaConsumerManagerTest {
|
||||
@@ -17,12 +24,45 @@ class PipesKafkaConsumerManagerTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private MskService mskService;
|
||||
private KarapaceManager karapaceManager;
|
||||
private PipesKafkaRestClient restClient;
|
||||
private PipesKafkaConsumerManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mskService = Mockito.mock(MskService.class);
|
||||
manager = new PipesKafkaConsumerManager(mskService);
|
||||
karapaceManager = Mockito.mock(KarapaceManager.class);
|
||||
restClient = Mockito.mock(PipesKafkaRestClient.class);
|
||||
manager = new PipesKafkaConsumerManager(mskService, karapaceManager, restClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollClosesOrphanedConsumerWhenSubscriptionFails() throws Exception {
|
||||
Pipe pipe = new Pipe();
|
||||
pipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/orders-pipe");
|
||||
pipe.setName("orders-pipe");
|
||||
pipe.setSource("smk://broker-1:9092");
|
||||
pipe.setSourceParameters(MAPPER.readTree("""
|
||||
{
|
||||
"SelfManagedKafkaParameters": {
|
||||
"TopicName": "orders"
|
||||
}
|
||||
}
|
||||
"""));
|
||||
|
||||
URI restBaseUri = URI.create("http://localhost:8082/");
|
||||
KafkaConsumerHandle handle = new KafkaConsumerHandle("instance-1",
|
||||
URI.create("http://localhost:8082/consumers/g/instances/instance-1"));
|
||||
when(karapaceManager.ensureStarted("broker-1:9092")).thenReturn(restBaseUri);
|
||||
when(restClient.createConsumer(eq(restBaseUri), anyString(), anyString())).thenReturn(handle);
|
||||
Mockito.doThrow(new RuntimeException("subscribe failed"))
|
||||
.when(restClient).subscribe(eq(handle), anyList());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> manager.poll(pipe));
|
||||
|
||||
// The consumer already exists server-side once createConsumer succeeds; a failed
|
||||
// subscribe must delete it here, since the map never learns its handle to close it later.
|
||||
verify(restClient).close(handle);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import io.github.hectorvent.floci.services.msk.MskService;
|
||||
import io.github.hectorvent.floci.services.pipes.model.Pipe;
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Pins {@link PipesKafkaNativeSupport} to what {@code ConsumerConfig} resolves from
|
||||
* {@link PipesKafkaConsumerManager#consumerProperties}, both ways: a newly resolved class must be
|
||||
* registered, and nothing else may be. Reading that method rather than copying it means a new
|
||||
* setting there is covered here too.
|
||||
*
|
||||
* <p>Scope: config-resolved classes only. Reflection always succeeds on the JVM, so a non-config
|
||||
* lookup from a future kafka-clients needs a Kafka pipe run against a native binary. The
|
||||
* compatibility suite already runs against the native image; it has no Kafka source case yet.
|
||||
*/
|
||||
class PipesKafkaNativeSupportTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static final Predicate<String> TRANSPORT_SECURITY =
|
||||
key -> key.startsWith("sasl.") || key.startsWith("ssl.");
|
||||
|
||||
@Test
|
||||
@DisplayName("classes ConsumerConfig resolves reflectively are registered")
|
||||
void registrationCoversReflectivelyResolvedClasses() throws Exception {
|
||||
Set<String> missing = new TreeSet<>(expectedClassNames());
|
||||
missing.removeAll(registeredClassNames());
|
||||
|
||||
assertTrue(missing.isEmpty(),
|
||||
"kafka-clients resolves these reflectively but PipesKafkaNativeSupport omits them, "
|
||||
+ "so a native build cannot construct a consumer: " + missing);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("nothing is registered that ConsumerConfig does not resolve")
|
||||
void registrationContainsNothingUnjustified() throws Exception {
|
||||
Set<String> unexpected = new TreeSet<>(registeredClassNames());
|
||||
unexpected.removeAll(expectedClassNames());
|
||||
|
||||
assertTrue(unexpected.isEmpty(),
|
||||
"these are not config-resolved, so this test cannot guard them and they need a "
|
||||
+ "native run to justify. SASL/SSL defaults in particular break the build — "
|
||||
+ "DefaultJwtValidator drags in optional jose4j: " + unexpected);
|
||||
}
|
||||
|
||||
/** Class-valued settings kafka-clients resolves, minus the transport security Floci never uses. */
|
||||
private static Set<String> expectedClassNames() throws Exception {
|
||||
Set<String> classes = new TreeSet<>();
|
||||
consumerConfigValues().forEach((key, value) -> {
|
||||
if (TRANSPORT_SECURITY.negate().test(key)) {
|
||||
collectClassNames(value, classes);
|
||||
}
|
||||
});
|
||||
return classes;
|
||||
}
|
||||
|
||||
private static Set<String> registeredClassNames() {
|
||||
RegisterForReflection annotation =
|
||||
PipesKafkaNativeSupport.class.getAnnotation(RegisterForReflection.class);
|
||||
assertNotNull(annotation, "PipesKafkaNativeSupport must carry @RegisterForReflection");
|
||||
|
||||
Set<String> names = new TreeSet<>(Set.of(annotation.classNames()));
|
||||
for (Class<?> target : annotation.targets()) {
|
||||
names.add(target.getName());
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors {@code AbstractConfig.getConfiguredInstances}: a setting may be a {@code Class} or a
|
||||
* class name — {@code metric.reporters} is the latter. Values naming no class are not candidates.
|
||||
*/
|
||||
private static void collectClassNames(Object value, Set<String> into) {
|
||||
switch (value) {
|
||||
case Class<?> type -> into.add(type.getName());
|
||||
case Collection<?> collection -> collection.forEach(element -> collectClassNames(element, into));
|
||||
case String name -> loadable(name).ifPresent(into::add);
|
||||
case null, default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<String> loadable(String className) {
|
||||
try {
|
||||
return Optional.of(Class.forName(className, false, ConsumerConfig.class.getClassLoader()).getName());
|
||||
} catch (ClassNotFoundException | LinkageError e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, ?> consumerConfigValues() throws Exception {
|
||||
PipesKafkaConsumerManager manager = new PipesKafkaConsumerManager(Mockito.mock(MskService.class));
|
||||
|
||||
Pipe pipe = new Pipe();
|
||||
pipe.setName("native-support");
|
||||
pipe.setSource("smk://localhost:9092");
|
||||
pipe.setSourceParameters(MAPPER.readTree("""
|
||||
{
|
||||
"SelfManagedKafkaParameters": {
|
||||
"TopicName": "orders"
|
||||
}
|
||||
}
|
||||
"""));
|
||||
|
||||
return new ConsumerConfig(manager.consumerProperties(pipe)).values();
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
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 {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private HttpServer fakeServer;
|
||||
private PipesKafkaRestClient 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("/consumers/orders-group", exchange -> {
|
||||
record(exchange);
|
||||
// Karapace returns base_uri as a path relative to the proxy root (not an absolute URL
|
||||
// as the Confluent REST Proxy reference spec shows) - this fixture matches that.
|
||||
String response = "{\"instance_id\":\"rest-consumer-1\","
|
||||
+ "\"base_uri\":\"consumers/orders-group/instances/rest-consumer-1\"}";
|
||||
respond(exchange, 200, response);
|
||||
});
|
||||
|
||||
fakeServer.createContext("/consumers/orders-group/instances/rest-consumer-1/subscription", exchange -> {
|
||||
record(exchange);
|
||||
respond(exchange, 204, "");
|
||||
});
|
||||
|
||||
fakeServer.createContext("/consumers/orders-group/instances/rest-consumer-1/records", exchange -> {
|
||||
record(exchange);
|
||||
byte[] key = "customer-1".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] value = "{\"status\":\"active\"}".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] headerValue = "trace-1".getBytes(StandardCharsets.UTF_8);
|
||||
String response = """
|
||||
[
|
||||
{
|
||||
"topic": "orders",
|
||||
"partition": 0,
|
||||
"offset": 42,
|
||||
"timestamp": 1700000000000,
|
||||
"key": "%s",
|
||||
"value": "%s",
|
||||
"headers": [{"name": "traceId", "value": "%s"}]
|
||||
}
|
||||
]
|
||||
""".formatted(base64(key), base64(value), base64(headerValue));
|
||||
respond(exchange, 200, response);
|
||||
});
|
||||
|
||||
fakeServer.createContext("/consumers/orders-group/instances/rest-consumer-1/offsets", exchange -> {
|
||||
record(exchange);
|
||||
respond(exchange, 200, "");
|
||||
});
|
||||
|
||||
fakeServer.createContext("/consumers/orders-group/instances/rest-consumer-1", exchange -> {
|
||||
if ("DELETE".equals(exchange.getRequestMethod())) {
|
||||
record(exchange);
|
||||
respond(exchange, 204, "");
|
||||
} else {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
}
|
||||
});
|
||||
|
||||
fakeServer.start();
|
||||
client = new PipesKafkaRestClient(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 void record(com.sun.net.httpserver.HttpExchange exchange) throws java.io.IOException {
|
||||
lastRequestMethod.set(exchange.getRequestMethod());
|
||||
lastRequestPath.set(exchange.getRequestURI().toString());
|
||||
lastRequestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String body) throws java.io.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();
|
||||
}
|
||||
|
||||
private static String base64(byte[] value) {
|
||||
return Base64.getEncoder().encodeToString(value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createConsumerParsesInstanceIdAndBaseUri() {
|
||||
KafkaConsumerHandle consumer = client.createConsumer(restBaseUri(), "orders-group", "latest");
|
||||
|
||||
assertEquals("rest-consumer-1", consumer.instanceId());
|
||||
assertEquals("POST", lastRequestMethod.get());
|
||||
assertTrue(consumer.baseUri().toString().endsWith("/consumers/orders-group/instances/rest-consumer-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscribeSendsTopicList() throws Exception {
|
||||
KafkaConsumerHandle consumer = client.createConsumer(restBaseUri(), "orders-group", "earliest");
|
||||
|
||||
client.subscribe(consumer, List.of("orders"));
|
||||
|
||||
JsonNode body = MAPPER.readTree(lastRequestBody.get());
|
||||
assertEquals("orders", body.path("topics").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollDecodesBinaryKeyValueAndHeaders() {
|
||||
KafkaConsumerHandle consumer = client.createConsumer(restBaseUri(), "orders-group", "latest");
|
||||
|
||||
List<KafkaRecordDto> records = client.poll(consumer, Duration.ofMillis(100));
|
||||
|
||||
assertEquals(1, records.size());
|
||||
KafkaRecordDto record = records.get(0);
|
||||
assertEquals("orders", record.topic());
|
||||
assertEquals(0, record.partition());
|
||||
assertEquals(42L, record.offset());
|
||||
assertEquals(1700000000000L, record.timestamp());
|
||||
assertArrayEquals("customer-1".getBytes(StandardCharsets.UTF_8), record.key());
|
||||
assertArrayEquals("{\"status\":\"active\"}".getBytes(StandardCharsets.UTF_8), record.value());
|
||||
assertEquals(1, record.headers().size());
|
||||
assertEquals("traceId", record.headers().get(0).key());
|
||||
assertArrayEquals("trace-1".getBytes(StandardCharsets.UTF_8), record.headers().get(0).value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitSpecificOffsetsSendsOffsetsArray() throws Exception {
|
||||
KafkaConsumerHandle consumer = client.createConsumer(restBaseUri(), "orders-group", "latest");
|
||||
|
||||
client.commit(consumer, List.of(new KafkaOffsetDto("orders", 0, 43L)));
|
||||
|
||||
JsonNode body = MAPPER.readTree(lastRequestBody.get());
|
||||
JsonNode offset = body.path("offsets").get(0);
|
||||
assertEquals("orders", offset.path("topic").asText());
|
||||
assertEquals(0, offset.path("partition").asInt());
|
||||
assertEquals(43L, offset.path("offset").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeDeletesTheConsumerInstance() {
|
||||
KafkaConsumerHandle consumer = client.createConsumer(restBaseUri(), "orders-group", "latest");
|
||||
|
||||
client.close(consumer);
|
||||
|
||||
assertEquals("DELETE", lastRequestMethod.get());
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,6 @@ import io.github.hectorvent.floci.services.pipes.model.Pipe;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.vertx.core.Vertx;
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -20,20 +16,18 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -55,6 +49,7 @@ class PipesPollerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
lenient().when(kafkaConsumerManager.resolveBatchSize(any(), anyInt())).thenReturn(10);
|
||||
poller = new PipesPoller(vertx, sqsService, kinesisService, dynamoDbStreamService,
|
||||
kafkaConsumerManager, targetInvoker, new PipesFilterMatcher(MAPPER), MAPPER, config);
|
||||
}
|
||||
@@ -147,19 +142,19 @@ class PipesPollerTest {
|
||||
@Test
|
||||
void pollKafka_filtersUsingDecodedPayloadButDeliversOriginalRecord() throws Exception {
|
||||
Pipe pipe = selfManagedKafkaPipe();
|
||||
byte[] key = "customer-123".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] value = "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8);
|
||||
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("orders", 0, 42L, key, value);
|
||||
record.headers().add("traceId", "abc123".getBytes(StandardCharsets.UTF_8));
|
||||
byte[] key = "customer-123".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
byte[] value = "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
byte[] traceId = "abc123".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
KafkaRecordDto record = kafkaRecord("orders", 0, 42L, key, value, new KafkaHeaderDto("traceId", traceId));
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(record));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
|
||||
ArgumentCaptor<String> payloadCaptor = ArgumentCaptor.forClass(String.class);
|
||||
verify(targetInvoker).invoke(eq(pipe), payloadCaptor.capture(), eq("us-east-1"));
|
||||
verify(kafkaConsumerManager).commit(eq(pipe), anyMap());
|
||||
verify(kafkaConsumerManager).commit(eq(pipe), anyList());
|
||||
|
||||
JsonNode delivered = MAPPER.readTree(payloadCaptor.getValue());
|
||||
assertEquals("orders", delivered.path("topic").asText());
|
||||
@@ -177,29 +172,28 @@ class PipesPollerTest {
|
||||
@Test
|
||||
void pollKafka_doesNotCommitWhenDeliveryFails() throws Exception {
|
||||
Pipe pipe = selfManagedKafkaPipe();
|
||||
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>(
|
||||
"orders", 0, 7L, null, "{\"status\":\"active\"}".getBytes(StandardCharsets.UTF_8));
|
||||
KafkaRecordDto record = kafkaRecord("orders", 0, 7L, null,
|
||||
"{\"status\":\"active\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(record));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
org.mockito.Mockito.doThrow(new RuntimeException("boom"))
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
|
||||
verify(kafkaConsumerManager, never()).commit(pipe);
|
||||
verify(kafkaConsumerManager, never()).commit(eq(pipe), anyMap());
|
||||
verify(kafkaConsumerManager, never()).commit(eq(pipe), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollKafka_commitsDeliveredPrefixWhenLaterRecordFails() throws Exception {
|
||||
Pipe pipe = selfManagedKafkaPipe();
|
||||
ConsumerRecord<byte[], byte[]> first = new ConsumerRecord<>(
|
||||
"orders", 0, 0L, null, "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8));
|
||||
ConsumerRecord<byte[], byte[]> second = new ConsumerRecord<>(
|
||||
"orders", 0, 1L, null, "{\"status\":\"active\",\"id\":\"order-2\"}".getBytes(StandardCharsets.UTF_8));
|
||||
KafkaRecordDto first = kafkaRecord("orders", 0, 0L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
KafkaRecordDto second = kafkaRecord("orders", 0, 1L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-2\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(first, second));
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(first, second));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
org.mockito.Mockito.doNothing()
|
||||
.doThrow(new RuntimeException("boom"))
|
||||
@@ -207,17 +201,42 @@ class PipesPollerTest {
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
|
||||
ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> offsetsCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KafkaOffsetDto>> offsetsCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(kafkaConsumerManager).commit(eq(pipe), offsetsCaptor.capture());
|
||||
assertEquals(1L, offsetsCaptor.getValue().get(new TopicPartition("orders", 0)).offset());
|
||||
assertEquals(1L, singleOffset(offsetsCaptor.getValue(), "orders", 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollKafka_laterGeneratedBatchDoesNotCommitPastAnEarlierFailureInTheSamePartition() throws Exception {
|
||||
// A REST Proxy poll can return more than one BatchSize worth of records, so pollKafka
|
||||
// splits them into several generated batches. If the first batch fails to deliver record 0
|
||||
// and a later batch then succeeds delivering record 1 from the same partition, the second
|
||||
// batch's commit must not advance past record 0, or it is lost forever.
|
||||
Pipe pipe = selfManagedKafkaPipe();
|
||||
when(kafkaConsumerManager.resolveBatchSize(eq(pipe), anyInt())).thenReturn(1);
|
||||
KafkaRecordDto first = kafkaRecord("orders", 0, 0L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
KafkaRecordDto second = kafkaRecord("orders", 0, 1L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-2\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(first, second));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
org.mockito.Mockito.doThrow(new RuntimeException("boom"))
|
||||
.doNothing()
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
|
||||
verify(kafkaConsumerManager, never()).commit(eq(pipe), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollKafka_representsNullKeyAndValueAsJsonNull() throws Exception {
|
||||
Pipe pipe = nullableSelfManagedKafkaPipe();
|
||||
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("orders", 0, 3L, null, null);
|
||||
KafkaRecordDto record = kafkaRecord("orders", 0, 3L, null, null);
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(record));
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(record));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
@@ -232,14 +251,14 @@ class PipesPollerTest {
|
||||
@Test
|
||||
void pollKafka_lambdaCommitsSuccessfulPrefixBeforeLaterFailure() throws Exception {
|
||||
Pipe pipe = lambdaSelfManagedKafkaPipe();
|
||||
ConsumerRecord<byte[], byte[]> first = new ConsumerRecord<>(
|
||||
"orders", 0, 0L, null, "{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(StandardCharsets.UTF_8));
|
||||
ConsumerRecord<byte[], byte[]> skipped = new ConsumerRecord<>(
|
||||
"orders", 0, 1L, null, "{\"status\":\"inactive\",\"id\":\"order-2\"}".getBytes(StandardCharsets.UTF_8));
|
||||
ConsumerRecord<byte[], byte[]> failing = new ConsumerRecord<>(
|
||||
"orders", 0, 2L, null, "{\"status\":\"active\",\"id\":\"order-3\"}".getBytes(StandardCharsets.UTF_8));
|
||||
KafkaRecordDto first = kafkaRecord("orders", 0, 0L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-1\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
KafkaRecordDto skipped = kafkaRecord("orders", 0, 1L, null,
|
||||
"{\"status\":\"inactive\",\"id\":\"order-2\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
KafkaRecordDto failing = kafkaRecord("orders", 0, 2L, null,
|
||||
"{\"status\":\"active\",\"id\":\"order-3\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(records(first, skipped, failing));
|
||||
when(kafkaConsumerManager.poll(pipe)).thenReturn(List.of(first, skipped, failing));
|
||||
when(kafkaConsumerManager.resolveBootstrapServers(pipe)).thenReturn("broker-1:9092");
|
||||
org.mockito.Mockito.doNothing()
|
||||
.doThrow(new RuntimeException("boom"))
|
||||
@@ -247,9 +266,10 @@ class PipesPollerTest {
|
||||
|
||||
poller.pollKafka(pipe, "us-east-1");
|
||||
|
||||
ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> offsetsCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KafkaOffsetDto>> offsetsCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(kafkaConsumerManager).commit(eq(pipe), offsetsCaptor.capture());
|
||||
assertEquals(2L, offsetsCaptor.getValue().get(new TopicPartition("orders", 0)).offset());
|
||||
assertEquals(2L, singleOffset(offsetsCaptor.getValue(), "orders", 0));
|
||||
}
|
||||
|
||||
private Pipe selfManagedKafkaPipe() throws Exception {
|
||||
@@ -300,12 +320,17 @@ class PipesPollerTest {
|
||||
return pipe;
|
||||
}
|
||||
|
||||
private ConsumerRecords<byte[], byte[]> records(ConsumerRecord<byte[], byte[]>... records) {
|
||||
Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> byPartition = new java.util.LinkedHashMap<>();
|
||||
for (ConsumerRecord<byte[], byte[]> record : records) {
|
||||
TopicPartition topicPartition = new TopicPartition(record.topic(), record.partition());
|
||||
byPartition.computeIfAbsent(topicPartition, ignored -> new java.util.ArrayList<>()).add(record);
|
||||
}
|
||||
return new ConsumerRecords<>(byPartition);
|
||||
private static KafkaRecordDto kafkaRecord(String topic, int partition, long offset, byte[] key, byte[] value,
|
||||
KafkaHeaderDto... headers) {
|
||||
return new KafkaRecordDto(topic, partition, offset, System.currentTimeMillis(),
|
||||
KafkaRecordDto.DEFAULT_TIMESTAMP_TYPE, key, value, List.of(headers));
|
||||
}
|
||||
|
||||
private static long singleOffset(List<KafkaOffsetDto> offsets, String topic, int partition) {
|
||||
return offsets.stream()
|
||||
.filter(offset -> offset.topic().equals(topic) && offset.partition() == partition)
|
||||
.mapToLong(KafkaOffsetDto::offset)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user