Files
spring-messaging-demo/cloud-stream/src/test/java/com/ankurm/cloudstream/Test03KafkaDlqTest.java
T

91 lines
5.3 KiB
Java

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");
}
}
}