Files

103 lines
5.7 KiB
Java

package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ConfigurableApplicationContext;
/** The whole pipeline, supplier to consumer, on a real Kafka broker (apache/kafka in Testcontainers). */
@ExtendWith(OutputCaptureExtension.class)
class Test02KafkaPipelineTest {
@Test
void pipelineAndPartitions(CapturedOutput output) throws Exception {
String bootstrap = Brokers.kafka().getBootstrapServers();
try (Transcript t = new Transcript("04-kafka-pipeline");
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
.web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=kafka", "--demo.max-orders=12"},
prefixed(Brokers.kafkaProps()), prefixed(Brokers.suffixed("k2"))))) {
t.line("$ profile kafka, supplier capped at 12 orders (demo.max-orders=12), broker %s", Brokers.KAFKA_IMAGE);
assertThat(Await.until(Duration.ofSeconds(60), () -> Test01TestBinderTest.count(output, "billed o-") == 12)).isTrue();
t.line("billed lines in the application log: %d", Test01TestBinderTest.count(output, "billed o-"));
try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
Map<String, TopicDescription> topics = admin.describeTopics(List.of("orders-k2", "invoices-k2")).allTopicNames().get();
for (String name : new TreeSet<>(topics.keySet())) {
t.line("topic %s created by the binder with %d partition(s)", name, topics.get(name).partitions().size());
}
assertThat(topics.get("orders-k2").partitions()).hasSize(3);
assertThat(topics.get("invoices-k2").partitions()).hasSize(1);
var group = admin.describeConsumerGroups(List.of("pricing")).all().get().get("pricing");
t.line("consumer group 'pricing': %d members (concurrency=3), partitions per member %s", group.members().size(),
group.members().stream().map(m -> m.assignment().topicPartitions().size()).sorted().toList());
assertThat(group.members()).hasSize(3);
}
Properties p = new Properties();
p.put("bootstrap.servers", bootstrap);
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
p.put("group.id", "inspector-" + System.nanoTime());
Map<Integer, List<String>> byPartition = new TreeMap<>();
int keyed = 0;
try (KafkaConsumer<String, String> c = new KafkaConsumer<>(p)) {
List<TopicPartition> tps = List.of(new TopicPartition("orders-k2", 0), new TopicPartition("orders-k2", 1),
new TopicPartition("orders-k2", 2));
c.assign(tps);
c.seekToBeginning(tps);
for (ConsumerRecord<String, String> r : c.poll(Duration.ofSeconds(5))) {
byPartition.computeIfAbsent(r.partition(), k -> new ArrayList<>())
.add(r.value().replaceAll(".*\"customerId\":\"(\\w+)\".*", "$1"));
if (r.key() != null) {
keyed++;
}
}
}
t.line("records on orders-k2 by partition (customer of each record):");
byPartition.forEach((part, customers) -> t.line(" partition %d: %s", part, customers));
t.line("records that carry a Kafka message key: %d", keyed);
for (String customer : List.of("alice", "bob", "carol", "dave")) {
long partitions = byPartition.values().stream().filter(l -> l.contains(customer)).count();
int murmur = org.apache.kafka.common.utils.Utils.toPositive(
org.apache.kafka.common.utils.Utils.murmur2(customer.getBytes(java.nio.charset.StandardCharsets.UTF_8))) % 3;
int hash = Math.abs(customer.hashCode()) % 3;
int actual = byPartition.entrySet().stream().filter(e -> e.getValue().contains(customer)).findFirst().get().getKey();
t.line("%s: in %d partition(s), actually partition %d; murmur2 %% 3 = %d, hashCode %% 3 = %d", customer, partitions,
actual, murmur, hash);
assertThat(partitions).isEqualTo(1);
assertThat(actual).isEqualTo(murmur);
}
assertThat(byPartition.values().stream().mapToInt(List::size).sum()).isEqualTo(12);
assertThat(keyed).isZero();
}
}
/** Spring Boot command-line arguments need the leading dashes. */
static String[] prefixed(String[] props) {
return java.util.Arrays.stream(props).map(s -> "--" + s).toArray(String[]::new);
}
}