1 package de.juplo.kafka.payment.transfer.adapter;
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import de.juplo.kafka.payment.transfer.domain.Transfer;
6 import de.juplo.kafka.payment.transfer.ports.CreateTransferUseCase;
7 import de.juplo.kafka.payment.transfer.ports.GetTransferUseCase;
8 import de.juplo.kafka.payment.transfer.ports.HandleStateChangeUseCase;
9 import de.juplo.kafka.payment.transfer.ports.TransferRepository;
10 import lombok.extern.slf4j.Slf4j;
11 import org.apache.kafka.clients.admin.AdminClient;
12 import org.apache.kafka.clients.admin.MemberDescription;
13 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
14 import org.apache.kafka.clients.consumer.ConsumerRecord;
15 import org.apache.kafka.clients.consumer.ConsumerRecords;
16 import org.apache.kafka.clients.consumer.KafkaConsumer;
17 import org.apache.kafka.common.TopicPartition;
18 import org.apache.kafka.common.errors.WakeupException;
19 import org.springframework.context.event.ContextRefreshedEvent;
20 import org.springframework.context.event.EventListener;
21 import org.springframework.web.bind.annotation.PostMapping;
22 import org.springframework.web.bind.annotation.RequestMapping;
23 import org.springframework.web.bind.annotation.ResponseBody;
25 import java.time.Clock;
26 import java.time.Duration;
27 import java.time.Instant;
29 import java.util.concurrent.CompletableFuture;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.Future;
32 import java.util.stream.Collectors;
35 @RequestMapping("/consumer")
38 public class TransferConsumer implements Runnable, ConsumerRebalanceListener
40 private final String topic;
41 private final int numPartitions;
42 private final KafkaConsumer<String, String> consumer;
43 private final AdminClient adminClient;
44 private final TransferRepository repository;
45 private final ObjectMapper mapper;
46 private final ConsumerUseCases productionUseCases, restoreUseCases;
48 private boolean running = false;
49 private boolean shutdown = false;
50 private Future<?> future = null;
52 private final String groupId;
53 private final String groupInstanceId;
54 private final Map<String, String> instanceIdUriMapping;
55 private final String[] instanceIdByPartition;
58 private int stateStoreInterval;
60 private volatile boolean partitionOwnershipUnknown = true;
63 public TransferConsumer(
66 Map<String, String> instanceIdUriMapping,
67 KafkaConsumer<String, String> consumer,
68 AdminClient adminClient,
69 TransferRepository repository,
71 int stateStoreInterval,
73 ConsumerUseCases productionUseCases,
74 ConsumerUseCases restoreUseCases)
77 this.numPartitions = numPartitions;
78 this.groupId = consumer.groupMetadata().groupId();
79 this.groupInstanceId = consumer.groupMetadata().groupInstanceId().get();
80 this.instanceIdByPartition = new String[numPartitions];
81 this.instanceIdUriMapping = new HashMap<>(instanceIdUriMapping.size());
82 for (String instanceId : instanceIdUriMapping.keySet())
84 // Requests are not redirected for the instance itself
85 String uri = instanceId.equals(groupInstanceId)
87 : instanceIdUriMapping.get(instanceId);
88 this.instanceIdUriMapping.put(instanceId, uri);
90 this.consumer = consumer;
91 this.adminClient = adminClient;
92 this.repository = repository;
94 this.stateStoreInterval = stateStoreInterval;
96 this.productionUseCases = productionUseCases;
97 this.restoreUseCases = restoreUseCases;
104 Instant stateStored = clock.instant();
110 ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
111 if (records.count() == 0)
114 log.debug("polled {} records", records.count());
115 records.forEach(record -> handleRecord(record, productionUseCases));
117 Instant now = clock.instant();
119 stateStoreInterval > 0 &&
120 Duration.between(stateStored, now).getSeconds() >= stateStoreInterval)
122 Map<Integer, Long> offsets = new HashMap<>();
124 for (TopicPartition topicPartition : consumer.assignment())
126 Integer partition = topicPartition.partition();
127 Long offset = consumer.position(topicPartition);
128 log.info("storing state locally for {}/{}: {}", topic, partition, offset);
129 offsets.put(partition, offset);
132 repository.storeState(offsets);
136 catch (WakeupException e)
138 log.info("cleanly interrupted while polling");
142 log.info("polling stopped");
145 private void handleRecord(ConsumerRecord<String, String> record, ConsumerUseCases useCases)
149 byte eventType = record.headers().lastHeader(EventType.HEADER).value()[0];
153 case EventType.NEW_TRANSFER:
155 NewTransferEvent newTransferEvent =
156 mapper.readValue(record.value(), NewTransferEvent.class);
159 newTransferEvent.getId(),
160 newTransferEvent.getPayer(),
161 newTransferEvent.getPayee(),
162 newTransferEvent.getAmount());
165 case EventType.TRANSFER_STATE_CHANGED:
167 TransferStateChangedEvent stateChangedEvent =
168 mapper.readValue(record.value(), TransferStateChangedEvent.class);
169 useCases.handleStateChange(stateChangedEvent.getId(), stateChangedEvent.getState());
173 catch (JsonProcessingException e)
176 "ignoring invalid json in message #{} on {}/{}: {}",
182 catch (IllegalArgumentException e)
185 "ignoring invalid message #{} on {}/{}: {}, message={}",
196 * Identifies the URI, at which the Group-Instance can be reached,
197 * that holds the state for a specific {@link Transfer}.
199 * The {@link Transfer#getId() ID} of the {@link Transfer} is named
200 * {@code key} here and of type {@code String}, because this example
201 * project stores the key as a String in Kafka to simplify the listing
202 * and manual manipulation of the according topic.
204 * @param key A {@code String}, that represents the {@link Transfer#getId() ID} of a {@link Transfer}.
205 * @return An {@link Optional}, that holds the URI at which the Group-Instance
206 * can be reached, that holds the state for the {@link Transfer}, that
207 * is identified by the key (if present), or is empty, if the {@link Transfer}
208 * would be handled by the local instance.
210 public Optional<String> uriForKey(String key)
214 while (partitionOwnershipUnknown)
216 try { wait(); } catch (InterruptedException e) {}
219 int partition = TransferPartitioner.computeHashForKey(key, numPartitions);
222 .ofNullable(instanceIdByPartition[partition])
223 .map(id -> instanceIdUriMapping.get(id));
228 public synchronized void onApplicationEvent(ContextRefreshedEvent event)
230 // "Needed", because this method is called synchronously during the
231 // initialization pahse of Spring. If the subscription happens
232 // in the same thread, it would block the completion of the initialization.
233 // Hence, the app would not react to any signal (CTRL-C, for example) except
234 // a KILL until the restoring is finished.
235 future = CompletableFuture.runAsync(() -> start());
236 log.info("start of application completed");
241 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
243 partitionOwnershipUnknown = true;
244 log.info("partitions revoked: {}", partitions);
245 for (TopicPartition topicPartition : partitions)
247 int partition = topicPartition.partition();
248 long offset = consumer.position(topicPartition);
249 log.info("deactivating partition {}, offset: {}", partition, offset);
250 repository.deactivatePartition(partition, offset);
255 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
257 log.info("partitions assigned: {}", partitions);
258 fetchAssignmentsAsync();
259 if (partitions.size() > 0)
261 for (TopicPartition topicPartition : partitions)
263 int partition = topicPartition.partition();
264 long offset = repository.activatePartition(partition);
265 log.info("activated partition {}, seeking to offset {}", partition, offset);
266 consumer.seek(topicPartition, offset);
273 private void fetchAssignmentsAsync()
276 .describeConsumerGroups(List.of(groupId))
279 .whenComplete((descriptions, e) ->
283 log.error("could not fetch group data: {}", e.getMessage());
289 for (MemberDescription description : descriptions.members())
294 .forEach(tp -> instanceIdByPartition[tp.partition()] = description.groupInstanceId().get());
296 partitionOwnershipUnknown = false;
304 public void onPartitionsLost(Collection<TopicPartition> partitions)
306 partitionOwnershipUnknown = true;
307 log.info("partiotions lost: {}", partitions);
311 private void restore(Collection<TopicPartition> partitions)
313 log.info("--> starting restore...");
315 Map<Integer, Long> lastSeen =
317 .endOffsets(partitions)
320 .collect(Collectors.toMap(
321 entry -> entry.getKey().partition(),
322 entry -> entry.getValue() - 1));
324 Map<Integer, Long> positions =
328 .collect(Collectors.toMap(
329 partition -> partition,
330 partition -> repository.storedPosition(partition)));
336 .map(entry -> entry.getValue() < lastSeen.get(entry.getKey()))
337 .reduce(false, (a, b) -> a || b))
341 ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
342 if (records.count() == 0)
345 log.debug("polled {} records", records.count());
346 records.forEach(record ->
348 handleRecord(record, restoreUseCases);
349 positions.put(record.partition(), record.offset());
352 catch(WakeupException e)
354 log.info("--> cleanly interrupted while restoring");
358 log.info("--> restore completed!");
361 @PostMapping("start")
362 public synchronized String start()
366 log.info("consumer already running!");
367 return "Already running!";
370 int foundNumPartitions = consumer.partitionsFor(topic).size();
371 if (foundNumPartitions != numPartitions)
374 "unexpected number of partitions for topic {}: expected={}, found={}",
379 return "Wrong number of partitions for topic " + topic + ": " + foundNumPartitions;
382 consumer.subscribe(List.of(topic), this);
385 future = CompletableFuture.runAsync(this);
387 log.info("consumer started");
392 public synchronized String stop()
396 log.info("consumer not running!");
397 return "Not running";
402 if (!future.isDone())
405 log.info("waiting for the consumer...");
410 catch (InterruptedException|ExecutionException e)
412 log.error("Exception while joining polling task!", e);
413 return e.getMessage();
418 consumer.unsubscribe();
421 log.info("consumer stopped");
425 public synchronized void shutdown()
427 log.info("shutdown initiated!");
430 log.info("closing consumer");
436 public interface ConsumerUseCases
439 CreateTransferUseCase,
440 HandleStateChangeUseCase {};