Verbesserungen aus 'stored-offsets' nach 'stored-state' gemerged
[demos/kafka/training] / src / test / java / de / juplo / kafka / ApplicationTests.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.KafkaConsumer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.RecordDeserializationException;
10 import org.apache.kafka.common.serialization.*;
11 import org.apache.kafka.common.utils.Bytes;
12 import org.junit.jupiter.api.*;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
15 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23
24 import java.time.Duration;
25 import java.util.*;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.stream.Collectors;
30 import java.util.stream.IntStream;
31
32 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
33 import static de.juplo.kafka.ApplicationTests.TOPIC;
34 import static org.assertj.core.api.Assertions.*;
35 import static org.awaitility.Awaitility.*;
36
37
38 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
39 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
40 @TestPropertySource(
41                 properties = {
42                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
43                                 "consumer.topic=" + TOPIC,
44                                 "consumer.commit-interval=1s",
45                                 "spring.mongodb.embedded.version=4.4.13" })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 @EnableAutoConfiguration
48 @AutoConfigureDataMongo
49 @Slf4j
50 class ApplicationTests
51 {
52         public static final String TOPIC = "FOO";
53         public static final int PARTITIONS = 10;
54
55
56         StringSerializer stringSerializer = new StringSerializer();
57
58         @Autowired
59         Serializer valueSerializer;
60         @Autowired
61         KafkaProducer<String, Bytes> kafkaProducer;
62         @Autowired
63         KafkaConsumer<String, Long> kafkaConsumer;
64         @Autowired
65         KafkaConsumer<Bytes, Bytes> offsetConsumer;
66         @Autowired
67         ApplicationProperties properties;
68         @Autowired
69         ExecutorService executor;
70         @Autowired
71         KeyCountingRebalanceListener keyCountingRebalanceListener;
72         @Autowired
73         KeyCountingRecordHandler keyCountingRecordHandler;
74
75         EndlessConsumer<String, Long> endlessConsumer;
76         Map<TopicPartition, Long> oldOffsets;
77         Map<TopicPartition, Long> newOffsets;
78         Set<ConsumerRecord<String, Long>> receivedRecords;
79
80
81         /** Tests methods */
82
83         @Test
84         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
85         {
86                 send100Messages((partition, key, counter) ->
87                 {
88                         Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
89                         return new ProducerRecord<>(TOPIC, partition, key, value);
90                 });
91
92                 await("100 records received")
93                                 .atMost(Duration.ofSeconds(30))
94                                 .pollInterval(Duration.ofSeconds(1))
95                                 .until(() -> receivedRecords.size() >= 100);
96
97                 await("Offsets committed")
98                                 .atMost(Duration.ofSeconds(10))
99                                 .pollInterval(Duration.ofSeconds(1))
100                                 .untilAsserted(() ->
101                                 {
102                                         checkSeenOffsetsForProgress();
103                                         compareToCommitedOffsets(newOffsets);
104                                 });
105
106                 assertThatExceptionOfType(IllegalStateException.class)
107                                 .isThrownBy(() -> endlessConsumer.exitStatus())
108                                 .describedAs("Consumer should still be running");
109         }
110
111         @Test
112         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
113         {
114                 send100Messages((partition, key, counter) ->
115                 {
116                         Bytes value = counter == 77
117                                         ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
118                                         : new Bytes(valueSerializer.serialize(TOPIC, counter));
119                         return new ProducerRecord<>(TOPIC, partition, key, value);
120                 });
121
122                 await("Consumer failed")
123                                 .atMost(Duration.ofSeconds(30))
124                                 .pollInterval(Duration.ofSeconds(1))
125                                 .until(() -> !endlessConsumer.running());
126
127                 checkSeenOffsetsForProgress();
128                 compareToCommitedOffsets(newOffsets);
129
130                 endlessConsumer.start();
131                 await("Consumer failed")
132                                 .atMost(Duration.ofSeconds(30))
133                                 .pollInterval(Duration.ofSeconds(1))
134                                 .until(() -> !endlessConsumer.running());
135
136                 checkSeenOffsetsForProgress();
137                 compareToCommitedOffsets(newOffsets);
138                 assertThat(receivedRecords.size())
139                                 .describedAs("Received not all sent events")
140                                 .isLessThan(100);
141
142                 assertThatNoException()
143                                 .describedAs("Consumer should not be running")
144                                 .isThrownBy(() -> endlessConsumer.exitStatus());
145                 assertThat(endlessConsumer.exitStatus())
146                                 .describedAs("Consumer should have exited abnormally")
147                                 .containsInstanceOf(RecordDeserializationException.class);
148         }
149
150
151         /** Helper methods for the verification of expectations */
152
153         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
154         {
155                 doForCurrentOffsets((tp, offset) ->
156                 {
157                         Long expected = offsetsToCheck.get(tp) + 1;
158                         log.debug("Checking, if the offset for {} is {}", tp, expected);
159                         assertThat(offset)
160                                         .describedAs("Committed offset corresponds to the offset of the consumer")
161                                         .isEqualTo(expected);
162                 });
163         }
164
165         void checkSeenOffsetsForProgress()
166         {
167                 // Be sure, that some messages were consumed...!
168                 Set<TopicPartition> withProgress = new HashSet<>();
169                 partitions().forEach(tp ->
170                 {
171                         Long oldOffset = oldOffsets.get(tp) + 1;
172                         Long newOffset = newOffsets.get(tp) + 1;
173                         if (!oldOffset.equals(newOffset))
174                         {
175                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
176                                 withProgress.add(tp);
177                         }
178                 });
179                 assertThat(withProgress)
180                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
181                                 .isNotEmpty();
182         }
183
184
185         /** Helper methods for setting up and running the tests */
186
187         void seekToEnd()
188         {
189                 offsetConsumer.assign(partitions());
190                 offsetConsumer.seekToEnd(partitions());
191                 partitions().forEach(tp ->
192                 {
193                         // seekToEnd() works lazily: it only takes effect on poll()/position()
194                         Long offset = offsetConsumer.position(tp);
195                         log.info("New position for {}: {}", tp, offset);
196                 });
197                 // The new positions must be commited!
198                 offsetConsumer.commitSync();
199                 offsetConsumer.unsubscribe();
200         }
201
202         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
203         {
204                 offsetConsumer.assign(partitions());
205                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
206                 offsetConsumer.unsubscribe();
207         }
208
209         List<TopicPartition> partitions()
210         {
211                 return
212                                 IntStream
213                                                 .range(0, PARTITIONS)
214                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
215                                                 .collect(Collectors.toList());
216         }
217
218
219         public interface RecordGenerator<K, V>
220         {
221                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
222         }
223
224         void send100Messages(RecordGenerator recordGenerator)
225         {
226                 long i = 0;
227
228                 for (int partition = 0; partition < 10; partition++)
229                 {
230                         for (int key = 0; key < 10; key++)
231                         {
232                                 ProducerRecord<String, Bytes> record =
233                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
234
235                                 kafkaProducer.send(record, (metadata, e) ->
236                                 {
237                                         if (metadata != null)
238                                         {
239                                                 log.debug(
240                                                                 "{}|{} - {}={}",
241                                                                 metadata.partition(),
242                                                                 metadata.offset(),
243                                                                 record.key(),
244                                                                 record.value());
245                                         }
246                                         else
247                                         {
248                                                 log.warn(
249                                                                 "Exception for {}={}: {}",
250                                                                 record.key(),
251                                                                 record.value(),
252                                                                 e.toString());
253                                         }
254                                 });
255                         }
256                 }
257         }
258
259
260         @BeforeEach
261         public void init()
262         {
263                 seekToEnd();
264
265                 oldOffsets = new HashMap<>();
266                 newOffsets = new HashMap<>();
267                 receivedRecords = new HashSet<>();
268
269                 doForCurrentOffsets((tp, offset) ->
270                 {
271                         oldOffsets.put(tp, offset - 1);
272                         newOffsets.put(tp, offset - 1);
273                 });
274
275                 TestRecordHandler<String, Long> captureOffsetAndExecuteTestHandler =
276                                 new TestRecordHandler<String, Long>(keyCountingRecordHandler) {
277                                         @Override
278                                         public void onNewRecord(ConsumerRecord<String, Long> record)
279                                         {
280                                                 newOffsets.put(
281                                                                 new TopicPartition(record.topic(), record.partition()),
282                                                                 record.offset());
283                                                 receivedRecords.add(record);
284                                         }
285                                 };
286
287                 endlessConsumer =
288                                 new EndlessConsumer<>(
289                                                 executor,
290                                                 properties.getClientId(),
291                                                 properties.getTopic(),
292                                                 kafkaConsumer,
293                                                 keyCountingRebalanceListener,
294                                                 captureOffsetAndExecuteTestHandler);
295
296                 endlessConsumer.start();
297         }
298
299         @AfterEach
300         public void deinit()
301         {
302                 try
303                 {
304                         endlessConsumer.stop();
305                 }
306                 catch (Exception e)
307                 {
308                         log.info("Exception while stopping the consumer: {}", e.toString());
309                 }
310         }
311
312
313         @TestConfiguration
314         @Import(ApplicationConfiguration.class)
315         public static class Configuration
316         {
317                 @Bean
318                 Serializer<Long> serializer()
319                 {
320                         return new LongSerializer();
321                 }
322
323                 @Bean
324                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
325                 {
326                         Properties props = new Properties();
327                         props.put("bootstrap.servers", properties.getBootstrapServer());
328                         props.put("linger.ms", 100);
329                         props.put("key.serializer", StringSerializer.class.getName());
330                         props.put("value.serializer", BytesSerializer.class.getName());
331
332                         return new KafkaProducer<>(props);
333                 }
334
335                 @Bean
336                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
337                 {
338                         Properties props = new Properties();
339                         props.put("bootstrap.servers", properties.getBootstrapServer());
340                         props.put("client.id", "OFFSET-CONSUMER");
341                         props.put("group.id", properties.getGroupId());
342                         props.put("key.deserializer", BytesDeserializer.class.getName());
343                         props.put("value.deserializer", BytesDeserializer.class.getName());
344
345                         return new KafkaConsumer<>(props);
346                 }
347         }
348 }