Sent messages are deleted individually after a crash
[demos/kafka/outbox] / delivery / src / main / java / de / juplo / kafka / outbox / delivery / OutboxProducer.java
1 package de.juplo.kafka.outbox.delivery;
2
3 import com.google.common.primitives.Longs;
4 import org.apache.kafka.clients.consumer.ConsumerRecords;
5 import org.apache.kafka.clients.consumer.KafkaConsumer;
6 import org.apache.kafka.clients.consumer.OffsetAndMetadata;
7 import org.apache.kafka.common.PartitionInfo;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.serialization.StringDeserializer;
10 import org.apache.kafka.common.serialization.StringSerializer;
11
12 import java.time.Clock;
13 import java.time.Duration;
14 import java.time.LocalTime;
15 import java.util.*;
16
17 import org.apache.kafka.clients.producer.KafkaProducer;
18 import org.apache.kafka.clients.producer.ProducerRecord;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21 import org.springframework.scheduling.annotation.Scheduled;
22
23 import javax.annotation.PreDestroy;
24
25 import static org.apache.kafka.clients.CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG;
26 import static org.apache.kafka.clients.consumer.ConsumerConfig.*;
27 import static org.apache.kafka.clients.producer.ProducerConfig.*;
28
29
30 public class OutboxProducer
31 {
32   final static Logger LOG = LoggerFactory.getLogger(OutboxProducer.class);
33
34   public final static String HEADER = "#";
35
36   private final OutboxRepository repository;
37   private final KafkaProducer<String, String> producer;
38   private final String topic;
39   private final Set<Long> send = new HashSet<>();
40   private final Clock clock;
41   private final Duration cleanupInterval;
42
43   private long sequenceNumber = 0l;
44   private LocalTime nextCleanup;
45
46   public OutboxProducer(
47       ApplicationProperties properties,
48       OutboxRepository repository,
49       Clock clock)
50   {
51     this.repository = repository;
52
53     Properties props = new Properties();
54     props.put(BOOTSTRAP_SERVERS_CONFIG, properties.bootstrapServers);
55     props.put(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
56     props.put(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
57     props.put(ENABLE_IDEMPOTENCE_CONFIG, true);
58
59     this.producer = new KafkaProducer<>(props);
60     this.topic = properties.topic;
61
62     props = new Properties();
63     props.put(BOOTSTRAP_SERVERS_CONFIG, properties.bootstrapServers);
64     props.put(GROUP_ID_CONFIG, "outbox");
65     props.put(KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
66     props.put(VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
67
68     List<PartitionInfo> partitions = consumer.listTopics().get(this.topic);
69     Set<TopicPartition> assignment = new HashSet<>();
70     for (PartitionInfo info : partitions)
71     {
72       LOG.debug("Found {}/{} (ISR: {})", info.topic(), info.partition(), info.inSyncReplicas());
73       assignment.add(new TopicPartition(info.topic(), info.partition()));
74     }
75
76     LOG.info("Using topic {} with {} partitions", topic, partitions);
77
78     KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
79     consumer.assign(assignment);
80
81     long[] currentOffsets = new long[partitions.size()];
82     for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : consumer.committed(assignment).entrySet())
83     {
84       LOG.info("Found current offset {} for partition {}", entry.getValue(), entry.getKey());
85       currentOffsets[entry.getKey().partition()] = entry.getValue().offset() - 1l;
86     }
87     LOG.info("Current offsets: {}", currentOffsets);
88
89     long[] endOffsets = new long[partitions.size()];
90     for (Map.Entry<TopicPartition, Long> entry : consumer.endOffsets(assignment).entrySet())
91     {
92       LOG.info("Found next offset {} for partition {}", entry.getValue(), entry.getKey());
93       endOffsets[entry.getKey().partition()] = entry.getValue() - 1l;
94     }
95     LOG.info("End-offsets: {}", endOffsets);
96
97     int deleted = 0;
98     while(!Arrays.equals(currentOffsets, endOffsets))
99     {
100       ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
101       LOG.debug("Fetched {} records", records.count());
102       records.forEach(record ->
103       {
104         long recordSequenceNumber = Longs.fromByteArray(record.headers().lastHeader(HEADER).value());
105         LOG.debug(
106             "Found message #{} on offset {} of partition {}",
107             recordSequenceNumber,
108             record.offset(),
109             record.partition());
110         send.add(recordSequenceNumber);
111         currentOffsets[record.partition()] = record.offset();
112       });
113       deleted += cleanUp();
114       LOG.debug("Current offsets: {}", currentOffsets);
115     }
116
117     LOG.info("Cleaned up {} already send entries from outbox table", deleted);
118
119     consumer.close();
120
121     this.clock = clock;
122     this.cleanupInterval = properties.cleanupInterval;
123     this.nextCleanup = LocalTime.now(clock).plus(this.cleanupInterval);
124   }
125
126   @Scheduled(fixedDelayString = "${de.juplo.kafka.outbox.interval}")
127   public void poll()
128   {
129     List<OutboxItem> items;
130     do
131     {
132       items = repository.fetch(sequenceNumber);
133       LOG.debug("Polled {} new items", items.size());
134       for (OutboxItem item : items)
135         send(item);
136       if (nextCleanup.isBefore(LocalTime.now(clock)))
137       {
138         cleanUp();
139         nextCleanup = LocalTime.now(clock).plus(cleanupInterval);
140         LOG.debug("Next clean-up: {}", nextCleanup);
141       }
142     }
143     while (items.size() > 0);
144   }
145
146   int cleanUp()
147   {
148     int deleted = repository.delete(send);
149     LOG.debug("Cleaned up {}/{} entries from outbox, next clean-up: {}", deleted, send.size());
150     send.clear();
151     return deleted;
152   }
153
154   void send(OutboxItem item)
155   {
156     final ProducerRecord<String, String> record =
157         new ProducerRecord<>(topic, item.getKey(), item.getValue());
158
159     sequenceNumber = item.getSequenceNumber();
160     record.headers().add(HEADER, Longs.toByteArray(sequenceNumber));
161
162     producer.send(record, (metadata, e) ->
163     {
164       if (metadata != null)
165       {
166         send.add(item.getSequenceNumber());
167         LOG.info(
168             "{}/{}:{} - {}:{}={}",
169             metadata.topic(),
170             metadata.partition(),
171             metadata.offset(),
172             item.getSequenceNumber(),
173             record.key(),
174             record.value());
175       }
176       else
177       {
178         // HANDLE ERROR
179         LOG.error(
180             "{}/{} - {}:{}={} -> ",
181             record.topic(),
182             record.partition(),
183             item.getSequenceNumber(),
184             record.key(),
185             record.value(),
186             e);
187       }
188     });
189   }
190
191
192   @PreDestroy
193   public void close()
194   {
195     producer.close(Duration.ofSeconds(5));
196   }
197 }