congbobo184 commented on code in PR #17847:
URL: https://github.com/apache/pulsar/pull/17847#discussion_r1006532810


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/impl/TopicTransactionBuffer.java:
##########
@@ -646,82 +560,57 @@ public void run() {
                             this, topic.getName());
                     return;
                 }
-                
topic.getBrokerService().getPulsar().getTransactionBufferSnapshotServiceFactory()
-                        
.getTxnBufferSnapshotService().createReader(TopicName.get(topic.getName()))
-                        .thenAcceptAsync(reader -> {
-                            try {
-                                boolean hasSnapshot = false;
-                                while (reader.hasMoreEvents()) {
-                                    Message<TransactionBufferSnapshot> message 
= reader.readNext();
-                                    if 
(topic.getName().equals(message.getKey())) {
-                                        TransactionBufferSnapshot 
transactionBufferSnapshot = message.getValue();
-                                        if (transactionBufferSnapshot != null) 
{
-                                            hasSnapshot = true;
-                                            
callBack.handleSnapshot(transactionBufferSnapshot);
-                                            this.startReadCursorPosition = 
PositionImpl.get(
-                                                    
transactionBufferSnapshot.getMaxReadPositionLedgerId(),
-                                                    
transactionBufferSnapshot.getMaxReadPositionEntryId());
-                                        }
-                                    }
-                                }
-                                if (!hasSnapshot) {
-                                    closeReader(reader);
-                                    callBack.noNeedToRecover();
-                                    return;
+                
abortedTxnProcessor.recoverFromSnapshot(callBack).thenAcceptAsync(startReadCursorPosition
 -> {
+                    //Transaction is not enable for this topic, so just make 
maxReadPosition as LAC.
+                    if (startReadCursorPosition == null) {
+                        return;
+                    } else {
+                        this.startReadCursorPosition = startReadCursorPosition;
+                    }

Review Comment:
   startReadCursorPosition = null, we don't need to recover by the orignal topic
   ```suggestion
                       if (startReadCursorPosition == null) {
                           callBack.noNeedToRecover();
                           return;
                       } else {
                           this.startReadCursorPosition = 
startReadCursorPosition;
                       }
   ```
   callBack don't become the parameter for the mthod `recoverFromSnapshot `



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/impl/TopicTransactionBuffer.java:
##########
@@ -197,7 +173,8 @@ public void handleTxnEntry(Entry entry) {
                             PositionImpl position = 
PositionImpl.get(entry.getLedgerId(), entry.getEntryId());
                             if (Markers.isTxnMarker(msgMetadata)) {
                                 if (Markers.isTxnAbortMarker(msgMetadata)) {
-                                    aborts.put(txnID, position);
+                                    
snapshotAbortedTxnProcessor.appendAbortedTxn(
+                                            new 
TxnIDData(txnID.getMostSigBits(), txnID.getLeastSigBits()), position);

Review Comment:
   ```suggestion
                                       
snapshotAbortedTxnProcessor.appendAbortedTxn(txnId, position);
   ```
   TxnIDData only take snapshot need to cover



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/impl/TopicTransactionBuffer.java:
##########
@@ -225,7 +202,8 @@ public void recoverExceptionally(Throwable e) {
                         
recoverTime.setRecoverEndTime(System.currentTimeMillis());
                         topic.close(true);
                     }
-                }, this.topic, this, takeSnapshotWriter));
+                }, this.topic,
+                        this, takeSnapshotWriter, 
snapshotAbortedTxnProcessor));

Review Comment:
   ```suggestion
                   }, this.topic, this, takeSnapshotWriter, 
snapshotAbortedTxnProcessor));
   ```
   the takeSnapshotWriter can become a variable in snapshotAbortedTxnProcessor



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/impl/SingleSnapshotAbortedTxnProcessorImpl.java:
##########
@@ -0,0 +1,250 @@
+/**
+ * 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.pulsar.broker.transaction.buffer.impl;
+
+import io.netty.util.Timeout;
+import io.netty.util.Timer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl;
+import org.apache.bookkeeper.mledger.impl.PositionImpl;
+import org.apache.commons.collections4.map.LinkedMap;
+import org.apache.pulsar.broker.service.persistent.PersistentTopic;
+import org.apache.pulsar.broker.systopic.SystemTopicClient;
+import org.apache.pulsar.broker.transaction.buffer.AbortedTxnProcessor;
+import org.apache.pulsar.broker.transaction.buffer.metadata.AbortTxnMetadata;
+import 
org.apache.pulsar.broker.transaction.buffer.metadata.TransactionBufferSnapshot;
+import org.apache.pulsar.broker.transaction.buffer.metadata.v2.TxnIDData;
+import org.apache.pulsar.client.api.Message;
+import org.apache.pulsar.common.naming.TopicName;
+
+@Slf4j
+public class SingleSnapshotAbortedTxnProcessorImpl implements 
AbortedTxnProcessor {
+    private final PersistentTopic topic;
+    private final 
CompletableFuture<SystemTopicClient.Writer<TransactionBufferSnapshot>> 
takeSnapshotWriter;
+    private volatile PositionImpl maxReadPosition;
+
+    private final Timer timer;
+
+    /**
+     * Aborts, map for jude message is aborted, linked for remove abort txn in 
memory when this
+     * position have been deleted.
+     */
+    private final LinkedMap<TxnIDData, PositionImpl> aborts = new 
LinkedMap<>();
+
+    private volatile long lastSnapshotTimestamps;
+    private final int takeSnapshotIntervalNumber;
+
+    private final int takeSnapshotIntervalTime;
+
+
+    // when add abort or change max read position, the count will +1. Take 
snapshot will set 0 into it.
+    private final AtomicLong changeMaxReadPositionAndAddAbortTimes = new 
AtomicLong();
+
+
+    public SingleSnapshotAbortedTxnProcessorImpl(PersistentTopic topic) {
+        this.topic = topic;
+        this.maxReadPosition = (PositionImpl) 
topic.getManagedLedger().getLastConfirmedEntry();
+        this.takeSnapshotWriter = this.topic.getBrokerService().getPulsar()
+                .getTransactionBufferSnapshotServiceFactory()
+                
.getTxnBufferSnapshotService().createWriter(TopicName.get(topic.getName()));
+        this.timer = 
topic.getBrokerService().getPulsar().getTransactionTimer();
+        this.takeSnapshotIntervalNumber = topic.getBrokerService().getPulsar()
+                
.getConfiguration().getTransactionBufferSnapshotMaxTransactionCount();
+        this.takeSnapshotIntervalTime = topic.getBrokerService().getPulsar()
+                
.getConfiguration().getTransactionBufferSnapshotMinTimeInMillis();
+        this.maxReadPosition = (PositionImpl) 
topic.getManagedLedger().getLastConfirmedEntry();
+    }
+
+    @Override
+    public void appendAbortedTxn(TxnIDData abortedTxnId, PositionImpl 
position) {
+        aborts.put(abortedTxnId, position);
+    }
+
+    @Override
+    public void updateMaxReadPosition(Position maxReadPosition) {
+        if (this.maxReadPosition != maxReadPosition) {
+            this.maxReadPosition = (PositionImpl) maxReadPosition;
+            takeSnapshotByChangeTimes();
+        }
+    }
+
+    @Override
+    public void updateMaxReadPositionNotIncreaseChangeTimes(Position 
maxReadPosition) {
+        this.maxReadPosition = (PositionImpl) maxReadPosition;
+    }
+
+    @Override
+    public void trimExpiredTxnIDDataOrSnapshotSegments() {
+        while (!aborts.isEmpty() && !((ManagedLedgerImpl) 
topic.getManagedLedger())
+                .ledgerExists(aborts.get(aborts.firstKey()).getLedgerId())) {
+            if (log.isDebugEnabled()) {
+                aborts.firstKey();
+                log.debug("[{}] Topic transaction buffer clear aborted 
transaction, TxnId : {}, Position : {}",
+                        topic.getName(), aborts.firstKey(), 
aborts.get(aborts.firstKey()));
+            }
+            aborts.remove(aborts.firstKey());
+        }
+    }
+
+    @Override
+    public boolean checkAbortedTransaction(TxnIDData txnID, Position 
readPosition) {
+        return aborts.containsKey(txnID);
+    }
+
+
+    @Override
+    public CompletableFuture<PositionImpl> 
recoverFromSnapshot(TopicTransactionBufferRecoverCallBack callBack) {
+        return 
topic.getBrokerService().getPulsar().getTransactionBufferSnapshotServiceFactory()
+                .getTxnBufferSnapshotService()
+                
.createReader(TopicName.get(topic.getName())).thenComposeAsync(reader -> {
+                    PositionImpl startReadCursorPosition = null;
+                    try {
+                        boolean hasSnapshot = false;
+                        while (reader.hasMoreEvents()) {
+                            Message<TransactionBufferSnapshot> message = 
reader.readNext();
+                            if (topic.getName().equals(message.getKey())) {
+                                TransactionBufferSnapshot 
transactionBufferSnapshot = message.getValue();
+                                if (transactionBufferSnapshot != null) {
+                                    hasSnapshot = true;
+                                    handleSnapshot(transactionBufferSnapshot);
+                                    startReadCursorPosition = PositionImpl.get(
+                                            
transactionBufferSnapshot.getMaxReadPositionLedgerId(),
+                                            
transactionBufferSnapshot.getMaxReadPositionEntryId());
+                                }
+                            }
+                        }
+                        closeReader(reader);
+                        if (!hasSnapshot) {
+                            callBack.noNeedToRecover();
+                            return CompletableFuture.completedFuture(null);
+                        }
+                        return 
CompletableFuture.completedFuture(startReadCursorPosition);
+                    } catch (Exception ex) {
+                        log.error("[{}] Transaction buffer recover fail when 
read "
+                                + "transactionBufferSnapshot!", 
topic.getName(), ex);
+                        callBack.recoverExceptionally(ex);
+                        closeReader(reader);

Review Comment:
   future isn't completely



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/impl/TopicTransactionBuffer.java:
##########
@@ -646,82 +560,57 @@ public void run() {
                             this, topic.getName());
                     return;
                 }
-                
topic.getBrokerService().getPulsar().getTransactionBufferSnapshotServiceFactory()
-                        
.getTxnBufferSnapshotService().createReader(TopicName.get(topic.getName()))
-                        .thenAcceptAsync(reader -> {
-                            try {
-                                boolean hasSnapshot = false;
-                                while (reader.hasMoreEvents()) {
-                                    Message<TransactionBufferSnapshot> message 
= reader.readNext();
-                                    if 
(topic.getName().equals(message.getKey())) {
-                                        TransactionBufferSnapshot 
transactionBufferSnapshot = message.getValue();
-                                        if (transactionBufferSnapshot != null) 
{
-                                            hasSnapshot = true;
-                                            
callBack.handleSnapshot(transactionBufferSnapshot);
-                                            this.startReadCursorPosition = 
PositionImpl.get(
-                                                    
transactionBufferSnapshot.getMaxReadPositionLedgerId(),
-                                                    
transactionBufferSnapshot.getMaxReadPositionEntryId());
-                                        }
-                                    }
-                                }
-                                if (!hasSnapshot) {
-                                    closeReader(reader);
-                                    callBack.noNeedToRecover();
-                                    return;
+                
abortedTxnProcessor.recoverFromSnapshot(callBack).thenAcceptAsync(startReadCursorPosition
 -> {
+                    //Transaction is not enable for this topic, so just make 
maxReadPosition as LAC.
+                    if (startReadCursorPosition == null) {
+                        return;
+                    } else {
+                        this.startReadCursorPosition = startReadCursorPosition;
+                    }
+                    ManagedCursor managedCursor;
+                    try {
+                        managedCursor = topic.getManagedLedger()
+                                
.newNonDurableCursor(this.startReadCursorPosition, SUBSCRIPTION_NAME);
+                    } catch (ManagedLedgerException e) {
+                        callBack.recoverExceptionally(e);
+                        log.error("[{}]Transaction buffer recover fail when 
open cursor!", topic.getName(), e);
+                        return;
+                    }
+                    PositionImpl lastConfirmedEntry =
+                            (PositionImpl) 
topic.getManagedLedger().getLastConfirmedEntry();
+                    PositionImpl currentLoadPosition = (PositionImpl) 
this.startReadCursorPosition;
+                    FillEntryQueueCallback fillEntryQueueCallback = new 
FillEntryQueueCallback(entryQueue,
+                            managedCursor, TopicTransactionBufferRecover.this);
+                    if (lastConfirmedEntry.getEntryId() != -1) {
+                        while 
(lastConfirmedEntry.compareTo(currentLoadPosition) > 0
+                                && fillEntryQueueCallback.fillQueue()) {
+                            Entry entry = entryQueue.poll();
+                            if (entry != null) {
+                                try {
+                                    currentLoadPosition = 
PositionImpl.get(entry.getLedgerId(),
+                                            entry.getEntryId());
+                                    callBack.handleTxnEntry(entry);
+                                } finally {
+                                    entry.release();
                                 }
-                            } catch (Exception ex) {
-                                log.error("[{}] Transaction buffer recover 
fail when read "
-                                        + "transactionBufferSnapshot!", 
topic.getName(), ex);
-                                callBack.recoverExceptionally(ex);
-                                closeReader(reader);
-                                return;
-                            }
-                            closeReader(reader);
-
-                            ManagedCursor managedCursor;
-                            try {
-                                managedCursor = topic.getManagedLedger()
-                                        
.newNonDurableCursor(this.startReadCursorPosition, SUBSCRIPTION_NAME);
-                            } catch (ManagedLedgerException e) {
-                                callBack.recoverExceptionally(e);
-                                log.error("[{}]Transaction buffer recover fail 
when open cursor!", topic.getName(), e);
-                                return;
-                            }
-                            PositionImpl lastConfirmedEntry =
-                                    (PositionImpl) 
topic.getManagedLedger().getLastConfirmedEntry();
-                            PositionImpl currentLoadPosition = (PositionImpl) 
this.startReadCursorPosition;
-                            FillEntryQueueCallback fillEntryQueueCallback = 
new FillEntryQueueCallback(entryQueue,
-                                    managedCursor, 
TopicTransactionBufferRecover.this);
-                            if (lastConfirmedEntry.getEntryId() != -1) {
-                                while 
(lastConfirmedEntry.compareTo(currentLoadPosition) > 0
-                                        && fillEntryQueueCallback.fillQueue()) 
{
-                                    Entry entry = entryQueue.poll();
-                                    if (entry != null) {
-                                        try {
-                                            currentLoadPosition = 
PositionImpl.get(entry.getLedgerId(),
-                                                    entry.getEntryId());
-                                            callBack.handleTxnEntry(entry);
-                                        } finally {
-                                            entry.release();
-                                        }
-                                    } else {
-                                        try {
-                                            Thread.sleep(1);
-                                        } catch (InterruptedException e) {
-                                            //no-op
-                                        }
-                                    }
+                            } else {
+                                try {
+                                    Thread.sleep(1);
+                                } catch (InterruptedException e) {
+                                    //no-op
                                 }
                             }
+                        }
+                    }
 
-                            closeCursor(SUBSCRIPTION_NAME);
-                            callBack.recoverComplete();
-                        }, 
topic.getBrokerService().getPulsar().getTransactionExecutorProvider()
-                                .getExecutor(this)).exceptionally(e -> {
-                            callBack.recoverExceptionally(e.getCause());
-                            log.error("[{}]Transaction buffer new snapshot 
reader fail!", topic.getName(), e);
-                            return null;
-                        });
+                    closeCursor(SUBSCRIPTION_NAME);
+                    callBack.recoverComplete();
+                }, 
topic.getBrokerService().getPulsar().getTransactionExecutorProvider()
+                        .getExecutor(this)).exceptionally(e -> {
+                    callBack.recoverExceptionally(e.getCause());
+                    log.error("[{}]Transaction buffer new snapshot reader 
fail!", topic.getName(), e);

Review Comment:
   change this log detail



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/buffer/AbortedTxnProcessor.java:
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pulsar.broker.transaction.buffer;
+
+import io.netty.util.TimerTask;
+import java.util.concurrent.CompletableFuture;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.impl.PositionImpl;
+import 
org.apache.pulsar.broker.transaction.buffer.impl.TopicTransactionBufferRecoverCallBack;
+import org.apache.pulsar.broker.transaction.buffer.metadata.v2.TxnIDData;
+
+
+public interface AbortedTxnProcessor extends TimerTask {
+
+    /**
+     * After the transaction buffer writes a transaction aborted mark to the 
topic,
+     * the transaction buffer will add the aborted transaction ID to 
AbortedTxnProcessor.
+     * @param txnID aborted transaction ID.
+     */
+    void appendAbortedTxn(TxnIDData txnID, PositionImpl position);
+
+    /**
+     * After the transaction buffer writes a transaction aborted mark to the 
topic,
+     * the transaction buffer will update max read position in 
AbortedTxnProcessor
+     * @param maxReadPosition  the max read position after the transaction is 
aborted.
+     */
+    void updateMaxReadPosition(Position maxReadPosition);
+
+    /**
+     * This method is used to updated max read position for the topic which 
nerver used transaction send message.
+     * @param maxReadPosition the max read position after the transaction is 
aborted.
+     */
+    void updateMaxReadPositionNotIncreaseChangeTimes(Position maxReadPosition);
+
+    /**
+     * Pulsar has a configuration for ledger retention time.
+     * If the transaction aborted mark position has been deleted, the 
transaction is valid and can be clear.
+     * In the old implementation we clear the invalid aborted txn ID one by 
one.
+     * In the new implementation, we adopt snapshot segments. And then we 
clear invalid segment by its max read position.
+     */
+    void trimExpiredTxnIDDataOrSnapshotSegments();

Review Comment:
   ```suggestion
       void trimExpiredAbortedTxns();
   ```



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