Rückbau auf einen Consumer, der in `onPartitionsRevoked()` immer committed
[demos/kafka/training] / src / test / java / de / juplo / kafka / GenericApplicationTests.java
1 package de.juplo.kafka;
2
3 import com.mongodb.client.MongoClient;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
6 import org.apache.kafka.clients.consumer.ConsumerRecord;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.clients.producer.KafkaProducer;
9 import org.apache.kafka.clients.producer.ProducerRecord;
10 import org.apache.kafka.common.TopicPartition;
11 import org.apache.kafka.common.errors.RecordDeserializationException;
12 import org.apache.kafka.common.serialization.*;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
17 import org.springframework.boot.autoconfigure.mongo.MongoProperties;
18 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Import;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
25
26 import java.time.Duration;
27 import java.util.*;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
33
34 import static de.juplo.kafka.GenericApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.GenericApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
38
39
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestPropertySource(
42                 properties = {
43                                 "sumup.adder.bootstrap-server=${spring.embedded.kafka.brokers}",
44                                 "sumup.adder.topic=" + TOPIC,
45                                 "sumup.adder.commit-interval=500ms",
46                                 "spring.mongodb.embedded.version=4.4.13" })
47 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 @EnableAutoConfiguration
49 @AutoConfigureDataMongo
50 @Slf4j
51 abstract class GenericApplicationTests<K, V>
52 {
53         public static final String TOPIC = "FOO";
54         public static final int PARTITIONS = 10;
55
56
57         @Autowired
58         KafkaConsumer<K, V> kafkaConsumer;
59         @Autowired
60         Consumer<ConsumerRecord<K, V>> consumer;
61         @Autowired
62         ApplicationProperties properties;
63         @Autowired
64         ExecutorService executor;
65         @Autowired
66         MongoClient mongoClient;
67         @Autowired
68         MongoProperties mongoProperties;
69         @Autowired
70         ConsumerRebalanceListener rebalanceListener;
71         @Autowired
72         RecordHandler<K, V> recordHandler;
73
74         KafkaProducer<Bytes, Bytes> testRecordProducer;
75         KafkaConsumer<Bytes, Bytes> offsetConsumer;
76         EndlessConsumer<K, V> endlessConsumer;
77         Map<TopicPartition, Long> oldOffsets;
78         Map<TopicPartition, Long> seenOffsets;
79         Set<ConsumerRecord<K, V>> receivedRecords;
80
81
82         final RecordGenerator recordGenerator;
83         final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
84
85         public GenericApplicationTests(RecordGenerator recordGenerator)
86         {
87                 this.recordGenerator = recordGenerator;
88                 this.messageSender = (record) -> sendMessage(record);
89         }
90
91
92         /** Tests methods */
93
94         @Test
95         void commitsCurrentOffsetsOnSuccess() throws Exception
96         {
97                 int numberOfGeneratedMessages =
98                                 recordGenerator.generate(false, false, messageSender);
99
100                 await(numberOfGeneratedMessages + " records received")
101                                 .atMost(Duration.ofSeconds(30))
102                                 .pollInterval(Duration.ofSeconds(1))
103                                 .until(() -> receivedRecords.size() >= numberOfGeneratedMessages);
104
105                 await("Offsets committed")
106                                 .atMost(Duration.ofSeconds(10))
107                                 .pollInterval(Duration.ofSeconds(1))
108                                 .untilAsserted(() ->
109                                 {
110                                         checkSeenOffsetsForProgress();
111                                         assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
112                                 });
113
114                 assertThatExceptionOfType(IllegalStateException.class)
115                                 .isThrownBy(() -> endlessConsumer.exitStatus())
116                                 .describedAs("Consumer should still be running");
117
118                 endlessConsumer.stop();
119                 recordGenerator.assertBusinessLogic();
120         }
121
122         @Test
123         @SkipWhenErrorCannotBeGenerated(poisonPill = true)
124         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
125         {
126                 int numberOfGeneratedMessages =
127                                 recordGenerator.generate(true, false, messageSender);
128
129                 await("Consumer failed")
130                                 .atMost(Duration.ofSeconds(30))
131                                 .pollInterval(Duration.ofSeconds(1))
132                                 .until(() -> !endlessConsumer.running());
133
134                 checkSeenOffsetsForProgress();
135                 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
136
137                 endlessConsumer.start();
138                 await("Consumer failed")
139                                 .atMost(Duration.ofSeconds(30))
140                                 .pollInterval(Duration.ofSeconds(1))
141                                 .until(() -> !endlessConsumer.running());
142
143                 checkSeenOffsetsForProgress();
144                 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
145                 assertThat(receivedRecords.size())
146                                 .describedAs("Received not all sent events")
147                                 .isLessThan(numberOfGeneratedMessages);
148
149                 assertThatNoException()
150                                 .describedAs("Consumer should not be running")
151                                 .isThrownBy(() -> endlessConsumer.exitStatus());
152                 assertThat(endlessConsumer.exitStatus())
153                                 .describedAs("Consumer should have exited abnormally")
154                                 .containsInstanceOf(RecordDeserializationException.class);
155
156                 recordGenerator.assertBusinessLogic();
157         }
158
159         @Test
160         @SkipWhenErrorCannotBeGenerated(logicError = true)
161         void doesNotCommitOffsetsOnLogicError()
162         {
163                 int numberOfGeneratedMessages =
164                                 recordGenerator.generate(false, true, messageSender);
165
166                 await("Consumer failed")
167                                 .atMost(Duration.ofSeconds(30))
168                                 .pollInterval(Duration.ofSeconds(1))
169                                 .until(() -> !endlessConsumer.running());
170
171                 checkSeenOffsetsForProgress();
172                 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
173
174                 endlessConsumer.start();
175                 await("Consumer failed")
176                                 .atMost(Duration.ofSeconds(30))
177                                 .pollInterval(Duration.ofSeconds(1))
178                                 .until(() -> !endlessConsumer.running());
179
180                 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
181
182                 assertThatNoException()
183                                 .describedAs("Consumer should not be running")
184                                 .isThrownBy(() -> endlessConsumer.exitStatus());
185                 assertThat(endlessConsumer.exitStatus())
186                                 .describedAs("Consumer should have exited abnormally")
187                                 .containsInstanceOf(RuntimeException.class);
188
189                 recordGenerator.assertBusinessLogic();
190         }
191
192
193         /** Helper methods for the verification of expectations */
194
195         void assertSeenOffsetsEqualCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
196         {
197                 doForCurrentOffsets((tp, offset) ->
198                 {
199                         Long expected = offsetsToCheck.get(tp) + 1;
200                         log.debug("Checking, if the offset {} for {} is exactly {}", offset, tp, expected);
201                         assertThat(offset)
202                                         .describedAs("Committed offset corresponds to the offset of the consumer")
203                                         .isEqualTo(expected);
204                 });
205         }
206
207         void assertSeenOffsetsAreBehindCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
208         {
209                 List<Boolean> isOffsetBehindSeen = new LinkedList<>();
210
211                 doForCurrentOffsets((tp, offset) ->
212                 {
213                         Long expected = offsetsToCheck.get(tp) + 1;
214                         log.debug("Checking, if the offset {} for {} is at most {}", offset, tp, expected);
215                         assertThat(offset)
216                                         .describedAs("Committed offset must be at most equal to the offset of the consumer")
217                                         .isLessThanOrEqualTo(expected);
218                         isOffsetBehindSeen.add(offset < expected);
219                 });
220
221                 assertThat(isOffsetBehindSeen.stream().reduce(false, (result, next) -> result | next))
222                                 .describedAs("Committed offsets are behind seen offsets")
223                                 .isTrue();
224         }
225
226         void checkSeenOffsetsForProgress()
227         {
228                 // Be sure, that some messages were consumed...!
229                 Set<TopicPartition> withProgress = new HashSet<>();
230                 partitions().forEach(tp ->
231                 {
232                         Long oldOffset = oldOffsets.get(tp) + 1;
233                         Long newOffset = seenOffsets.get(tp) + 1;
234                         if (!oldOffset.equals(newOffset))
235                         {
236                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
237                                 withProgress.add(tp);
238                         }
239                 });
240                 assertThat(withProgress)
241                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
242                                 .isNotEmpty();
243         }
244
245
246         /** Helper methods for setting up and running the tests */
247
248         void seekToEnd()
249         {
250                 offsetConsumer.assign(partitions());
251                 offsetConsumer.seekToEnd(partitions());
252                 partitions().forEach(tp ->
253                 {
254                         // seekToEnd() works lazily: it only takes effect on poll()/position()
255                         Long offset = offsetConsumer.position(tp);
256                         log.info("New position for {}: {}", tp, offset);
257                 });
258                 // The new positions must be commited!
259                 offsetConsumer.commitSync();
260                 offsetConsumer.unsubscribe();
261         }
262
263         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
264         {
265                 offsetConsumer.assign(partitions());
266                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
267                 offsetConsumer.unsubscribe();
268         }
269
270         List<TopicPartition> partitions()
271         {
272                 return
273                                 IntStream
274                                                 .range(0, PARTITIONS)
275                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
276                                                 .collect(Collectors.toList());
277         }
278
279
280         public interface RecordGenerator
281         {
282                 int generate(
283                                 boolean poisonPills,
284                                 boolean logicErrors,
285                                 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
286
287                 default boolean canGeneratePoisonPill()
288                 {
289                         return true;
290                 }
291
292                 default boolean canGenerateLogicError()
293                 {
294                         return true;
295                 }
296
297                 default void assertBusinessLogic()
298                 {
299                         log.debug("No business-logic to assert");
300                 }
301         }
302
303         void sendMessage(ProducerRecord<Bytes, Bytes> record)
304         {
305                 testRecordProducer.send(record, (metadata, e) ->
306                 {
307                         if (metadata != null)
308                         {
309                                 log.debug(
310                                                 "{}|{} - {}={}",
311                                                 metadata.partition(),
312                                                 metadata.offset(),
313                                                 record.key(),
314                                                 record.value());
315                         }
316                         else
317                         {
318                                 log.warn(
319                                                 "Exception for {}={}: {}",
320                                                 record.key(),
321                                                 record.value(),
322                                                 e.toString());
323                         }
324                 });
325         }
326
327
328         @BeforeEach
329         public void init()
330         {
331                 Properties props;
332                 props = new Properties();
333                 props.put("bootstrap.servers", properties.getBootstrapServer());
334                 props.put("linger.ms", 100);
335                 props.put("key.serializer", BytesSerializer.class.getName());
336                 props.put("value.serializer", BytesSerializer.class.getName());
337                 testRecordProducer = new KafkaProducer<>(props);
338
339                 props = new Properties();
340                 props.put("bootstrap.servers", properties.getBootstrapServer());
341                 props.put("client.id", "OFFSET-CONSUMER");
342                 props.put("group.id", properties.getGroupId());
343                 props.put("key.deserializer", BytesDeserializer.class.getName());
344                 props.put("value.deserializer", BytesDeserializer.class.getName());
345                 offsetConsumer = new KafkaConsumer<>(props);
346
347                 mongoClient.getDatabase(mongoProperties.getDatabase()).drop();
348                 seekToEnd();
349
350                 oldOffsets = new HashMap<>();
351                 seenOffsets = new HashMap<>();
352                 receivedRecords = new HashSet<>();
353
354                 doForCurrentOffsets((tp, offset) ->
355                 {
356                         oldOffsets.put(tp, offset - 1);
357                         seenOffsets.put(tp, offset - 1);
358                 });
359
360                 TestRecordHandler<K, V> captureOffsetAndExecuteTestHandler =
361                                 new TestRecordHandler<K, V>(recordHandler)
362                                 {
363                                         @Override
364                                         public void onNewRecord(ConsumerRecord<K, V> record)
365                                         {
366                                                 seenOffsets.put(
367                                                                 new TopicPartition(record.topic(), record.partition()),
368                                                                 record.offset());
369                                                 receivedRecords.add(record);
370                                         }
371                                 };
372
373                 endlessConsumer =
374                                 new EndlessConsumer<>(
375                                                 executor,
376                                                 properties.getClientId(),
377                                                 properties.getTopic(),
378                                                 kafkaConsumer,
379                                                 rebalanceListener,
380                                                 captureOffsetAndExecuteTestHandler);
381
382                 endlessConsumer.start();
383         }
384
385         @AfterEach
386         public void deinit()
387         {
388                 try
389                 {
390                         testRecordProducer.close();
391                         offsetConsumer.close();
392                 }
393                 catch (Exception e)
394                 {
395                         log.info("Exception while stopping the consumer: {}", e.toString());
396                 }
397         }
398
399
400         @TestConfiguration
401         @Import(ApplicationConfiguration.class)
402         public static class Configuration
403         {
404         }
405 }