airajena commented on code in PR #102:
URL: 
https://github.com/apache/fineract-business-intelligence/pull/102#discussion_r4318449215


##########
ingestion/ingestion-sink/src/main/java/org/apache/fineract/bi/ingestion/app/SinkWorker.java:
##########
@@ -0,0 +1,404 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.bi.ingestion.app;
+
+import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.regex.Pattern;
+import javax.sql.DataSource;
+import org.apache.fineract.bi.ingestion.cdc.ChangeEvent;
+import org.apache.fineract.bi.ingestion.cdc.DebeziumEnvelopeParser;
+import org.apache.fineract.bi.ingestion.cdc.PoisonEventException;
+import org.apache.fineract.bi.ingestion.routing.OwnershipCache;
+import org.apache.fineract.bi.ingestion.routing.OwnershipSnapshot;
+import org.apache.fineract.bi.ingestion.routing.Route;
+import org.apache.fineract.bi.ingestion.sink.FencedWriteException;
+import org.apache.fineract.bi.ingestion.sink.PartitionOffset;
+import org.apache.fineract.bi.ingestion.sink.RoutedEvent;
+import org.apache.fineract.bi.ingestion.sink.WarehouseWriter;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class SinkWorker implements Runnable {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SinkWorker.class);
+
+    static final class HoldException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        HoldException(String message) {
+            super(message);
+        }
+    }
+
+    private final int index;
+    private final SinkConfig config;
+    private final DataSource dataSource;
+    private final OwnershipCache ownership;
+    private final DebeziumEnvelopeParser parser;
+    private final WarehouseWriter writer;
+    private final DeadLetterPublisher deadLetters;
+    private final SinkMetrics metrics;
+    private final ProgressReporter progress;
+    private final AtomicBoolean running = new AtomicBoolean(true);
+    private final List<ConsumerRecord<byte[], byte[]>> buffer = new 
ArrayList<>();
+    private volatile boolean alive = true;
+    private KafkaConsumer<byte[], byte[]> consumer;
+
+    public SinkWorker(int index, SinkConfig config, DataSource dataSource, 
OwnershipCache ownership,
+            DebeziumEnvelopeParser parser, WarehouseWriter writer, 
DeadLetterPublisher deadLetters,
+            SinkMetrics metrics, ProgressReporter progress) {
+        this.index = index;
+        this.config = config;
+        this.dataSource = dataSource;
+        this.ownership = ownership;
+        this.parser = parser;
+        this.writer = writer;
+        this.deadLetters = deadLetters;
+        this.metrics = metrics;
+        this.progress = progress;
+    }
+
+    public boolean isAlive() {
+        return alive;
+    }
+
+    public void shutdown() {
+        running.set(false);
+        KafkaConsumer<byte[], byte[]> c = consumer;
+        if (c != null) {
+            c.wakeup();
+        }
+    }
+
+    Properties consumerProperties() {
+        Properties p = new Properties();
+        p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, 
config.bootstrapServers());
+        p.put(ConsumerConfig.GROUP_ID_CONFIG, config.groupId());
+        p.put(ConsumerConfig.CLIENT_ID_CONFIG, config.writerId() + "-" + 
index);
+        p.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+        p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+        p.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 
Integer.toString(config.maxPollRecords()));
+        p.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 
Integer.toString(config.fetchMinBytes()));
+        p.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 
Integer.toString(config.fetchMaxWaitMs()));
+        p.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 
Integer.toString(config.maxPollIntervalMs()));
+        p.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
+                "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
+        p.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
+        p.putAll(config.consumerOverrides());
+        return p;
+    }
+
+    @Override
+    public void run() {
+        Thread.currentThread().setName("sink-worker-" + index);
+        try (KafkaConsumer<byte[], byte[]> c =
+                new KafkaConsumer<>(consumerProperties(), new 
ByteArrayDeserializer(), new ByteArrayDeserializer())) {
+            consumer = c;
+            KafkaClientMetrics clientMetrics = new KafkaClientMetrics(c);
+            clientMetrics.bindTo(metrics.registry());
+            c.subscribe(Pattern.compile(config.topicPattern()), new 
Rebalance());
+            long batchStartedAt = 0;
+            while (running.get()) {
+                ConsumerRecords<byte[], byte[]> records = 
c.poll(Duration.ofMillis(config.pollTimeoutMs()));
+                for (ConsumerRecord<byte[], byte[]> r : records) {
+                    buffer.add(r);
+                }
+                long now = System.currentTimeMillis();
+                if (!buffer.isEmpty() && batchStartedAt == 0) {
+                    batchStartedAt = now;
+                }
+                boolean full = buffer.size() >= config.maxBatchEvents();
+                boolean lingered = !buffer.isEmpty() && now - batchStartedAt 
>= config.maxBatchWaitMs();
+                if (full || lingered) {
+                    Map<TopicPartition, OffsetAndMetadata> committed = 
processWithRetry(c);
+                    if (committed != null && !committed.isEmpty()) {
+                        c.commitAsync(committed, (offsets, e) -> {
+                            if (e != null) {
+                                LOG.debug("Informational Kafka commit failed 
(warehouse offsets are authoritative)", e);
+                            }
+                        });
+                    }
+                    batchStartedAt = 0;
+                }
+            }
+        } catch (WakeupException e) {
+            if (running.get()) {
+                LOG.error("Unexpected wakeup", e);
+            }
+        } catch (RuntimeException e) {
+            LOG.error("Sink worker {} crashed", index, e);
+        } finally {
+            alive = false;
+            consumer = null;
+            LOG.info("Sink worker {} stopped", index);
+        }
+    }
+
+    private Map<TopicPartition, OffsetAndMetadata> 
processWithRetry(KafkaConsumer<byte[], byte[]> c) {
+        long backoff = 200;
+        int fencedInARow = 0;
+        boolean paused = false;
+        try {
+            while (running.get() && !buffer.isEmpty()) {
+                try {
+                    Map<TopicPartition, OffsetAndMetadata> result = 
process(new ArrayList<>(buffer));
+                    buffer.clear();
+                    return result;
+                } catch (FencedWriteException e) {
+                    metrics.fenced();
+                    fencedInARow++;
+                    LOG.info("Batch fenced ({}), refreshing ownership and 
re-routing", e.getMessage());
+                    refreshOwnership(true);
+                    if (fencedInARow < 5) {
+                        continue;
+                    }
+                } catch (HoldException e) {
+                    metrics.hold();
+                    LOG.warn("Holding batch: {}", e.getMessage());
+                    refreshOwnership(false);
+                } catch (SQLException | KafkaException | 
java.util.concurrent.ExecutionException e) {

Review Comment:
   Fixed. Errors are classified by SQLSTATE. Permanent ones (data, constraint, 
missing contract table) trigger poison-row bisection, so the bad row goes to 
the dead-letter topic and the rest of the batch is applied. Oversized 
dead-letter values are recorded with metadata only. /health now fails when 
batches have been failing for longer than a configurable time.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to