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


##########
ingestion/ingestion-sink/src/main/java/org/apache/fineract/bi/ingestion/app/SinkWorker.java:
##########
@@ -0,0 +1,657 @@
+/*
+ * 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.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+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.OwnershipSnapshot;
+import org.apache.fineract.bi.ingestion.routing.OwnershipView;
+import org.apache.fineract.bi.ingestion.routing.Route;
+import org.apache.fineract.bi.ingestion.sink.BatchWriter;
+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.SkipCheck;
+import org.apache.fineract.bi.ingestion.sink.SqlFailures;
+import org.apache.fineract.bi.ingestion.sink.WarehouseWriter;
+import org.apache.kafka.clients.consumer.Consumer;
+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 SinkFatalException extends RuntimeException {
+        private static final long serialVersionUID = 1L;
+
+        SinkFatalException(String message) {
+            super(message);
+        }
+    }
+
+    record Outcome(Map<TopicPartition, OffsetAndMetadata> commit, 
Map<TopicPartition, Long> heldFrom) {
+    }
+
+    @FunctionalInterface
+    interface OffsetLoader {
+        Map<String, Long> load(Connection c, String consumerGroup, 
Collection<String> topics) throws SQLException;
+    }
+
+    private final int index;
+    private final SinkConfig config;
+    private final ConnectionSource connections;
+    private final OwnershipView ownership;
+    private final DebeziumEnvelopeParser parser;
+    private final BatchWriter writer;
+    private final DeadLetterSink deadLetters;
+    private final SinkMetrics metrics;
+    private final ProgressReporter progress;
+    private final Function<Properties, Consumer<byte[], byte[]>> 
consumerFactory;
+    private OffsetLoader offsetLoader = WarehouseWriter::loadOffsets;
+    private final AtomicBoolean running = new AtomicBoolean(true);
+    private final Random random = new Random();
+    private final List<ConsumerRecord<byte[], byte[]>> buffer = new 
ArrayList<>();
+    private final Set<TopicPartition> held = new HashSet<>();
+    private volatile boolean alive = true;
+    private volatile boolean fatal;
+    private volatile long failingSince;
+    private Consumer<byte[], byte[]> consumer;
+
+    public SinkWorker(int index, SinkConfig config, ConnectionSource 
connections, OwnershipView ownership,
+            DebeziumEnvelopeParser parser, WarehouseWriter writer, 
DeadLetterSink deadLetters,
+            SinkMetrics metrics, ProgressReporter progress) {
+        this(index, config, connections, ownership, parser, writer, 
deadLetters, metrics, progress,
+                p -> new KafkaConsumer<>(p, new ByteArrayDeserializer(), new 
ByteArrayDeserializer()));
+    }
+
+    SinkWorker(int index, SinkConfig config, ConnectionSource connections, 
OwnershipView ownership,
+            DebeziumEnvelopeParser parser, BatchWriter writer, DeadLetterSink 
deadLetters,
+            SinkMetrics metrics, ProgressReporter progress,
+            Function<Properties, Consumer<byte[], byte[]>> consumerFactory) {
+        this.index = index;
+        this.config = config;
+        this.connections = connections;
+        this.ownership = ownership;
+        this.parser = parser;
+        this.writer = writer;
+        this.deadLetters = deadLetters;
+        this.metrics = metrics;
+        this.progress = progress;
+        this.consumerFactory = consumerFactory;
+    }
+
+    public boolean isAlive() {
+        return alive && !fatal;
+    }
+
+    void enqueue(ConsumerRecord<byte[], byte[]> record) {
+        buffer.add(record);
+    }
+
+    int buffered() {
+        return buffer.size();
+    }
+
+    Set<TopicPartition> heldPartitions() {
+        return held;
+    }
+
+    void attach(Consumer<byte[], byte[]> c) {
+        this.consumer = c;
+    }
+
+    void useOffsetLoader(OffsetLoader loader) {
+        this.offsetLoader = loader;
+    }
+
+    public boolean isHealthy(long nowMillis) {
+        long since = failingSince;
+        return isAlive() && (since == 0 || nowMillis - since < 
config.healthStuckMs());
+    }
+
+    public void shutdown() {
+        running.set(false);
+        Consumer<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 (Consumer<byte[], byte[]> c = 
consumerFactory.apply(consumerProperties())) {
+            consumer = c;
+            new KafkaClientMetrics(c).bindTo(metrics.registry());
+            c.subscribe(Pattern.compile(config.topicPattern()), new 
Rebalance());
+            loop(c);
+        } catch (WakeupException e) {
+            if (running.get()) {
+                LOG.error("Unexpected wakeup", e);
+            }
+        } catch (RuntimeException e) {
+            if (isFatalCause(e)) {
+                fatal = true;
+            }
+            LOG.error("Sink worker {} crashed", index, e);
+        } finally {
+            alive = false;
+            consumer = null;
+            LOG.info("Sink worker {} stopped", index);
+        }
+    }
+
+    void loop(Consumer<byte[], byte[]> c) {
+        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.isEmpty()) {
+                    c.commitAsync(committed, (offsets, e) -> {
+                        if (e != null) {
+                            LOG.debug("Informational Kafka commit failed 
(warehouse offsets are authoritative)", e);
+                        }
+                    });
+                }
+                batchStartedAt = buffer.isEmpty() ? 0 : 
System.currentTimeMillis();
+            }
+        }
+    }
+
+    Map<TopicPartition, OffsetAndMetadata> processWithRetry(Consumer<byte[], 
byte[]> c) {
+        long backoff = 200;
+        int fencedInARow = 0;
+        boolean paused = false;
+        Map<TopicPartition, OffsetAndMetadata> commit = new HashMap<>();
+        try {
+            while (running.get() && !buffer.isEmpty()) {
+                try {
+                    List<ConsumerRecord<byte[], byte[]>> batch = new 
ArrayList<>(buffer);
+                    Outcome outcome = process(batch);
+                    settle(c, batch, outcome);
+                    mergeCommit(commit, outcome.commit());
+                    failingSince = 0;
+                    return commit;
+                } catch (FencedWriteException e) {
+                    metrics.fenced();
+                    fencedInARow++;
+                    LOG.info("Batch fenced ({}), refreshing ownership and 
re-routing", e.getMessage());
+                    refreshOwnership(true);
+                    if (fencedInARow < 5) {
+                        continue;
+                    }
+                    markFailing();
+                } catch (SQLException e) {
+                    SqlFailures.Kind kind = SqlFailures.classify(e);
+                    if (kind == SqlFailures.Kind.FATAL) {
+                        fail("Permanent warehouse error, stopping this worker: 
" + e.getMessage(), e);
+                        return commit;
+                    }
+                    if (kind == SqlFailures.Kind.DATA) {
+                        LOG.warn("Batch rejected by the warehouse ({}), 
isolating the offending record", e.getMessage());
+                        try {
+                            mergeCommit(commit, isolate(c, new 
ArrayList<>(buffer)));

Review Comment:
   Fixed. isolate() catches FencedWriteException, refreshes ownership and 
retries the current part with the new snapshot. After 5 fences in a row it 
gives up and the outer loop backs off; the worker stays alive. There's a unit 
test that fences mid-isolation.



-- 
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