Add cloud-stream module: Spring Cloud Stream 5.1 on Boot 4.2 with Kafka and RabbitMQ binders
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
e54cf840fd
commit
e2c42dc268
@@ -0,0 +1,25 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
final class Await {
|
||||
private Await() {
|
||||
}
|
||||
|
||||
static boolean until(Duration max, BooleanSupplier condition) {
|
||||
long end = System.nanoTime() + max.toNanos();
|
||||
while (System.nanoTime() < end) {
|
||||
if (condition.getAsBoolean()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return condition.getAsBoolean();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.testcontainers.kafka.KafkaContainer;
|
||||
import org.testcontainers.rabbitmq.RabbitMQContainer;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Lazily started singleton brokers shared by every test class in the run. */
|
||||
public final class Brokers {
|
||||
|
||||
public static final String KAFKA_IMAGE = "apache/kafka:4.4.0";
|
||||
public static final String RABBIT_IMAGE = "rabbitmq:4-management";
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
private static final HttpClient HTTP = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
|
||||
|
||||
private static KafkaContainer kafka;
|
||||
private static RabbitMQContainer rabbit;
|
||||
|
||||
private Brokers() {
|
||||
}
|
||||
|
||||
public static synchronized KafkaContainer kafka() {
|
||||
if (kafka == null) {
|
||||
kafka = new KafkaContainer(KAFKA_IMAGE);
|
||||
kafka.start();
|
||||
}
|
||||
return kafka;
|
||||
}
|
||||
|
||||
public static synchronized RabbitMQContainer rabbit() {
|
||||
if (rabbit == null) {
|
||||
rabbit = new RabbitMQContainer(RABBIT_IMAGE);
|
||||
rabbit.start();
|
||||
}
|
||||
return rabbit;
|
||||
}
|
||||
|
||||
/** Broker coordinates as command-line style properties, in the form Spring Boot and the binders read them. */
|
||||
public static String[] kafkaProps() {
|
||||
return new String[] {"spring.cloud.stream.kafka.binder.brokers=" + kafka().getBootstrapServers()};
|
||||
}
|
||||
|
||||
public static String[] rabbitProps() {
|
||||
RabbitMQContainer r = rabbit();
|
||||
return new String[] {"spring.rabbitmq.host=" + r.getHost(), "spring.rabbitmq.port=" + r.getAmqpPort(),
|
||||
"spring.rabbitmq.username=" + r.getAdminUsername(), "spring.rabbitmq.password=" + r.getAdminPassword()};
|
||||
}
|
||||
|
||||
/** Destination, DLQ and group names get a suffix so each test class works on its own topics and queues. */
|
||||
public static String[] suffixed(String suffix) {
|
||||
return new String[] {
|
||||
"spring.cloud.stream.bindings.orderSource-out-0.destination=orders-" + suffix,
|
||||
"spring.cloud.stream.bindings.priceOrder-in-0.destination=orders-" + suffix,
|
||||
"spring.cloud.stream.bindings.priceOrder-out-0.destination=invoices-" + suffix,
|
||||
"spring.cloud.stream.bindings.bill-in-0.destination=invoices-" + suffix,
|
||||
"spring.cloud.stream.kafka.bindings.bill-in-0.consumer.dlq-name=invoices-" + suffix + ".billing.dlq"};
|
||||
}
|
||||
|
||||
public static String[] concat(String[]... parts) {
|
||||
return java.util.stream.Stream.of(parts).flatMap(java.util.stream.Stream::of).toArray(String[]::new);
|
||||
}
|
||||
|
||||
// ---- RabbitMQ management API helpers --------------------------------------------------------------------
|
||||
|
||||
private static HttpRequest.Builder request(String path) {
|
||||
RabbitMQContainer r = rabbit();
|
||||
String auth = Base64.getEncoder().encodeToString((r.getAdminUsername() + ":" + r.getAdminPassword()).getBytes());
|
||||
return HttpRequest.newBuilder(URI.create("http://" + r.getHost() + ":" + r.getMappedPort(15672) + "/api" + path))
|
||||
.header("Authorization", "Basic " + auth).header("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
public static JsonNode mgmtGet(String path) {
|
||||
try {
|
||||
return JSON.readTree(HTTP.send(request(path).GET().build(), HttpResponse.BodyHandlers.ofString()).body());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonNode mgmtPost(String path, String body) {
|
||||
try {
|
||||
return JSON.readTree(HTTP.send(request(path).POST(HttpRequest.BodyPublishers.ofString(body)).build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Messages (ready + unacked) as rabbitmqctl reports them, or -1 when the queue does not exist. */
|
||||
public static int depth(String queue) {
|
||||
try {
|
||||
String out = rabbit().execInContainer("rabbitmqctl", "-q", "list_queues", "name", "messages").getStdout();
|
||||
for (String line : out.split("\n")) {
|
||||
String[] c = line.split("\\s+");
|
||||
if (c.length == 2 && c[0].equals(queue)) {
|
||||
return Integer.parseInt(c[1]);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String listQueues(String prefix) {
|
||||
try {
|
||||
String out = rabbit().execInContainer("rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers").getStdout();
|
||||
return java.util.Arrays.stream(out.split("\n")).filter(l -> l.startsWith(prefix)).sorted()
|
||||
.collect(java.util.stream.Collectors.joining("\n"));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.cloud.stream.binder.test.InputDestination;
|
||||
import org.springframework.cloud.stream.binder.test.OutputDestination;
|
||||
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
|
||||
/**
|
||||
* The test binder replaces Kafka and RabbitMQ with in-memory destinations, so the three function
|
||||
* types can be exercised with no broker and no Docker. The same CloudStreamApplication is used: only
|
||||
* the binder changes.
|
||||
*/
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class Test01TestBinderTest {
|
||||
|
||||
private static ConfigurableApplicationContext start(String... args) {
|
||||
return new SpringApplicationBuilder(TestChannelBinderConfiguration.getCompleteConfiguration(CloudStreamApplication.class))
|
||||
.web(WebApplicationType.NONE).run(args);
|
||||
}
|
||||
|
||||
private static Message<byte[]> json(String s) {
|
||||
return MessageBuilder.withPayload(s.getBytes()).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void function() {
|
||||
try (Transcript t = new Transcript("01-test-binder-function");
|
||||
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=priceOrder")) {
|
||||
InputDestination in = ctx.getBean(InputDestination.class);
|
||||
OutputDestination out = ctx.getBean(OutputDestination.class);
|
||||
t.line("$ function definition = priceOrder (binder: test, no broker)");
|
||||
in.send(json("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}"), "orders");
|
||||
Message<byte[]> reply = out.receive(2000, "invoices");
|
||||
t.line("in orders : {\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}");
|
||||
t.line("out invoices : %s", new String(reply.getPayload()));
|
||||
t.line("out contentType header: %s", reply.getHeaders().get("contentType"));
|
||||
assertThat(new String(reply.getPayload())).isEqualTo("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"total\":19.0}");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void supplier() {
|
||||
try (Transcript t = new Transcript("02-test-binder-supplier");
|
||||
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=orderSource",
|
||||
"--spring.cloud.stream.poller.fixed-delay=100", "--demo.max-orders=5")) {
|
||||
OutputDestination out = ctx.getBean(OutputDestination.class);
|
||||
t.line("$ function definition = orderSource, poller fixed-delay = 100 ms, demo.max-orders = 5");
|
||||
List<String> got = new ArrayList<>();
|
||||
Message<byte[]> m;
|
||||
while ((m = out.receive(1500, "orders")) != null) {
|
||||
got.add(new String(m.getPayload()));
|
||||
t.line("polled #%d: %s", got.size(), got.get(got.size() - 1));
|
||||
t.line(" headers: %s scst_partition=%s", new java.util.TreeSet<>(m.getHeaders().keySet()), m.getHeaders().get("scst_partition"));
|
||||
}
|
||||
t.line("messages sent before the supplier started returning null: %d", got.size());
|
||||
assertThat(got).hasSize(5);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumer(CapturedOutput output) {
|
||||
try (Transcript t = new Transcript("03-test-binder-consumer");
|
||||
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=bill")) {
|
||||
InputDestination in = ctx.getBean(InputDestination.class);
|
||||
t.line("$ function definition = bill (max-attempts=3, back-off 200 ms)");
|
||||
in.send(json("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"total\":19.0}"), "invoices");
|
||||
t.line("good invoice sent -> log lines containing 'bill attempt for o-1': %d", count(output, "bill attempt for o-1"));
|
||||
String poisonResult;
|
||||
try {
|
||||
in.send(json("{\"orderId\":\"o-2\",\"customerId\":\"bob\",\"total\":-1.0}"), "invoices");
|
||||
poisonResult = "send() returned normally";
|
||||
} catch (Exception e) {
|
||||
poisonResult = "send() threw " + e.getClass().getSimpleName() + ": " + rootMessage(e);
|
||||
}
|
||||
t.line("poison invoice sent -> attempts: %d", count(output, "bill attempt for o-2"));
|
||||
t.line("%s", poisonResult);
|
||||
}
|
||||
}
|
||||
|
||||
static int count(CapturedOutput output, String needle) {
|
||||
String s = output.getAll();
|
||||
int n = 0;
|
||||
for (int i = s.indexOf(needle); i >= 0; i = s.indexOf(needle, i + 1)) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static String rootMessage(Throwable e) {
|
||||
while (e.getCause() != null) {
|
||||
e = e.getCause();
|
||||
}
|
||||
return e.getMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.common.header.Header;
|
||||
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.cloud.stream.function.StreamBridge;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
/** Dead-letter handling with the Kafka binder: enable-dlq republishes a failed record to a DLQ topic. */
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class Test03KafkaDlqTest {
|
||||
|
||||
@Test
|
||||
void poisonGoesToTheDlqTopic(CapturedOutput output) throws Exception {
|
||||
try (Transcript t = new Transcript("05-kafka-dlq");
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run(Brokers.concat(new String[] {"--spring.profiles.active=kafka",
|
||||
"--spring.cloud.function.definition=bill"},
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.kafkaProps()),
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.suffixed("k3"))))) {
|
||||
StreamBridge bridge = ctx.getBean(StreamBridge.class);
|
||||
t.line("$ profile kafka, function definition = bill, enable-dlq=true, max-attempts=3");
|
||||
bridge.send("invoices-k3", new Invoice("o-1", "alice", 19.0));
|
||||
bridge.send("invoices-k3", new Invoice("o-2", "bob", -1.0));
|
||||
bridge.send("invoices-k3", new Invoice("o-3", "carol", 9.5));
|
||||
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed o-3") == 1)).isTrue();
|
||||
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "bill attempt for o-2") == 3)).isTrue();
|
||||
t.line("bill attempts: o-1=%d o-2=%d o-3=%d", Test01TestBinderTest.count(output, "bill attempt for o-1"),
|
||||
Test01TestBinderTest.count(output, "bill attempt for o-2"), Test01TestBinderTest.count(output, "bill attempt for o-3"));
|
||||
t.line("billed: o-1=%d o-2=%d o-3=%d (o-3 was behind the poison record on the same partition)",
|
||||
Test01TestBinderTest.count(output, "billed o-1"), Test01TestBinderTest.count(output, "billed o-2"),
|
||||
Test01TestBinderTest.count(output, "billed o-3"));
|
||||
|
||||
Properties p = new Properties();
|
||||
p.put("bootstrap.servers", Brokers.kafka().getBootstrapServers());
|
||||
p.put("key.deserializer", StringDeserializer.class.getName());
|
||||
p.put("value.deserializer", StringDeserializer.class.getName());
|
||||
p.put("group.id", "inspector-" + System.nanoTime());
|
||||
p.put("auto.offset.reset", "earliest");
|
||||
List<ConsumerRecord<String, String>> dead = new java.util.ArrayList<>();
|
||||
try (KafkaConsumer<String, String> c = new KafkaConsumer<>(p)) {
|
||||
c.subscribe(List.of("invoices-k3.billing.dlq"));
|
||||
Await.until(Duration.ofSeconds(20), () -> {
|
||||
c.poll(Duration.ofMillis(500)).forEach(dead::add);
|
||||
return !dead.isEmpty();
|
||||
});
|
||||
}
|
||||
assertThat(dead).hasSize(1);
|
||||
ConsumerRecord<String, String> r = dead.get(0);
|
||||
t.line("DLQ topic invoices-k3.billing.dlq holds %d record(s)", dead.size());
|
||||
t.line("payload: %s", r.value());
|
||||
for (Header h : r.headers()) {
|
||||
if (!h.key().startsWith("x-")) {
|
||||
continue;
|
||||
}
|
||||
String v = switch (h.key()) {
|
||||
case "x-original-partition" -> String.valueOf(java.nio.ByteBuffer.wrap(h.value()).getInt());
|
||||
case "x-original-offset", "x-original-timestamp" -> String.valueOf(java.nio.ByteBuffer.wrap(h.value()).getLong());
|
||||
default -> new String(h.value(), StandardCharsets.UTF_8).replace("\n", " ").replaceAll("Lambda/0x[0-9a-f]+", "Lambda/0x...");
|
||||
};
|
||||
if (h.key().equals("x-original-timestamp")) {
|
||||
v = "(epoch millis, omitted)";
|
||||
}
|
||||
t.line("header %s = %s", h.key(), v.length() > 90 ? v.substring(0, 90) + "..." : v);
|
||||
if (h.key().equals("x-exception-stacktrace")) {
|
||||
String full = new String(h.value(), StandardCharsets.UTF_8);
|
||||
t.line(" stack trace mentions the real cause (IllegalArgumentException: Refusing to bill o-2): %s",
|
||||
full.contains("java.lang.IllegalArgumentException: Refusing to bill o-2"));
|
||||
assertThat(full).contains("java.lang.IllegalArgumentException: Refusing to bill o-2");
|
||||
}
|
||||
}
|
||||
assertThat(r.value()).contains("o-2");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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 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 same pipeline on RabbitMQ. Rabbit has no partitions inside a queue: the binder fakes them with one queue per
|
||||
* partition (orders.pricing-0, -1, -2) and each consumer instance owns exactly one of them.
|
||||
*/
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class Test04RabbitPipelineTest {
|
||||
|
||||
private static ConfigurableApplicationContext start(String suffix, int index, String definition, String... extra) {
|
||||
return new SpringApplicationBuilder(CloudStreamApplication.class).web(WebApplicationType.NONE)
|
||||
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--demo.max-orders=12",
|
||||
"--spring.cloud.function.definition=" + definition,
|
||||
"--spring.cloud.stream.bindings.priceOrder-in-0.consumer.instance-index=" + index},
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.suffixed(suffix)), extra));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneInstanceOwnsOneQueue(CapturedOutput output) throws Exception {
|
||||
try (Transcript t = new Transcript("06-rabbit-partitions")) {
|
||||
t.line("$ profile rabbit, 12 orders: alice, bob, carol, dave x 3, partition-count=3, consumer instance-count=3 instance-index=0");
|
||||
|
||||
// Run A: the producer declares only the exchange, so a partition with no queue yet is dropped.
|
||||
int before = Test01TestBinderTest.count(output, "billed o-");
|
||||
try (ConfigurableApplicationContext a = start("r4a", 0, "orderSource;priceOrder;bill")) {
|
||||
Await.until(Duration.ofSeconds(20), () -> Test01TestBinderTest.count(output, "billed o-") - before >= 6);
|
||||
Thread.sleep(3000);
|
||||
t.line("");
|
||||
t.line("run A, no required-groups on the orders producer: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - before);
|
||||
t.line("queues on the broker (name, messages, consumers):");
|
||||
Brokers.listQueues("orders-r4a").lines().forEach(l -> t.line(" %s", l));
|
||||
assertThat(Test01TestBinderTest.count(output, "billed o-") - before).isEqualTo(6);
|
||||
}
|
||||
|
||||
// Run B: required-groups makes the producer declare every partition queue up front.
|
||||
int beforeB = Test01TestBinderTest.count(output, "billed o-");
|
||||
List<ConfigurableApplicationContext> extras = new ArrayList<>();
|
||||
try (ConfigurableApplicationContext b = start("r4b", 0, "orderSource;priceOrder;bill",
|
||||
"--spring.cloud.stream.bindings.orderSource-out-0.producer.required-groups=pricing")) {
|
||||
Await.until(Duration.ofSeconds(20), () -> Test01TestBinderTest.count(output, "billed o-") - beforeB >= 6);
|
||||
Thread.sleep(3000);
|
||||
t.line("");
|
||||
t.line("run B, required-groups=pricing on the orders producer: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - beforeB);
|
||||
t.line("queues on the broker (name, messages, consumers):");
|
||||
Brokers.listQueues("orders-r4b").lines().forEach(l -> t.line(" %s", l));
|
||||
assertThat(Brokers.depth("orders-r4b.pricing-1")).isEqualTo(3);
|
||||
assertThat(Brokers.depth("orders-r4b.pricing-2")).isEqualTo(3);
|
||||
|
||||
// Run C: two more instances, one per remaining partition queue.
|
||||
extras.add(start("r4b", 1, "priceOrder"));
|
||||
extras.add(start("r4b", 2, "priceOrder"));
|
||||
Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed o-") - beforeB == 12);
|
||||
Thread.sleep(2000);
|
||||
t.line("");
|
||||
t.line("run C, plus instance-index 1 and 2: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - beforeB);
|
||||
t.line("queues on the broker (name, messages, consumers):");
|
||||
Brokers.listQueues("orders-r4b").lines().forEach(l -> t.line(" %s", l));
|
||||
assertThat(Test01TestBinderTest.count(output, "billed o-") - beforeB).isEqualTo(12);
|
||||
} finally {
|
||||
extras.forEach(ConfigurableApplicationContext::close);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.TreeSet;
|
||||
|
||||
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.cloud.stream.function.StreamBridge;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
|
||||
/** Dead-lettering with the Rabbit binder, with and without republish-to-dlq. */
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class Test05RabbitDlqTest {
|
||||
|
||||
private static ConfigurableApplicationContext start(String suffix, String... extra) {
|
||||
return new SpringApplicationBuilder(CloudStreamApplication.class).web(WebApplicationType.NONE)
|
||||
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--spring.cloud.function.definition=bill"},
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.suffixed(suffix)), extra));
|
||||
}
|
||||
|
||||
private void poisonRun(Transcript t, CapturedOutput output, String suffix, String label, String... extra) throws Exception {
|
||||
t.line("");
|
||||
t.line("--- %s ---", label);
|
||||
try (ConfigurableApplicationContext ctx = start(suffix, extra)) {
|
||||
StreamBridge bridge = ctx.getBean(StreamBridge.class);
|
||||
bridge.send("invoices-" + suffix, new Invoice("p-" + suffix, "alice", -1.0));
|
||||
bridge.send("invoices-" + suffix, new Invoice("g-" + suffix, "bob", 9.5));
|
||||
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed g-" + suffix) == 1)).isTrue();
|
||||
assertThat(Await.until(Duration.ofSeconds(30), () -> Brokers.depth("invoices-" + suffix + ".billing.dlq") == 1)).isTrue();
|
||||
t.line("bill attempts for the poison invoice: %d", Test01TestBinderTest.count(output, "bill attempt for p-" + suffix));
|
||||
t.line("queues (name, messages, consumers):");
|
||||
Brokers.listQueues("invoices-" + suffix).lines().forEach(l -> t.line(" %s", l.replace(suffix, "<run>")));
|
||||
JsonNode msgs = Brokers.mgmtPost("/queues/%2F/invoices-" + suffix + ".billing.dlq/get",
|
||||
"{\"count\":1,\"ackmode\":\"ack_requeue_true\",\"encoding\":\"auto\"}");
|
||||
JsonNode m = msgs.get(0);
|
||||
t.line("DLQ payload: %s", m.path("payload").asString());
|
||||
TreeSet<String> headers = new TreeSet<>(m.path("properties").path("headers").propertyNames());
|
||||
t.line("DLQ header names: %s", headers);
|
||||
for (String h : headers) {
|
||||
if (h.equals("x-exception-message") || h.equals("x-original-exchange") || h.equals("x-original-routingKey")
|
||||
|| h.equals("x-first-death-reason") || h.equals("x-first-death-queue")) {
|
||||
t.line(" %s = %s", h, m.path("properties").path("headers").path(h).asString().replace(suffix, "<run>")
|
||||
.replaceAll("Lambda/0x[0-9a-f]+", "Lambda/0x..."));
|
||||
}
|
||||
}
|
||||
if (headers.contains("x-death")) {
|
||||
JsonNode death = m.path("properties").path("headers").path("x-death").get(0);
|
||||
t.line(" x-death: reason=%s queue=%s count=%d", death.path("reason").asString(),
|
||||
death.path("queue").asString().replace(suffix, "<run>"), death.path("count").asInt());
|
||||
}
|
||||
t.line("DLQ header has x-exception-stacktrace: %s", headers.contains("x-exception-stacktrace"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void republishVersusPlainDeadLettering(CapturedOutput output) throws Exception {
|
||||
try (Transcript t = new Transcript("07-rabbit-dlq")) {
|
||||
t.line("$ profile rabbit, function definition = bill, auto-bind-dlq=true, max-attempts=3");
|
||||
poisonRun(t, output, "r5a", "republish-to-dlq=true (what application-rabbit.yml sets)");
|
||||
poisonRun(t, output, "r5b", "republish-to-dlq=false (broker-side dead lettering only)",
|
||||
"--spring.cloud.stream.rabbit.bindings.bill-in-0.consumer.republish-to-dlq=false");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
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.cloud.stream.binder.test.InputDestination;
|
||||
import org.springframework.cloud.stream.binder.test.OutputDestination;
|
||||
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
|
||||
/** Three ways the wiring goes wrong, each with the symptom the framework really produces. */
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class Test06WiringMistakesTest {
|
||||
|
||||
@Test
|
||||
void twoBindersOnTheClasspathAndNoDefault() {
|
||||
try (Transcript t = new Transcript("08-two-binders-no-default")) {
|
||||
t.line("$ both binder starters on the classpath, no spring.cloud.stream.default-binder, no per-binding binder");
|
||||
String message;
|
||||
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
|
||||
.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=priceOrder")) {
|
||||
message = "context started";
|
||||
} catch (Exception e) {
|
||||
Throwable root = e;
|
||||
while (root.getCause() != null && !root.getMessage().contains("more than one binder")) {
|
||||
root = root.getCause();
|
||||
}
|
||||
message = root.getClass().getSimpleName() + ": " + root.getMessage();
|
||||
}
|
||||
t.line("%s", message);
|
||||
assertThat(message).contains("more than one binder");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void definitionMissing() {
|
||||
try (Transcript t = new Transcript("09-no-function-definition");
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(
|
||||
TestChannelBinderConfiguration.getCompleteConfiguration(CloudStreamApplication.class))
|
||||
.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=", "--demo.max-orders=3")) {
|
||||
t.line("$ three function beans (orderSource, priceOrder, bill), spring.cloud.function.definition left empty");
|
||||
t.line("beans of type Function: %s, Supplier: %s, Consumer: %s",
|
||||
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Function.class))),
|
||||
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Supplier.class))),
|
||||
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Consumer.class))));
|
||||
InputDestination in = ctx.getBean(InputDestination.class);
|
||||
OutputDestination out = ctx.getBean(OutputDestination.class);
|
||||
String result;
|
||||
try {
|
||||
in.send(MessageBuilder.withPayload("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}".getBytes()).build(), "orders");
|
||||
Message<byte[]> reply = out.receive(1500, "invoices");
|
||||
result = reply == null ? "sent to 'orders', nothing came out of 'invoices'" : "reply: " + new String(reply.getPayload());
|
||||
} catch (Exception e) {
|
||||
result = "send threw " + e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
t.line("%s", result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredGroupsWithoutProducerDlqArguments(CapturedOutput output) throws Exception {
|
||||
try (Transcript t = new Transcript("10-rabbit-required-groups-mismatch");
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--demo.max-orders=3",
|
||||
"--spring.cloud.function.definition=priceOrder;bill",
|
||||
"--spring.cloud.stream.rabbit.bindings.priceOrder-out-0.producer.auto-bind-dlq=false"},
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
|
||||
Test02KafkaPipelineTest.prefixed(Brokers.suffixed("r6"))))) {
|
||||
t.line("$ rabbit profile, but the producer binding priceOrder-out-0 has required-groups=billing and auto-bind-dlq=false");
|
||||
assertThat(Await.until(Duration.ofSeconds(20), () -> output.getAll().contains("PRECONDITION_FAILED"))).isTrue();
|
||||
String line = output.getAll().lines().filter(l -> l.contains("PRECONDITION_FAILED")).findFirst().get();
|
||||
t.line("%s", line.substring(line.indexOf("reply-code=")).replaceAll("class-id.*", "").replace("invoices-r6", "invoices-<run>").replaceAll(",\\s*$", ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.cloudstream;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Collects lines and writes them to output/NN-name.txt when closed. Tests assert the same values
|
||||
* they print, so every number in the article is an assertion that fails the build when it stops being true.
|
||||
*/
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path file;
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
|
||||
public Transcript(String name) {
|
||||
this.file = Path.of(System.getProperty("user.dir"), "output", name + ".txt");
|
||||
}
|
||||
|
||||
public Transcript line(String format, Object... args) {
|
||||
lines.add(args.length == 0 ? format : String.format(format, args));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, lines);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user