You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/10/23 10:08:31 UTC
(pulsar) branch branch-5.0 updated (e45345f9b95e -> 71b758c4fca2)
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a change to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
from e45345f9b95e Bump version to 5.0.2-SNAPSHOT
new 454361b0e1ad [improve][conf] Document managedLedgerForceRecovery and schemaLedgerForceRecovery in broker.conf and standalone.conf (#24672)
new 2a3665e24872 [fix][client] Client interceptors close method not called after producer/consumer/reader close (#23830)
new 302edbafffa5 [fix][broker] Don't allow creating a non-persistent partitioned topic with '-partition-' in name (#23488)
new 7f5e884d4eef [fix][proxy] Answer failed partition metadata and lookup requests with their own response type (#26607)
new 80f000b03aa4 [fix][ml] Move the read position atomically when a replay is at it (#22803)
new 8db7583d0c7d [fix][broker] Don't count unread fixed-delay entries in msgBacklogNoDelayed (#23353)
new dfbf329a0167 [fix][broker] Don't redeliver individually acknowledged messages from the compacted ledger (#23495)
new 8c88cd2f1e84 [fix][broker] Reply to failed GetLastMessageId with the original request id (#27053)
new ab530fa967bc [fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)
new 1a314116cd8d [fix][txn] Fix reuse of recycled pooled objects in transaction code paths (#27057)
new 4ae80f3534d0 [fix][broker] Serialize outgoing commands before passing them to broker interceptors (#27054)
new f1514ba74509 [fix][broker] Fix 'rewinded' typos in PersistentDispatcherSingleActiveConsumer logs (#22021)
new 93ef7f43ebd7 [fix][fn] Send Go function logs to the log topic periodically and on shutdown (#22516)
new 07670237ee56 [fix][txn] Fix PendingAckHandleImpl potential thread safety issue (#22166)
new a0f1d2c292c6 [improve][conf] Add BookKeeper DirectIO entry logger settings to bookkeeper.conf (#20929)
new b701db6686ee [fix][client] Queue acks without grouping while the consumer is reconnecting (#21928)
new d8f3da9d71ed [fix][broker] Don't swap the local metadata store's synchronizer when configurationMetadataSyncEventTopic is updated on a shared store (#22695)
new d3bd6b6fa44e [fix][ml] Don't trim ledgers while cursors are lazily recovering (#20814)
new 09487c394cbb [fix][broker] Reject namespace-level partitioned topic creation on a remote partition conflict (#22577)
new 6f26ad38abc7 [fix][client] Read the OAuth2 private key without requiring a content type (#20824)
new ce0969cf16ca [fix][client] Close the producer when its encryption key cannot be loaded (#27024)
new 5ce6346b1c0f [improve][broker] Index topic watcher notifications by namespace (#26969)
new 71b758c4fca2 [fix][proxy] Copy GetTopicsOfNamespace properties before the broker connection completes (#27055)
The 23 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
conf/bookkeeper.conf | 23 +
conf/broker.conf | 11 +
conf/standalone.conf | 11 +
.../bookkeeper/mledger/impl/ManagedCursorImpl.java | 18 +-
.../bookkeeper/mledger/impl/ManagedLedgerImpl.java | 113 ++--
.../bookkeeper/mledger/impl/ManagedCursorTest.java | 57 ++
.../bookkeeper/mledger/impl/ManagedLedgerTest.java | 208 +++++++
.../TopicResourcesNotificationBenchmark.java | 147 +++++
.../pulsar/broker/resources/package-info.java | 3 +-
.../pulsar/broker/resources/TopicResources.java | 107 +++-
.../broker/resources/TopicResourcesTest.java | 394 +++++++++++++
.../org/apache/pulsar/broker/PulsarService.java | 17 +
.../apache/pulsar/broker/admin/AdminResource.java | 92 ++-
.../pulsar/broker/admin/impl/BrokersBase.java | 6 +
.../broker/admin/v2/NonPersistentTopics.java | 4 +-
.../broker/service/PulsarCommandSenderImpl.java | 71 +--
.../apache/pulsar/broker/service/ServerCnx.java | 8 +-
...tractPersistentDispatcherMultipleConsumers.java | 6 +
.../PersistentDispatcherMultipleConsumers.java | 10 +
.../PersistentDispatcherSingleActiveConsumer.java | 6 +-
.../service/persistent/PersistentSubscription.java | 6 +
.../broker/service/persistent/PersistentTopic.java | 39 +-
.../stats/prometheus/NamespaceStatsAggregator.java | 2 +-
.../pendingack/impl/PendingAckHandleImpl.java | 59 +-
.../pulsar/compaction/CompactedTopicUtils.java | 24 +-
.../pulsar/broker/admin/PersistentTopicsTest.java | 17 +
.../pulsar/broker/admin/TopicPoliciesTest.java | 3 +-
.../broker/service/OneWayReplicatorTest.java | 20 +
...OneWayReplicatorUsingGlobalPartitionedTest.java | 6 +
.../service/OneWayReplicatorUsingGlobalZKTest.java | 5 +
.../pulsar/broker/service/PersistentTopicTest.java | 29 +
.../service/PulsarCommandSenderImplTest.java | 110 ++++
.../pulsar/broker/service/ServerCnxTest.java | 32 +
.../SyncConfigStoreSharedWithLocalTest.java | 89 +++
.../DelayedDeliveryFixedDelayStatsTest.java | 119 ++++
.../impl/PendingAckHandleImplThreadingTest.java | 167 ++++++
.../apache/pulsar/client/api/InterceptorsTest.java | 88 +++
.../apache/pulsar/client/impl/ConsumerAckTest.java | 47 ++
.../impl/ProducerEncryptionKeyFailureTest.java | 83 +++
.../pulsar/compaction/CompactedTopicUtilsTest.java | 43 ++
.../apache/pulsar/compaction/CompactionTest.java | 56 ++
.../pulsar/client/api/ConsumerInterceptor.java | 3 +
.../pulsar/client/api/ProducerInterceptor.java | 3 +
.../pulsar/client/api/ReaderInterceptor.java | 3 +
.../api/interceptor/ProducerInterceptor.java | 3 +
.../apache/pulsar/client/impl/ConsumerBase.java | 10 +
.../apache/pulsar/client/impl/ConsumerImpl.java | 8 +-
.../pulsar/client/impl/ConsumerInterceptors.java | 3 +-
.../client/impl/MultiTopicsConsumerImpl.java | 5 +-
.../client/impl/PartitionedProducerImpl.java | 32 +-
.../PersistentAcknowledgmentsGroupingTracker.java | 37 +-
.../apache/pulsar/client/impl/ProducerBase.java | 18 +
.../apache/pulsar/client/impl/ProducerImpl.java | 60 +-
.../pulsar/client/impl/ProducerInterceptors.java | 3 +-
.../pulsar/client/impl/PulsarClientImpl.java | 6 +
.../client/impl/TransactionMetaStoreHandler.java | 20 +-
.../impl/auth/oauth2/ClientCredentialsFlow.java | 32 +-
.../impl/AcknowledgementsGroupingTrackerTest.java | 45 +-
.../pulsar/client/impl/ConsumerImplTest.java | 11 +
.../pulsar/client/impl/ProducerImplTest.java | 99 +++-
.../pulsar/client/impl/PulsarClientImplTest.java | 117 ++++
.../impl/TransactionMetaStoreHandlerTest.java | 40 ++
.../auth/oauth2/ClientCredentialsFlowTest.java | 94 +++
pulsar-client/src/test/resources/oauth2_key.json | 7 +
pulsar-function-go/logutil/log.go | 21 +-
pulsar-function-go/pf/instance.go | 11 +-
pulsar-function-go/pf/logAppender.go | 42 ++
pulsar-function-go/pf/logAppender_test.go | 104 ++++
.../pulsar/proxy/server/LookupProxyHandler.java | 163 ++++--
.../proxy/server/LookupProxyHandlerTest.java | 649 +++++++++++++++++++++
.../coordinator/impl/TxnLogBufferedWriter.java | 13 +-
.../coordinator/impl/TxnLogBufferedWriterTest.java | 63 ++
72 files changed, 3763 insertions(+), 318 deletions(-)
create mode 100644 microbench/src/main/java/org/apache/pulsar/broker/resources/TopicResourcesNotificationBenchmark.java
copy {pulsar-broker-common => microbench}/src/main/java/org/apache/pulsar/broker/resources/package-info.java (93%)
create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PulsarCommandSenderImplTest.java
create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SyncConfigStoreSharedWithLocalTest.java
create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryFixedDelayStatsTest.java
create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImplThreadingTest.java
create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ProducerEncryptionKeyFailureTest.java
create mode 100644 pulsar-client/src/test/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlowTest.java
create mode 100644 pulsar-client/src/test/resources/oauth2_key.json
create mode 100644 pulsar-function-go/pf/logAppender_test.go
create mode 100644 pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
(pulsar) 01/23: [improve][conf] Document managedLedgerForceRecovery and schemaLedgerForceRecovery in broker.conf and standalone.conf (#24672)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 454361b0e1adacc8429e3d9198202122946c5200
Author: Thomas Bousquet <th...@gmail.com>
AuthorDate: Thu Oct 22 13:27:54 2026 -0700
[improve][conf] Document managedLedgerForceRecovery and schemaLedgerForceRecovery in broker.conf and standalone.conf (#24672)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit f0e78c4b5ecfd40b52ed958f9d0b0e91c6e1bdb9)
---
conf/broker.conf | 11 +++++++++++
conf/standalone.conf | 11 +++++++++++
2 files changed, 22 insertions(+)
diff --git a/conf/broker.conf b/conf/broker.conf
index 30ccebef805e..bd3de04715a7 100644
--- a/conf/broker.conf
+++ b/conf/broker.conf
@@ -1756,6 +1756,17 @@ managedLedgerInfoCompressionThresholdInBytes=16384
# corrupted at bookkeeper and managed-cursor is stuck at that ledger.
autoSkipNonRecoverableData=false
+# Whether to recover a cursor whose cursor ledger fails to open or read with any BookKeeper error, instead of
+# failing the topic load. The cursor is rewound to the mark-delete position last saved in the cursor metadata,
+# so the acknowledgments made after that snapshot are lost and those messages are delivered again.
+# Updating it dynamically only affects topics loaded after the change.
+managedLedgerForceRecovery=false
+
+# Whether to treat any BookKeeper error when reading a schema ledger as if the schema data were deleted, instead of
+# failing the operation. The topic is then treated as if it had no stored schema, so enabling this can permanently
+# lose schema history.
+schemaLedgerForceRecovery=false
+
# Whether to recover cursors lazily when trying to recover a managed ledger backing a persistent topic.
# It can improve write availability of topics.
# The caveat is now when recovered ledger is ready to write we're not sure if all old consumers last mark
diff --git a/conf/standalone.conf b/conf/standalone.conf
index 69b66ce06e08..dc197246b76e 100644
--- a/conf/standalone.conf
+++ b/conf/standalone.conf
@@ -1210,6 +1210,17 @@ managedLedgerInfoCompressionThresholdInBytes=16384
# corrupted at bookkeeper and managed-cursor is stuck at that ledger.
autoSkipNonRecoverableData=false
+# Whether to recover a cursor whose cursor ledger fails to open or read with any BookKeeper error, instead of
+# failing the topic load. The cursor is rewound to the mark-delete position last saved in the cursor metadata,
+# so the acknowledgments made after that snapshot are lost and those messages are delivered again.
+# Updating it dynamically only affects topics loaded after the change.
+managedLedgerForceRecovery=false
+
+# Whether to treat any BookKeeper error when reading a schema ledger as if the schema data were deleted, instead of
+# failing the operation. The topic is then treated as if it had no stored schema, so enabling this can permanently
+# lose schema history.
+schemaLedgerForceRecovery=false
+
# operation timeout while updating managed-ledger metadata.
managedLedgerMetadataOperationsTimeoutSeconds=60
(pulsar) 14/23: [fix][txn] Fix PendingAckHandleImpl potential thread safety issue (#22166)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 07670237ee56d9a4b6cd8f0ba65f501b7d60f50c
Author: 道君- Tao Jiuming <da...@apache.org>
AuthorDate: Fri Oct 23 08:19:19 2026 +0800
[fix][txn] Fix PendingAckHandleImpl potential thread safety issue (#22166)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 01b0c0adb7a3db1f5193a92476848b3a5eb40528)
---
.../pendingack/impl/PendingAckHandleImpl.java | 59 ++++----
.../impl/PendingAckHandleImplThreadingTest.java | 167 +++++++++++++++++++++
2 files changed, 200 insertions(+), 26 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImpl.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImpl.java
index 3706cfad7110..280a81b62d97 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImpl.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImpl.java
@@ -89,6 +89,8 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
* If the position is batch position and it does not exits the map, will be added to the map.
* If the position is batch position and it exits the map, will do operation `and` for this
* two positions bit set.
+ * <p>
+ * Not thread safe: it is only modified on {@link #internalPinnedExecutor} while holding the handle's monitor.
*/
private LinkedMap<TxnID, HashMap<Position, Position>> individualAckOfTransaction;
@@ -110,7 +112,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
* <p>
* If it does not exits the map, the position will be added to the map.
*/
- private ConcurrentSkipListMap<Position, MutablePair<Position, Integer>> individualAckPositions;
+ private volatile ConcurrentSkipListMap<Position, MutablePair<Position, Integer>> individualAckPositions;
/**
* The map is for transaction with position witch was cumulative acked by this transaction.
@@ -225,8 +227,8 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
acceptQueue.add(() -> internalIndividualAcknowledgeMessage(txnID, positions, completableFuture));
}
- public void internalIndividualAcknowledgeMessage(TxnID txnID, List<MutablePair<Position, Integer>> positions,
- CompletableFuture<Void> completableFuture) {
+ private void internalIndividualAcknowledgeMessage(TxnID txnID, List<MutablePair<Position, Integer>> positions,
+ CompletableFuture<Void> completableFuture) {
if (txnID == null) {
completableFuture.completeExceptionally(new NotAllowedException("txnID can not be null."));
return;
@@ -238,8 +240,8 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
}
this.pendingAckStoreFuture.thenAccept(pendingAckStore ->
- pendingAckStore.appendIndividualAck(txnID, positions).thenAccept(v -> {
- synchronized (org.apache.pulsar.broker.transaction.pendingack.impl.PendingAckHandleImpl.this) {
+ pendingAckStore.appendIndividualAck(txnID, positions).thenAcceptAsync(v -> {
+ synchronized (PendingAckHandleImpl.this) {
for (MutablePair<Position, Integer> positionIntegerMutablePair : positions) {
log.debug()
.attr("position", positionIntegerMutablePair.left)
@@ -311,7 +313,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
handleIndividualAck(txnID, positions);
completableFuture.complete(null);
}
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionallyAsync(e -> {
synchronized (PendingAckHandleImpl.this) {
// we also modify the in memory state when append fail,
// because we don't know the persistent state, when were replay it,
@@ -321,7 +323,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
completableFuture.completeExceptionally(e.getCause());
}
return null;
- })).exceptionally(e -> {
+ }, internalPinnedExecutor)).exceptionally(e -> {
completableFuture.completeExceptionally(e);
return null;
});
@@ -387,7 +389,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
Position position = positions.get(0);
this.pendingAckStoreFuture.thenAccept(pendingAckStore ->
- pendingAckStore.appendCumulativeAck(txnID, position).thenAccept(v -> {
+ pendingAckStore.appendCumulativeAck(txnID, position).thenAcceptAsync(v -> {
log.debug()
.attr("txnId", txnID)
.attr("position", position)
@@ -415,14 +417,14 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
handleCumulativeAck(txnID, position);
completableFuture.complete(null);
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionallyAsync(e -> {
//we also modify the in memory state when append fail, because we don't know the persistent
// state, when wereplay it, it will produce the wrong operation. so we append fail, we should
// wait tc time out or client abort this transaction.
handleCumulativeAck(txnID, position);
completableFuture.completeExceptionally(e.getCause());
return null;
- })
+ }, internalPinnedExecutor)
).exceptionally(e -> {
completableFuture.completeExceptionally(e);
return null;
@@ -472,21 +474,21 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
if (this.cumulativeAckOfTransaction != null) {
if (cumulativeAckOfTransaction.getKey().equals(txnID)) {
pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore
- .appendCommitMark(txnID, AckType.Cumulative).thenAccept(v -> {
+ .appendCommitMark(txnID, AckType.Cumulative).thenAcceptAsync(v -> {
log.debug()
.attr("txnId", txnID)
.log("Transaction pending ack store commit cumulative success");
persistentSubscription.acknowledgeMessageAsync(
Collections.singletonList(cumulativeAckOfTransaction.getValue()),
AckType.Cumulative, properties)
- .thenRun(() -> {
+ .thenRunAsync(() -> {
cumulativeAckOfTransaction = null;
commitFuture.complete(null);
- }).exceptionally(ackError -> {
+ }, internalPinnedExecutor).exceptionally(ackError -> {
commitFuture.completeExceptionally(ackError);
return null;
});
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionally(e -> {
log.error()
.attr("txnId", txnID)
.exception(e)
@@ -502,7 +504,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
}
} else {
pendingAckStoreFuture.thenAccept(pendingAckStore ->
- pendingAckStore.appendCommitMark(txnID, AckType.Individual).thenAccept(v -> {
+ pendingAckStore.appendCommitMark(txnID, AckType.Individual).thenAcceptAsync(v -> {
synchronized (PendingAckHandleImpl.this) {
if (individualAckOfTransaction != null && individualAckOfTransaction.containsKey(txnID)) {
HashMap<Position, Position> pendingAckMessageForCurrentTxn =
@@ -522,7 +524,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
commitFuture.complete(null);
}
}
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionally(e -> {
log.error()
.attr("txnId", txnID)
.exception(e)
@@ -573,22 +575,23 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
acceptQueue.add(() -> internalAbortTxn(txnId, consumer, lowWaterMark, completableFuture));
}
- public CompletableFuture<Void> internalAbortTxn(TxnID txnId, Consumer consumer,
+ private CompletableFuture<Void> internalAbortTxn(TxnID txnId, Consumer consumer,
long lowWaterMark, CompletableFuture<Void> abortFuture) {
if (this.cumulativeAckOfTransaction != null) {
pendingAckStoreFuture.thenAccept(pendingAckStore ->
- pendingAckStore.appendAbortMark(txnId, AckType.Cumulative).thenAccept(v -> {
+ pendingAckStore.appendAbortMark(txnId, AckType.Cumulative).thenAcceptAsync(v -> {
log.debug()
.attr("txnId", txnId)
.log("Transaction pending ack store abort cumulative success");
- if (cumulativeAckOfTransaction.getKey().equals(txnId)) {
+ // another commit or abort may have cleared it while the abort mark was being written
+ if (cumulativeAckOfTransaction != null && cumulativeAckOfTransaction.getKey().equals(txnId)) {
cumulativeAckOfTransaction = null;
}
abortFuture.complete(null);
// in cumulative ack with transaction, don't depend on server redeliver message,
// it will cause the messages to be out of order
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionally(e -> {
log.error()
.attr("txnId", txnId)
.exception(e)
@@ -602,7 +605,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
});
} else if (this.individualAckOfTransaction != null) {
pendingAckStoreFuture.thenAccept(pendingAckStore ->
- pendingAckStore.appendAbortMark(txnId, AckType.Individual).thenAccept(v -> {
+ pendingAckStore.appendAbortMark(txnId, AckType.Individual).thenAcceptAsync(v -> {
synchronized (PendingAckHandleImpl.this) {
HashMap<Position, Position> pendingAckMessageForCurrentTxn =
individualAckOfTransaction.get(txnId);
@@ -620,7 +623,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
abortFuture.complete(null);
}
}
- }).exceptionally(e -> {
+ }, internalPinnedExecutor).exceptionally(e -> {
log.error()
.attr("txnId", txnId)
.exception(e)
@@ -806,10 +809,14 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
HashMap<Position, Position> currentTxn,
Map<String, Long> properties) {
if (currentTxn != null) {
+ // The cursor completes the ack on its own thread, while other transactions may be updating
+ // individualAckOfTransaction, so the removal must go back to the pinned executor and the lock.
return persistentSubscription.acknowledgeMessageAsync(new ArrayList<>(currentTxn.values()),
- AckType.Individual, properties).thenRun(() -> {
- individualAckOfTransaction.remove(txnID);
- });
+ AckType.Individual, properties).thenRunAsync(() -> {
+ synchronized (PendingAckHandleImpl.this) {
+ individualAckOfTransaction.remove(txnID);
+ }
+ }, internalPinnedExecutor);
} else {
return CompletableFuture.completedFuture(null);
}
@@ -968,7 +975,7 @@ public class PendingAckHandleImpl extends PendingAckHandleState implements Pendi
}
@Override
- public TransactionPendingAckStats getStats(boolean lowWaterMarks) {
+ public synchronized TransactionPendingAckStats getStats(boolean lowWaterMarks) {
TransactionPendingAckStats transactionPendingAckStats = new TransactionPendingAckStats();
transactionPendingAckStats.state = this.getState().name();
if (lowWaterMarks) {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImplThreadingTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImplThreadingTest.java
new file mode 100644
index 000000000000..5291311baf8a
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImplThreadingTest.java
@@ -0,0 +1,167 @@
+/*
+ * 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.pendingack.impl;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.PositionFactory;
+import org.apache.commons.lang3.tuple.MutablePair;
+import org.apache.pulsar.broker.service.persistent.PersistentSubscription;
+import org.apache.pulsar.broker.transaction.pendingack.PendingAckStore;
+import org.apache.pulsar.broker.transaction.pendingack.TransactionPendingAckStoreProvider;
+import org.apache.pulsar.client.api.transaction.TxnID;
+import org.apache.pulsar.common.api.proto.CommandAck.AckType;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Verifies that {@link PendingAckHandleImpl} only changes its in-memory pending-ack state on its pinned executor,
+ * even when the pending-ack store or the cursor completes on another thread.
+ */
+@Test(groups = "broker")
+public class PendingAckHandleImplThreadingTest {
+
+ private ExecutorService pinnedExecutor;
+ private PersistentSubscription subscription;
+ private PendingAckStore store;
+ private PendingAckHandleImpl handle;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ pinnedExecutor = Executors.newSingleThreadExecutor(new DefaultThreadFactory("pending-ack-pinned"));
+ subscription = mock(PersistentSubscription.class, RETURNS_DEEP_STUBS);
+ when(subscription.getTopicName()).thenReturn("persistent://public/default/pending-ack-threading");
+ when(subscription.getName()).thenReturn("sub");
+ var pulsar = subscription.getTopic().getBrokerService().getPulsar();
+ when(pulsar.getTransactionExecutorProvider().getExecutor(any(PendingAckHandleImpl.class)))
+ .thenReturn(pinnedExecutor);
+ TransactionPendingAckStoreProvider provider = mock(TransactionPendingAckStoreProvider.class);
+ when(pulsar.getTransactionPendingAckStoreProvider()).thenReturn(provider);
+ when(provider.checkInitializedBefore(subscription)).thenReturn(CompletableFuture.completedFuture(true));
+ store = mock(PendingAckStore.class);
+ when(provider.newPendingAckStore(subscription)).thenReturn(CompletableFuture.completedFuture(store));
+ doAnswer(invocation -> {
+ PendingAckHandleImpl h = invocation.getArgument(0);
+ h.changeToReadyState();
+ h.completeHandleFuture();
+ return null;
+ }).when(store).replayAsync(any(), any());
+ when(store.appendCommitMark(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
+ when(store.closeAsync()).thenReturn(CompletableFuture.completedFuture(null));
+
+ handle = new PendingAckHandleImpl(subscription);
+ handle.pendingAckHandleFuture().get(10, TimeUnit.SECONDS);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ if (handle != null) {
+ handle.closeAsync().get(10, TimeUnit.SECONDS);
+ }
+ pinnedExecutor.shutdownNow();
+ }
+
+ @Test
+ public void testAppendCompletedOnAnotherThreadIsAppliedOnPinnedExecutor() throws Exception {
+ CompletableFuture<Void> appended = new CompletableFuture<>();
+ when(store.appendIndividualAck(any(), anyList())).thenReturn(appended);
+ TxnID txnID = new TxnID(1, 1);
+ CompletableFuture<Void> ackFuture = handle.individualAcknowledgeMessage(txnID, positions(5, 1));
+ verify(store, timeout(10000)).appendIndividualAck(eq(txnID), anyList());
+
+ CountDownLatch release = blockPinnedExecutor();
+ try {
+ // Completed here, as the store's own thread would.
+ appended.complete(null);
+ assertThat(handle.getStats(false).ongoingTxnSize)
+ .as("The ack must not be applied on the store's thread").isEqualTo(0);
+ assertThat(ackFuture).isNotDone();
+ } finally {
+ release.countDown();
+ }
+ ackFuture.get(10, TimeUnit.SECONDS);
+ assertThat(handle.getStats(false).ongoingTxnSize).isEqualTo(1);
+ }
+
+ @Test
+ public void testCommitCompletedByCursorOnAnotherThreadIsAppliedOnPinnedExecutor() throws Exception {
+ when(store.appendIndividualAck(any(), anyList())).thenReturn(CompletableFuture.completedFuture(null));
+ TxnID txnID = new TxnID(1, 2);
+ handle.individualAcknowledgeMessage(txnID, positions(5, 2)).get(10, TimeUnit.SECONDS);
+ assertThat(handle.getStats(false).ongoingTxnSize).isEqualTo(1);
+
+ CompletableFuture<Void> cursorAck = new CompletableFuture<>();
+ when(subscription.acknowledgeMessageAsync(anyList(), eq(AckType.Individual), any())).thenReturn(cursorAck);
+ CompletableFuture<Void> commitFuture = handle.commitTxn(txnID, Map.of(), 0L);
+ verify(subscription, timeout(10000)).acknowledgeMessageAsync(anyList(), eq(AckType.Individual), any());
+
+ CountDownLatch release = blockPinnedExecutor();
+ try {
+ // Completed here, as the cursor's mark-delete callback thread would.
+ cursorAck.complete(null);
+ assertThat(handle.getStats(false).ongoingTxnSize)
+ .as("The committed transaction must not be removed on the cursor's thread").isEqualTo(1);
+ assertThat(commitFuture).isNotDone();
+ } finally {
+ release.countDown();
+ }
+ commitFuture.get(10, TimeUnit.SECONDS);
+ assertThat(handle.getStats(false).ongoingTxnSize).isEqualTo(0);
+ }
+
+ private static List<MutablePair<Position, Integer>> positions(long ledgerId, long entryId) {
+ return List.of(MutablePair.of(PositionFactory.create(ledgerId, entryId), 1));
+ }
+
+ /**
+ * Occupies the pinned executor until the returned latch is released, so that any work handed to it stays queued.
+ */
+ private CountDownLatch blockPinnedExecutor() throws Exception {
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ pinnedExecutor.execute(() -> {
+ started.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ assertThat(started.await(10, TimeUnit.SECONDS)).isTrue();
+ return release;
+ }
+}
(pulsar) 21/23: [fix][client] Close the producer when its encryption key cannot be loaded (#27024)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit ce0969cf16ca8615662633cb74f57bcedccb0fc9
Author: SeungTaek Lim <na...@gmail.com>
AuthorDate: Fri Oct 23 14:10:36 2026 +0900
[fix][client] Close the producer when its encryption key cannot be loaded (#27024)
(cherry picked from commit c2b5d91c6f413d4f2d5cd9dfd707e61d7879e24b)
---
.../impl/ProducerEncryptionKeyFailureTest.java | 83 +++++++++++++++
.../apache/pulsar/client/impl/ProducerBase.java | 7 ++
.../apache/pulsar/client/impl/ProducerImpl.java | 57 ++++++----
.../pulsar/client/impl/PulsarClientImpl.java | 6 ++
.../pulsar/client/impl/ProducerImplTest.java | 75 +++++++++++++
.../pulsar/client/impl/PulsarClientImplTest.java | 117 +++++++++++++++++++++
6 files changed, 327 insertions(+), 18 deletions(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ProducerEncryptionKeyFailureTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ProducerEncryptionKeyFailureTest.java
new file mode 100644
index 000000000000..379243efc66b
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ProducerEncryptionKeyFailureTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.client.impl;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.client.api.CryptoKeyReader;
+import org.apache.pulsar.client.api.EncryptionKeyInfo;
+import org.apache.pulsar.client.api.ProducerConsumerBase;
+import org.apache.pulsar.client.api.PulsarClientException;
+import org.awaitility.Awaitility;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker-impl")
+public class ProducerEncryptionKeyFailureTest extends ProducerConsumerBase {
+
+ @BeforeClass(alwaysRun = true)
+ @Override
+ protected void setup() throws Exception {
+ super.internalSetup();
+ super.producerBaseSetup();
+ }
+
+ @AfterClass(alwaysRun = true)
+ @Override
+ protected void cleanup() throws Exception {
+ super.internalCleanup();
+ }
+
+ /** A key reader that cannot find any key, as a misconfigured deployment would. */
+ private static final class MissingKeyReader implements CryptoKeyReader {
+ @Override
+ public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> metadata) {
+ return null;
+ }
+
+ @Override
+ public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> metadata) {
+ return null;
+ }
+ }
+
+ @Test(timeOut = 60_000)
+ public void testProducerWhoseKeyCannotBeLoadedIsNotLeftBehind() throws Exception {
+ String topic = "persistent://my-property/my-ns/crypto-key-failure-" + System.nanoTime();
+ // Created up front so that the broker can report its publishers whether or not a producer connects.
+ admin.topics().createNonPartitionedTopic(topic);
+ PulsarClientImpl client = (PulsarClientImpl) pulsarClient;
+
+ expectThrows(PulsarClientException.CryptoException.class, () -> pulsarClient.newProducer()
+ .topic(topic)
+ .addEncryptionKey("missing-key")
+ .cryptoKeyReader(new MissingKeyReader())
+ .create());
+
+ // The connection is opened by another thread: give it time to register the producer, which it must not.
+ Awaitility.await().during(3, TimeUnit.SECONDS).atMost(10, TimeUnit.SECONDS).untilAsserted(() ->
+ assertTrue(admin.topics().getStats(topic).getPublishers().isEmpty(),
+ "A producer whose creation failed must not stay registered on the broker"));
+ assertEquals(client.producersCount(), 0, "A producer whose creation failed must not stay in the client");
+ }
+}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
index 7cfcec64e896..1b5bef3f9c63 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
@@ -147,6 +147,13 @@ public abstract class ProducerBase<T> extends HandlerState implements Producer<T
@Override
public abstract CompletableFuture<Void> closeAsync();
+ /** Whether the producer has reached a state it does not leave: closing, closed, failed, terminated or fenced. */
+ protected boolean isTerminalState() {
+ State state = getState();
+ return state == State.Closing || state == State.Closed || state == State.Failed
+ || state == State.Terminated || state == State.ProducerFenced;
+ }
+
@Override
public String getTopic() {
return topic;
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
index 393b685e8525..16a220337c87 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
@@ -277,24 +277,6 @@ public class ProducerImpl<T> extends ProducerBase<T> implements TimerTask, Conne
this.msgCrypto = null;
}
- if (this.msgCrypto != null) {
- // Regenerate data key cipher at fixed interval
- keyGeneratorTask = client.eventLoopGroup().scheduleWithFixedDelay(catchingAndLoggingThrowables(() -> {
- try {
- msgCrypto.addPublicKeyCipher(conf.getEncryptionKeys(), conf.getCryptoKeyReader());
- } catch (CryptoException e) {
- if (!producerCreatedFuture.isDone()) {
- log.warn().log("Failed to add public key cipher");
- producerCreatedFuture.completeExceptionally(
- PulsarClientException.wrap(e,
- String.format("The producer %s of the topic %s "
- + "adds the public key cipher was failed",
- producerName, topic)));
- }
- }
- }), 0L, 4L, TimeUnit.HOURS);
- }
-
if (conf.getSendTimeoutMs() > 0) {
sendTimeout = client.timer().newTimeout(this, conf.getSendTimeoutMs(), TimeUnit.MILLISECONDS);
}
@@ -345,6 +327,9 @@ public class ProducerImpl<T> extends ProducerBase<T> implements TimerTask, Conne
this.connectionHandler = initConnectionHandler();
setChunkMaxMessageSize();
+ if (this.msgCrypto != null) {
+ scheduleKeyGeneratorTask();
+ }
grabCnx();
producersOpenedCounter.increment();
}
@@ -3208,6 +3193,42 @@ public class ProducerImpl<T> extends ProducerBase<T> implements TimerTask, Conne
this.connectionHandler.setClientCnx(clientCnx);
}
+ /**
+ * Loads the public key cipher now and refreshes it at a fixed interval. Called once the producer is initialized
+ * and before it connects: a key that cannot be loaded fails the creation and closes the producer, which uses the
+ * counters, the stats and the connection handler, and a connection failure that ends the creation
+ * ({@link #connectionFailed}) must find the handle of the task to cancel it. {@link #closeAsync()} is
+ * synchronized, so the task cannot close the producer before the handle is stored here and the close can cancel
+ * it; when the producer has reached a terminal state by then, from the scheduling thread for instance, the handle
+ * is cancelled here instead.
+ */
+ private synchronized void scheduleKeyGeneratorTask() {
+ keyGeneratorTask = client.eventLoopGroup().scheduleWithFixedDelay(
+ catchingAndLoggingThrowables(this::addPublicKeyCipher), 0L, 4L, TimeUnit.HOURS);
+ if (isTerminalState()) {
+ keyGeneratorTask.cancel(false);
+ }
+ }
+
+ private void addPublicKeyCipher() {
+ try {
+ msgCrypto.addPublicKeyCipher(conf.getEncryptionKeys(), conf.getCryptoKeyReader());
+ } catch (CryptoException e) {
+ if (!producerCreatedFuture.isDone()) {
+ log.warn().log("Failed to add public key cipher");
+ producerCreatedFuture.completeExceptionally(
+ PulsarClientException.wrap(e,
+ String.format("The producer %s of the topic %s "
+ + "adds the public key cipher was failed",
+ producerName, topic)));
+ // The creation has failed, so close the producer as the other creation failures do. Otherwise it
+ // stays in the client and keeps the connection it is about to open, which registers it on the
+ // broker and then reconnects it as if it had been created.
+ closeAsync();
+ }
+ }
+ }
+
void grabCnx() {
this.connectionHandler.grabCnx();
}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
index 5b88d3cf8761..a37270342347 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
@@ -1013,6 +1013,12 @@ public class PulsarClientImpl implements PulsarClient {
Optional.empty());
}
producers.add(producer);
+ // The creation can fail before this line runs, from another thread or from a connection that fails at
+ // once, in which case the producer has already closed or failed and removed itself from the client. Do
+ // not keep it then.
+ if (producer.isTerminalState()) {
+ cleanupProducer(producer);
+ }
}).exceptionally(ex -> {
log.warn().attr("topic", topic).exceptionMessage(ex).log("Failed to get partitioned topic metadata");
producerCreatedFuture.completeExceptionally(ex);
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
index a881701e6bcc..91f938289488 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
@@ -24,6 +24,7 @@ import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyLong;
+import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
@@ -66,6 +67,7 @@ import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pulsar.client.api.CryptoKeyReader;
import org.apache.pulsar.client.api.MessageCrypto;
+import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerCryptoFailureAction;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
@@ -79,6 +81,7 @@ import org.apache.pulsar.client.impl.metrics.LatencyHistogram;
import org.apache.pulsar.common.api.proto.MessageMetadata;
import org.apache.pulsar.common.protocol.ByteBufPair;
import org.apache.pulsar.common.protocol.Commands;
+import org.apache.pulsar.common.util.FutureUtil;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.testng.annotations.DataProvider;
@@ -327,6 +330,78 @@ public class ProducerImplTest {
return conf;
}
+ @DataProvider
+ public Object[][] keyTaskTiming() {
+ return new Object[][]{{true}, {false}};
+ }
+
+ /**
+ * A key that cannot be loaded fails the creation, and the producer is closed and taken out of the client with
+ * its key task cancelled, whether the task runs while the constructor is still scheduling it ({@code inline})
+ * or later.
+ */
+ @Test(dataProvider = "keyTaskTiming")
+ @SuppressWarnings("unchecked")
+ public void testKeyThatCannotBeLoadedClosesTheProducer(boolean inline) {
+ PulsarClientImpl client = mockedPulsarClient();
+ EventLoopGroup eventLoopGroup = client.eventLoopGroup();
+ ScheduledFuture<?> keyTask = mock(ScheduledFuture.class);
+ AtomicReference<Runnable> scheduled = new AtomicReference<>();
+ doAnswer(invocation -> {
+ Runnable task = invocation.getArgument(0);
+ if (inline) {
+ task.run();
+ } else {
+ scheduled.set(task);
+ }
+ return keyTask;
+ }).when(eventLoopGroup).scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any());
+ ProducerConfigurationData conf = new ProducerConfigurationData();
+ conf.setEncryptionKeys(new TreeSet<>(Collections.singleton("missing-key")));
+ conf.setCryptoKeyReader(mock(CryptoKeyReader.class)); // returns no key
+ CompletableFuture<Producer<byte[]>> created = new CompletableFuture<>();
+
+ ProducerImpl<byte[]> producer = new ProducerImpl<>(client, "persistent://public/default/key-failure", conf,
+ created, 0, Schema.BYTES, null, Optional.empty());
+ if (!inline) {
+ scheduled.get().run();
+ }
+
+ assertTrue(created.isCompletedExceptionally(), "The creation must fail");
+ assertThatThrownBy(created::join).hasCauseInstanceOf(PulsarClientException.CryptoException.class);
+ assertEquals(producer.getState(), HandlerState.State.Closed);
+ verify(keyTask).cancel(false);
+ verify(client).cleanupProducer(producer);
+ }
+
+ /**
+ * A connection failure that ends the creation runs the terminal cleanup; the key task scheduled by the
+ * constructor must be cancelled by it, so it is scheduled before the producer connects.
+ */
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testKeyTaskIsCancelledWhenTheConnectionFailsTheCreation() {
+ PulsarClientImpl client = mockedPulsarClient();
+ EventLoopGroup eventLoopGroup = client.eventLoopGroup();
+ ScheduledFuture<?> keyTask = mock(ScheduledFuture.class);
+ doReturn(keyTask).when(eventLoopGroup).scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any());
+ when(client.getConnection(anyString(), anyInt())).thenReturn(
+ FutureUtil.failedFuture(new PulsarClientException.AuthorizationException("not allowed")));
+ ProducerConfigurationData conf = new ProducerConfigurationData();
+ conf.setEncryptionKeys(new TreeSet<>(Collections.singleton("key")));
+ conf.setCryptoKeyReader(mock(CryptoKeyReader.class));
+ CompletableFuture<Producer<byte[]>> created = new CompletableFuture<>();
+
+ ProducerImpl<byte[]> producer = new ProducerImpl<>(client, "persistent://public/default/connection-failure",
+ conf, created, 0, Schema.BYTES, null, Optional.empty());
+
+ assertTrue(created.isCompletedExceptionally(), "The creation must fail");
+ assertThatThrownBy(created::join).hasCauseInstanceOf(PulsarClientException.AuthorizationException.class);
+ assertEquals(producer.getState(), HandlerState.State.Failed);
+ verify(keyTask).cancel(false);
+ verify(client).cleanupProducer(producer);
+ }
+
/** A client mock whose stubs satisfy the {@link ProducerImpl} constructor. */
private static PulsarClientImpl mockedPulsarClient() {
PulsarClientImpl client = mock(PulsarClientImpl.class);
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PulsarClientImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PulsarClientImplTest.java
index 8e01cc08c333..54050cb8eda5 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PulsarClientImplTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PulsarClientImplTest.java
@@ -54,17 +54,23 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
import java.util.regex.Pattern;
import lombok.Cleanup;
+import org.apache.pulsar.client.api.MessageRoutingMode;
+import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.PulsarClientSharedResources;
+import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.ServiceUrlProvider;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
+import org.apache.pulsar.client.impl.conf.ProducerConfigurationData;
import org.apache.pulsar.client.impl.metrics.InstrumentProvider;
import org.apache.pulsar.client.util.ExecutorProvider;
import org.apache.pulsar.client.util.ScheduledExecutorProvider;
@@ -76,6 +82,7 @@ import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.util.netty.EventLoopUtil;
import org.mockito.Mockito;
import org.testng.annotations.AfterMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
@@ -108,6 +115,116 @@ public class PulsarClientImplTest {
assertTrue(client.isClosed());
}
+ @DataProvider
+ public Object[][] partitions() {
+ return new Object[][]{{0}, {2}};
+ }
+
+ /**
+ * Cancelling the creation future does not stop the creation: the producer still comes up, and the client keeps
+ * owning it, so it is closed with the client.
+ */
+ @Test(dataProvider = "partitions")
+ @SuppressWarnings("unchecked")
+ public void testCancelledCreationLeavesTheProducerOwnedByTheClient(int partitions) throws Exception {
+ ClientConfigurationData conf = new ClientConfigurationData();
+ conf.setServiceUrl("pulsar://localhost:6650");
+ initializeEventLoopGroup(conf);
+ LookupService lookup = mock(LookupService.class);
+ CompletableFuture<PartitionedTopicMetadata> metadata = new CompletableFuture<>();
+ when(lookup.getPartitionedTopicMetadata(any(TopicName.class), anyBoolean(), anyBoolean()))
+ .thenReturn(metadata);
+ when(lookup.getBroker(any()))
+ .thenReturn(CompletableFuture.completedFuture(new LookupTopicResult(
+ mock(InetSocketAddress.class), mock(InetSocketAddress.class), false)));
+ ConnectionPool pool = mock(ConnectionPool.class);
+ ClientCnx cnx = mock(ClientCnx.class);
+ ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
+ Channel channel = mock(Channel.class);
+ when(channel.remoteAddress()).thenReturn(mock(SocketAddress.class));
+ when(channel.eventLoop()).thenReturn(eventLoopGroup.next());
+ when(ctx.channel()).thenReturn(channel);
+ when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(mock(ChannelFuture.class));
+ when(ctx.voidPromise()).thenReturn(mock(ChannelPromise.class));
+ when(cnx.channel()).thenReturn(channel);
+ when(cnx.ctx()).thenReturn(ctx);
+ ProducerResponse response = mock(ProducerResponse.class);
+ when(response.getProducerName()).thenReturn("cancelled-creation-producer");
+ when(cnx.sendRequestWithId(any(ByteBuf.class), anyLong()))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ when(pool.getConnection(any(InetSocketAddress.class), any(InetSocketAddress.class), anyInt()))
+ .thenReturn(CompletableFuture.completedFuture(cnx));
+ PulsarClientImpl client = new PulsarClientImpl(conf, eventLoopGroup, pool);
+ client.setLookup(lookup);
+ try {
+ ProducerConfigurationData producerConf = new ProducerConfigurationData();
+ producerConf.setTopicName("persistent://public/default/cancelled-creation");
+ producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
+ CompletableFuture<Producer<byte[]>> creation = client.createProducerAsync(producerConf, Schema.BYTES);
+
+ // Cancelled before the metadata is known, which is before the producer exists.
+ creation.cancel(true);
+ metadata.complete(new PartitionedTopicMetadata(partitions));
+
+ assertEquals(client.producersCount(), 1, "The client must keep owning the producer");
+ } finally {
+ client.close();
+ }
+ assertEquals(client.producersCount(), 0, "Closing the client must close the producer it kept");
+ }
+
+ @DataProvider
+ public Object[][] endedBeforeRegistration() {
+ return new Object[][]{
+ {"closed", (Consumer<ProducerImpl<?>>) ProducerImpl::closeAsync},
+ {"failed", (Consumer<ProducerImpl<?>>) producer ->
+ producer.connectionFailed(new PulsarClientException.AuthorizationException("not allowed"))},
+ };
+ }
+
+ /**
+ * A producer whose creation fails before the client has registered it, from another thread or from a
+ * connection that fails at once, removes itself from the client while it is not there yet. The client must not
+ * keep it afterwards.
+ */
+ @Test(dataProvider = "endedBeforeRegistration")
+ @SuppressWarnings("unchecked")
+ public void testProducerEndedBeforeItIsRegisteredIsNotKept(String how, Consumer<ProducerImpl<?>> end)
+ throws Exception {
+ LookupService lookup = mock(LookupService.class);
+ when(lookup.getPartitionedTopicMetadata(any(TopicName.class), anyBoolean(), anyBoolean()))
+ .thenReturn(CompletableFuture.completedFuture(new PartitionedTopicMetadata()));
+ when(lookup.getBroker(any())).thenReturn(new CompletableFuture<>());
+ ConnectionPool pool = mock(ConnectionPool.class);
+ ClientConfigurationData conf = new ClientConfigurationData();
+ conf.setServiceUrl("pulsar://localhost:6650");
+ PulsarClientImpl client = new PulsarClientImpl(conf, eventLoopGroup, pool) {
+ @Override
+ protected <T> ProducerImpl<T> newProducerImpl(String topic, int partitionIndex,
+ ProducerConfigurationData producerConf, Schema<T> schema,
+ ProducerInterceptors interceptors,
+ CompletableFuture<Producer<T>> producerCreatedFuture,
+ Optional<String> overrideProducerName) {
+ ProducerImpl<T> producer = super.newProducerImpl(topic, partitionIndex, producerConf, schema,
+ interceptors, producerCreatedFuture, overrideProducerName);
+ // Before createProducerAsync() has added the producer.
+ end.accept(producer);
+ return producer;
+ }
+ };
+ client.setLookup(lookup);
+ try {
+ ProducerConfigurationData producerConf = new ProducerConfigurationData();
+ producerConf.setTopicName("persistent://public/default/closed-before-registered");
+ client.createProducerAsync(producerConf, Schema.BYTES);
+
+ assertEquals(client.producersCount(), 0,
+ "A producer " + how + " before it was registered must not be kept");
+ } finally {
+ client.close();
+ }
+ }
+
@Test
@SuppressWarnings("unchecked")
public void testConsumerIsClosed() throws Exception {
(pulsar) 16/23: [fix][client] Queue acks without grouping while the consumer is reconnecting (#21928)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit b701db6686ee975f9e9a3ff0fde52ead07601d7e
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Oct 23 09:40:31 2026 +0800
[fix][client] Queue acks without grouping while the consumer is reconnecting (#21928)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 4060ccee890553c9dc5dbcb7cb81c1796925a7b1)
---
.../apache/pulsar/client/impl/ConsumerAckTest.java | 47 ++++++++++++++++++++++
.../apache/pulsar/client/impl/ConsumerImpl.java | 2 +
.../PersistentAcknowledgmentsGroupingTracker.java | 37 +++++++++++------
.../impl/AcknowledgementsGroupingTrackerTest.java | 45 ++++++++++++++++++++-
4 files changed, 117 insertions(+), 14 deletions(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ConsumerAckTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ConsumerAckTest.java
index 973fdc6e17a7..7ab9c9d7d541 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ConsumerAckTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/ConsumerAckTest.java
@@ -43,8 +43,10 @@ import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
+import org.awaitility.Awaitility;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.collections.Sets;
@@ -180,6 +182,51 @@ public class ConsumerAckTest extends SharedPulsarBaseTest {
assertTrue(data.consumer.getUnAckedMessageTracker().isEmpty());
}
+ @DataProvider
+ public Object[][] cumulative() {
+ return new Object[][]{{false}, {true}};
+ }
+
+ @Test(timeOut = 30000, dataProvider = "cumulative")
+ public void testAckWithoutGroupingWhileReconnecting(boolean cumulative) throws Exception {
+ final String topic = newTopicName();
+ // Leaves the consumer without a connection for a while after the unload
+ @Cleanup
+ PulsarClient slowReconnectClient = PulsarClient.builder()
+ .serviceUrl(getBrokerServiceUrl())
+ .startingBackoffInterval(3, TimeUnit.SECONDS)
+ .maxBackoffInterval(3, TimeUnit.SECONDS)
+ .build();
+ @Cleanup
+ ConsumerImpl<String> consumer = (ConsumerImpl<String>) slowReconnectClient.newConsumer(Schema.STRING)
+ .topic(topic)
+ .subscriptionName("sub")
+ .acknowledgmentGroupTime(0, TimeUnit.MILLISECONDS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topic)
+ .enableBatching(false)
+ .create();
+ producer.send("msg");
+ Message<String> message = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(message);
+
+ admin.topics().unload(topic);
+ Awaitility.await().until(() -> !consumer.isConnected());
+ // Without a connection, the ack waits for the subscription instead of failing
+ if (cumulative) {
+ consumer.acknowledgeCumulative(message.getMessageId());
+ } else {
+ consumer.acknowledge(message.getMessageId());
+ }
+
+ Awaitility.await().untilAsserted(() -> {
+ assertTrue(consumer.isConnected());
+ assertEquals(admin.topics().getStats(topic).getSubscriptions().get("sub").getMsgBacklog(), 0);
+ });
+ }
+
// Send 1 non-batched message, then send N-1 messages that are in the same batch
@SuppressWarnings("unchecked")
private AckTestData prepareDataForAck(String topic) throws PulsarClientException {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
index df9f1987d5a1..2d78c9a0cf34 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
@@ -990,6 +990,8 @@ public class ConsumerImpl<T> extends ConsumerBase<T> implements ConnectionHandle
if (!(firstTimeConnect && hasParentConsumer) && getCurrentReceiverQueueSize() != 0) {
increaseAvailablePermits(cnx, getCurrentReceiverQueueSize());
}
+ // send the acks that waited for the subscription
+ acknowledgmentsGroupingTracker.flush();
future.complete(null);
}).exceptionally((e) -> {
deregisterFromClientCnx();
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PersistentAcknowledgmentsGroupingTracker.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PersistentAcknowledgmentsGroupingTracker.java
index 501c7b07179b..fd0152c02ca9 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PersistentAcknowledgmentsGroupingTracker.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PersistentAcknowledgmentsGroupingTracker.java
@@ -252,10 +252,22 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
}
}
+ private boolean isImmediateAck(Map<String, Long> properties) {
+ // We cannot group acks when there are properties attached to them. Fortunately that's an uncommon condition
+ // since it's only used for the compaction subscription. Without a delay, the acks are only grouped while the
+ // consumer is not subscribed, until the flush that follows the subscription.
+ return (properties != null && !properties.isEmpty())
+ || (acknowledgementGroupTimeMicros == 0 && getSubscribedCnx() != null);
+ }
+
+ // The connection of the subscribed consumer: the broker drops the acks sent before the subscription completes
+ private @Nullable ClientCnx getSubscribedCnx() {
+ ClientCnx cnx = consumer.getClientCnx();
+ return cnx != null && consumer.getState() != HandlerState.State.Connecting ? cnx : null;
+ }
+
private CompletableFuture<Void> doIndividualAck(MessageIdAdv messageId, Map<String, Long> properties) {
- if (acknowledgementGroupTimeMicros == 0 || (properties != null && !properties.isEmpty())) {
- // We cannot group acks if the delay is 0 or when there are properties attached to it. Fortunately that's an
- // uncommon condition since it's only used for the compaction subscription.
+ if (isImmediateAck(properties)) {
return doImmediateAck(messageId, AckType.Individual, properties, null);
} else {
Optional<Lock> readLock = acquireReadLock();
@@ -264,7 +276,7 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
return readLock.map(__ -> currentIndividualAckFuture).orElse(CompletableFuture.completedFuture(null));
} finally {
readLock.ifPresent(Lock::unlock);
- if (isMaxAckGroupSizeReached()) {
+ if (acknowledgementGroupTimeMicros == 0 || isMaxAckGroupSizeReached()) {
flush();
}
}
@@ -291,7 +303,7 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
private CompletableFuture<Void> doIndividualBatchAck(MessageIdAdv batchMessageId,
Map<String, Long> properties) {
- if (acknowledgementGroupTimeMicros == 0 || (properties != null && !properties.isEmpty())) {
+ if (isImmediateAck(properties)) {
return doImmediateBatchIndexAck(batchMessageId, batchMessageId.getBatchIndex(),
batchMessageId.getBatchSize(), AckType.Individual, properties);
} else {
@@ -306,7 +318,7 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
return readLock.map(__ -> currentIndividualAckFuture).orElse(CompletableFuture.completedFuture(null));
} finally {
readLock.ifPresent(Lock::unlock);
- if (isMaxAckGroupSizeReached()) {
+ if (acknowledgementGroupTimeMicros == 0 || isMaxAckGroupSizeReached()) {
flush();
}
}
@@ -315,9 +327,7 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
private CompletableFuture<Void> doCumulativeAck(MessageIdAdv messageId, Map<String, Long> properties,
BitSetRecyclable bitSet) {
consumer.getStats().incrementNumAcksSent(consumer.getUnAckedMessageTracker().removeMessagesTill(messageId));
- if (acknowledgementGroupTimeMicros == 0 || (properties != null && !properties.isEmpty())) {
- // We cannot group acks if the delay is 0 or when there are properties attached to it. Fortunately that's an
- // uncommon condition since it's only used for the compaction subscription.
+ if (isImmediateAck(properties)) {
return doImmediateAck(messageId, AckType.Cumulative, properties, bitSet);
} else {
Optional<Lock> readLock = acquireReadLock();
@@ -331,6 +341,9 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
}).orElse(CompletableFuture.completedFuture(null));
} finally {
readLock.ifPresent(Lock::unlock);
+ if (acknowledgementGroupTimeMicros == 0) {
+ flush();
+ }
}
}
}
@@ -370,7 +383,7 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
private CompletableFuture<Void> doCumulativeBatchIndexAck(MessageIdAdv batchMessageId,
Map<String, Long> properties) {
- if (acknowledgementGroupTimeMicros == 0 || (properties != null && !properties.isEmpty())) {
+ if (isImmediateAck(properties)) {
return doImmediateBatchIndexAck(batchMessageId, batchMessageId.getBatchIndex(),
batchMessageId.getBatchSize(), AckType.Cumulative, properties);
} else {
@@ -450,11 +463,11 @@ public class PersistentAcknowledgmentsGroupingTracker implements Acknowledgments
*/
@Override
public void flush() {
- ClientCnx cnx = consumer.getClientCnx();
+ ClientCnx cnx = getSubscribedCnx();
if (cnx == null) {
log.debug().attr("consumer", consumer)
- .log("Cannot flush pending acks since we're not connected to broker");
+ .log("Cannot flush pending acks since we're not subscribed on the broker");
return;
}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/AcknowledgementsGroupingTrackerTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/AcknowledgementsGroupingTrackerTest.java
index c22453ceb2ba..c6f6276b698e 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/AcknowledgementsGroupingTrackerTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/AcknowledgementsGroupingTrackerTest.java
@@ -28,6 +28,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
@@ -351,8 +352,11 @@ public class AcknowledgementsGroupingTrackerTest {
returnCnx.set(false);
try {
- tracker.addAcknowledgment(msg1, AckType.Individual, Collections.emptyMap());
- assertFalse(tracker.isDuplicate(msg1));
+ CompletableFuture<Void> ackFuture =
+ tracker.addAcknowledgment(msg1, AckType.Individual, Collections.emptyMap());
+ // Without a connection, the ack waits for the next flush instead of failing
+ assertFalse(ackFuture.isCompletedExceptionally());
+ assertTrue(tracker.isDuplicate(msg1));
} finally {
returnCnx.set(true);
}
@@ -366,6 +370,43 @@ public class AcknowledgementsGroupingTrackerTest {
tracker.close();
}
+ @Test(dataProvider = "isNeedReceipt")
+ public void testImmediateAcksWaitForTheSubscription(boolean isNeedReceipt) throws Exception {
+ ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
+ conf.setAcknowledgementsGroupTimeMicros(0);
+ conf.setAckReceiptEnabled(isNeedReceipt);
+ PersistentAcknowledgmentsGroupingTracker tracker =
+ new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
+
+ MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
+ MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
+ MessageIdImpl msg3 = new MessageIdImpl(5, 3, 0);
+ MessageIdImpl msg4 = new MessageIdImpl(5, 4, 0);
+
+ // Reconnected but not subscribed yet: the broker would drop the acks sent on the new connection
+ doReturn(HandlerState.State.Connecting).when(consumer).getState();
+ clearInvocations(cnx);
+ try {
+ assertFalse(tracker.addAcknowledgment(msg2, AckType.Cumulative, Collections.emptyMap())
+ .isCompletedExceptionally());
+ assertFalse(tracker.addAcknowledgment(msg4, AckType.Individual, Collections.emptyMap())
+ .isCompletedExceptionally());
+ assertTrue(tracker.isDuplicate(msg1));
+ assertFalse(tracker.isDuplicate(msg3));
+ assertTrue(tracker.isDuplicate(msg4));
+ assertEquals(tracker.getPendingIndividualAcksSize(), 1);
+ verifyNoInteractions(cnx);
+ } finally {
+ doReturn(HandlerState.State.Ready).when(consumer).getState();
+ }
+
+ // The flush that follows the subscription sends them
+ tracker.flush();
+ assertFalse(tracker.isDuplicate(msg4));
+ assertEquals(tracker.getPendingIndividualAcksSize(), 0);
+ tracker.close();
+ }
+
@Test
public void testIndividualAckPropertiesAreCheckedAfterInterceptor() {
ConsumerImpl<?> disconnectedConsumer = mock(ConsumerImpl.class);
(pulsar) 03/23: [fix][broker] Don't allow creating a non-persistent partitioned topic with '-partition-' in name (#23488)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 302edbafffa557fae20a7ff97b4ae68299c819dd
Author: hanmz <gu...@tencent.com>
AuthorDate: Fri Oct 23 04:28:43 2026 +0800
[fix][broker] Don't allow creating a non-persistent partitioned topic with '-partition-' in name (#23488)
Co-authored-by: Lari Hotari <lh...@users.noreply.github.com>
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 8b8f72dfd324a69ce87bfda5be20153e1aa5457e)
---
.../pulsar/broker/admin/v2/NonPersistentTopics.java | 4 ++--
.../pulsar/broker/admin/PersistentTopicsTest.java | 17 +++++++++++++++++
2 files changed, 19 insertions(+), 2 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
index d42be7bed089..726e81484781 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
@@ -218,14 +218,14 @@ public class NonPersistentTopics extends PersistentTopics {
}
// Also handles the inherited 'application/vnd.partitioned-topic-metadata+json' createPartitionedTopic
- // overload: non-persistent topics validate the topic name only.
+ // overload: non-persistent topics validate the partitioned topic name only.
@Override
protected void validateAndCreatePartitionedTopic(AsyncResponse asyncResponse, String tenant, String namespace,
String encodedTopic, int numPartitions, boolean createLocalTopicOnly, Map<String, String> properties) {
try {
validateNamespaceName(tenant, namespace);
validateGlobalNamespaceOwnership();
- validateTopicName(tenant, namespace, encodedTopic);
+ validatePartitionedTopicName(tenant, namespace, encodedTopic);
validateCreateTopic(topicName);
internalCreatePartitionedTopic(asyncResponse, numPartitions, createLocalTopicOnly, properties);
} catch (Exception e) {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
index bf17e0cad380..e59d6c1bd0da 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
@@ -2163,4 +2163,21 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
assertEquals(batchMessage.getProperties().get("BaTcH-kEy3"), "BaTcH-vAlUe3");
}
}
+
+ @Test
+ public void testCreateNonPersistentPartitionedTopic() {
+ AsyncResponse response = mock(AsyncResponse.class);
+ ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
+ nonPersistentTopic.createPartitionedTopic(response, testTenant, testNamespace, "test-topic", 3, true);
+ verify(response, timeout(5000).times(1)).resume(responseCaptor.capture());
+ Assert.assertEquals(responseCaptor.getValue().getStatus(), Response.Status.NO_CONTENT.getStatusCode());
+
+ response = mock(AsyncResponse.class);
+ ArgumentCaptor<RestException> errorCaptor = ArgumentCaptor.forClass(RestException.class);
+ nonPersistentTopic.createPartitionedTopic(response, testTenant, testNamespace, "test-topic-partition-0", 3,
+ true);
+ verify(response, timeout(5000).times(1)).resume(errorCaptor.capture());
+ Assert.assertEquals(errorCaptor.getValue().getResponse().getStatus(),
+ Response.Status.PRECONDITION_FAILED.getStatusCode());
+ }
}
(pulsar) 13/23: [fix][fn] Send Go function logs to the log topic periodically and on shutdown (#22516)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 93ef7f43ebd75dc9071ed047bf22ceb55369c0c9
Author: David Rayner <92...@users.noreply.github.com>
AuthorDate: Fri Oct 23 01:08:36 2026 +0100
[fix][fn] Send Go function logs to the log topic periodically and on shutdown (#22516)
Co-authored-by: David Rayner <da...@roke.co.uk>
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit c17f93e79ca87f00477a249a8630337ad7b7fa4f)
---
pulsar-function-go/logutil/log.go | 21 +++++-
pulsar-function-go/pf/instance.go | 11 +---
pulsar-function-go/pf/logAppender.go | 42 ++++++++++++
pulsar-function-go/pf/logAppender_test.go | 104 ++++++++++++++++++++++++++++++
4 files changed, 168 insertions(+), 10 deletions(-)
diff --git a/pulsar-function-go/logutil/log.go b/pulsar-function-go/logutil/log.go
index 75d28e4a0aea..1db77f75ea7e 100644
--- a/pulsar-function-go/logutil/log.go
+++ b/pulsar-function-go/logutil/log.go
@@ -27,6 +27,7 @@ import (
"runtime"
"sort"
"strings"
+ "sync"
log "github.com/sirupsen/logrus"
)
@@ -87,7 +88,21 @@ func Fatalf(format string, v ...interface{}) {
log.Fatalf(format, v...)
}
-var StrEntry []string
+// entries holds the formatted log entries that have not been sent to the log topic yet.
+// The hook appends to it from any goroutine, so it is guarded by entriesMutex.
+var (
+ entriesMutex sync.Mutex
+ entries []string
+)
+
+// DrainEntries returns the log entries captured since the previous call and clears the buffer.
+func DrainEntries() []string {
+ entriesMutex.Lock()
+ defer entriesMutex.Unlock()
+ drained := entries
+ entries = nil
+ return drained
+}
// modifyHook injects file name and line pos into log entry.
type contextHook struct{}
@@ -114,7 +129,9 @@ func (hook *contextHook) Fire(entry *log.Entry) error {
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}
- StrEntry = append(StrEntry, strEntry)
+ entriesMutex.Lock()
+ entries = append(entries, strEntry)
+ entriesMutex.Unlock()
return nil
}
diff --git a/pulsar-function-go/pf/instance.go b/pulsar-function-go/pf/instance.go
index 581c6d371b55..574507e70a0a 100644
--- a/pulsar-function-go/pf/instance.go
+++ b/pulsar-function-go/pf/instance.go
@@ -525,18 +525,13 @@ func (gi *goInstance) setupLogHandler() error {
}
func (gi *goInstance) addLogTopicHandler() {
- // Clear StrEntry regardless gi.context.logAppender is set or not
- defer func() {
- log.StrEntry = nil
- }()
-
+ // Drain the captured entries regardless gi.context.logAppender is set or not
if gi.context.logAppender == nil {
+ log.DrainEntries()
return
}
- for _, logByte := range log.StrEntry {
- gi.context.logAppender.Append([]byte(logByte))
- }
+ gi.context.logAppender.Flush()
}
func (gi *goInstance) closeLogTopic() {
diff --git a/pulsar-function-go/pf/logAppender.go b/pulsar-function-go/pf/logAppender.go
index 699f5514f7fa..d4d4bce21351 100644
--- a/pulsar-function-go/pf/logAppender.go
+++ b/pulsar-function-go/pf/logAppender.go
@@ -21,17 +21,25 @@ package pf
import (
"context"
+ "sync"
"time"
"github.com/apache/pulsar-client-go/pulsar"
log "github.com/apache/pulsar/pulsar-function-go/logutil"
)
+// logFlushInterval is how often the captured log entries are sent to the log topic.
+const logFlushInterval = 100 * time.Millisecond
+
type LogAppender struct {
pulsarClient pulsar.Client
logTopic string
fqn string
producer pulsar.Producer
+ // flushMutex keeps the entries in order when the instance and the flush goroutine flush at the same time.
+ flushMutex sync.Mutex
+ stopCh chan struct{}
+ doneCh chan struct{}
}
func NewLogAppender(client pulsar.Client, logTopic, fqn string) *LogAppender {
@@ -57,9 +65,38 @@ func (la *LogAppender) Start() error {
return err
}
la.producer = producer
+ la.startFlushing(logFlushInterval)
return nil
}
+// startFlushing sends the captured log entries every interval, so they don't wait for the next message.
+func (la *LogAppender) startFlushing(interval time.Duration) {
+ la.stopCh = make(chan struct{})
+ la.doneCh = make(chan struct{})
+ go func() {
+ defer close(la.doneCh)
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ la.Flush()
+ case <-la.stopCh:
+ return
+ }
+ }
+ }()
+}
+
+// Flush sends the log entries captured since the previous flush to the log topic.
+func (la *LogAppender) Flush() {
+ la.flushMutex.Lock()
+ defer la.flushMutex.Unlock()
+ for _, entry := range log.DrainEntries() {
+ la.Append([]byte(entry))
+ }
+}
+
func (la *LogAppender) Append(logByte []byte) {
ctx := context.Background()
asyncMsg := pulsar.ProducerMessage{
@@ -76,7 +113,12 @@ func (la *LogAppender) GetName() string {
return la.fqn
}
+// Stop waits for the flush goroutine to exit, sends the remaining log entries and closes the producer,
+// which waits for the pending sends.
func (la *LogAppender) Stop() {
+ close(la.stopCh)
+ <-la.doneCh
+ la.Flush()
la.producer.Close()
la.producer = nil
}
diff --git a/pulsar-function-go/pf/logAppender_test.go b/pulsar-function-go/pf/logAppender_test.go
new file mode 100644
index 000000000000..365183902e2c
--- /dev/null
+++ b/pulsar-function-go/pf/logAppender_test.go
@@ -0,0 +1,104 @@
+//
+// 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 pf
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/apache/pulsar-client-go/pulsar"
+ "github.com/stretchr/testify/assert"
+
+ log "github.com/apache/pulsar/pulsar-function-go/logutil"
+)
+
+// recordingProducer records the payloads sent to the log topic.
+type recordingProducer struct {
+ MockPulsarProducer
+ mutex sync.Mutex
+ payloads []string
+ closed bool
+}
+
+func (p *recordingProducer) SendAsync(_ context.Context, msg *pulsar.ProducerMessage,
+ _ func(pulsar.MessageID, *pulsar.ProducerMessage, error)) {
+ p.mutex.Lock()
+ defer p.mutex.Unlock()
+ p.payloads = append(p.payloads, string(msg.Payload))
+}
+
+func (p *recordingProducer) Close() {
+ p.mutex.Lock()
+ defer p.mutex.Unlock()
+ p.closed = true
+}
+
+func (p *recordingProducer) sent(text string) bool {
+ p.mutex.Lock()
+ defer p.mutex.Unlock()
+ for _, payload := range p.payloads {
+ if strings.Contains(payload, text) {
+ return true
+ }
+ }
+ return false
+}
+
+func TestLogAppenderFlushesPeriodically(t *testing.T) {
+ log.DrainEntries()
+ producer := &recordingProducer{}
+ appender := &LogAppender{producer: producer}
+ appender.startFlushing(10 * time.Millisecond)
+ defer appender.Stop()
+
+ log.Info("logged while no message is processed")
+
+ assert.Eventually(t, func() bool {
+ return producer.sent("logged while no message is processed")
+ }, 5*time.Second, 10*time.Millisecond)
+}
+
+func TestLogAppenderStopFlushesRemainingEntries(t *testing.T) {
+ log.DrainEntries()
+ producer := &recordingProducer{}
+ appender := &LogAppender{producer: producer}
+ appender.startFlushing(time.Hour)
+
+ log.Info("logged right before stopping")
+ appender.Stop()
+
+ assert.True(t, producer.sent("logged right before stopping"))
+ assert.True(t, producer.closed)
+ assert.Nil(t, appender.producer)
+}
+
+func TestAddLogTopicHandlerWithoutLogTopic(t *testing.T) {
+ log.Info("logged without a log topic")
+ instance := &goInstance{context: NewFuncContext()}
+
+ instance.addLogTopicHandler()
+
+ for _, entry := range log.DrainEntries() {
+ assert.NotContains(t, entry, "logged without a log topic")
+ }
+}
(pulsar) 12/23: [fix][broker] Fix 'rewinded' typos in PersistentDispatcherSingleActiveConsumer logs (#22021)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit f1514ba745093ecd145d5b39571b6e7b6c5c1998
Author: hanmz <gu...@tencent.com>
AuthorDate: Fri Oct 23 07:57:24 2026 +0800
[fix][broker] Fix 'rewinded' typos in PersistentDispatcherSingleActiveConsumer logs (#22021)
Signed-off-by: Matteo Merli <mm...@apache.org>
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 00d7a586054fb5bd6053952c17363012e3a4f16b)
---
.../persistent/PersistentDispatcherSingleActiveConsumer.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherSingleActiveConsumer.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherSingleActiveConsumer.java
index e8ade25c2fea..cadc65a0e24a 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherSingleActiveConsumer.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherSingleActiveConsumer.java
@@ -284,7 +284,7 @@ public class PersistentDispatcherSingleActiveConsumer extends AbstractDispatcher
} else if (readOnActiveConsumerTask != null) {
log.debug()
.attr("consumer", consumer)
- .log("Ignoring flow control message since consumer is waiting for cursor to be rewinded");
+ .log("Ignoring flow control message since consumer is waiting for cursor to be rewound");
} else {
log.debug()
.attr("consumer", consumer)
@@ -319,7 +319,7 @@ public class PersistentDispatcherSingleActiveConsumer extends AbstractDispatcher
if (readOnActiveConsumerTask != null) {
log.info()
.attr("consumer", consumer)
- .log("Ignoring reDeliverUnAcknowledgedMessages: consumer is waiting for cursor to be rewinded");
+ .log("Ignoring reDeliverUnAcknowledgedMessages: consumer is waiting for cursor to be rewound");
return;
}
cursor.cancelPendingReadRequest();
@@ -327,7 +327,7 @@ public class PersistentDispatcherSingleActiveConsumer extends AbstractDispatcher
cursor.rewind(consumer.readCompacted());
log.debug()
.attr("consumer", consumer)
- .log("Cursor rewinded, redelivering unacknowledged messages.");
+ .log("Cursor rewound, redelivering unacknowledged messages.");
readMoreEntries(consumer);
}
(pulsar) 07/23: [fix][broker] Don't redeliver individually acknowledged messages from the compacted ledger (#23495)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit dfbf329a016720cf4f28fbb198786c1ab23e142b
Author: summer <74...@users.noreply.github.com>
AuthorDate: Fri Oct 23 06:56:24 2026 +0800
[fix][broker] Don't redeliver individually acknowledged messages from the compacted ledger (#23495)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 35e839388586303a4999140e35f67baf983df793)
---
.../pulsar/compaction/CompactedTopicUtils.java | 24 +++++++++-
.../pulsar/broker/admin/TopicPoliciesTest.java | 3 +-
.../pulsar/compaction/CompactedTopicUtilsTest.java | 43 +++++++++++++++++
.../apache/pulsar/compaction/CompactionTest.java | 56 ++++++++++++++++++++++
4 files changed, 123 insertions(+), 3 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/compaction/CompactedTopicUtils.java b/pulsar-broker/src/main/java/org/apache/pulsar/compaction/CompactedTopicUtils.java
index f86d1f96a178..f956aa01ff51 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/compaction/CompactedTopicUtils.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/compaction/CompactedTopicUtils.java
@@ -50,7 +50,8 @@ public class CompactedTopicUtils {
* <p>Positions up to the compaction horizon are read from the compacted ledger, later positions from the
* original ledger. A reader that has already moved on to the original ledger must stay there even when a later
* compaction moves the horizon past its read position, or it would skip the messages compaction removed since,
- * tombstones included.
+ * tombstones included. As in the original ledger, the entries that the cursor acknowledged individually are
+ * skipped.
*
* @param originalLedgerReadPosition the position from which this reader has been reading the original ledger,
* or {@code null}. Positions at or after it are read from the original ledger
@@ -129,13 +130,15 @@ public class CompactedTopicUtils {
}
}
+ Position nextPosition = result.get(result.size() - 1).getPosition().getNext();
+ result = removeIndividuallyAcknowledged(cursor, result);
+
long entriesSize = 0;
for (Entry entry : result) {
entriesSize += entry.getLength();
}
cursor.updateReadStats(result.size(), entriesSize);
- Position nextPosition = result.get(result.size() - 1).getPosition().getNext();
cursor.seek(nextPosition, true);
notifyIfPastHorizon(nextPosition, lastCompactedPosition, onOriginalLedgerRead);
return result;
@@ -153,6 +156,23 @@ public class CompactedTopicUtils {
}
}
+ // Unlike the reads of the original ledger, the reads of the compacted ledger don't skip the entries that the
+ // subscription acknowledged individually. The entries up to the mark-delete position stay: a read from the
+ // earliest position, such as the compactor's, must return them.
+ private static List<Entry> removeIndividuallyAcknowledged(ManagedCursor cursor, List<Entry> entries) {
+ Position markDeletePosition = cursor.getMarkDeletedPosition();
+ List<Entry> result = new ArrayList<>(entries.size());
+ for (Entry entry : entries) {
+ if (cursor.isMessageDeleted(entry.getPosition())
+ && entry.getPosition().compareTo(markDeletePosition) > 0) {
+ entry.release();
+ } else {
+ result.add(entry);
+ }
+ }
+ return result;
+ }
+
// The snapshot ends when the cursor moves past the horizon: the next read goes to the original ledger.
private static void notifyIfPastHorizon(Position nextReadPosition, Position lastCompactedPosition,
@Nullable Consumer<Position> onOriginalLedgerRead) {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java
index 866588433815..514037dfb48e 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java
@@ -3810,10 +3810,11 @@ public class TopicPoliciesTest extends MockedPulsarServiceBaseTest {
CompletableFuture<Long> future2 = (CompletableFuture<Long>) field.get(persistentTopic);
Awaitility.await().untilAsserted(() -> assertTrue(future2.isDone()));
+ // A new subscription, since "sub" has already acknowledged the remaining message
consumer = pulsarClient.newConsumer()
.subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
.readCompacted(true)
- .topic(topicPoliciesTopic).subscriptionName("sub").subscribe();
+ .topic(topicPoliciesTopic).subscriptionName("sub2").subscribe();
count = 0;
while (true) {
Message<?> message = consumer.receive(1, TimeUnit.SECONDS);
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactedTopicUtilsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactedTopicUtilsTest.java
index 9570e4eb376d..0db632778ae4 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactedTopicUtilsTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactedTopicUtilsTest.java
@@ -164,6 +164,49 @@ public class CompactedTopicUtilsTest {
Assert.assertEquals(reported.get(), lastCompactedPosition.getNext());
}
+ @Test
+ public void testIndividuallyAcknowledgedEntriesAreSkipped() throws Exception {
+ // The cursor acknowledged 1:90 individually, and its mark-delete position is before the compacted entries.
+ TopicCompactionService service = mockService(PositionFactory.create(1, 100));
+ ManagedCursorImpl cursor = mockCursor(PositionFactory.create(1, 80), PositionFactory.create(1, -1));
+ Mockito.doReturn(PositionFactory.create(1, 79)).when(cursor).getMarkDeletedPosition();
+ Position acknowledgedPosition = PositionFactory.create(1, 90);
+ Mockito.doReturn(true).when(cursor).isMessageDeleted(acknowledgedPosition);
+ Entry unacknowledged = mockEntry(PositionFactory.create(1, 85));
+ Entry acknowledged = mockEntry(acknowledgedPosition);
+ Mockito.doReturn(CompletableFuture.completedFuture(new ArrayList<>(List.of(unacknowledged, acknowledged))))
+ .when(service).readCompactedEntries(Mockito.any(), Mockito.anyInt());
+
+ List<Entry> entries = CompactedTopicUtils.asyncReadCompactedEntries(service, cursor, 10, 1000,
+ PositionFactory.LATEST, false, false).get();
+
+ Assert.assertEquals(entries, List.of(unacknowledged));
+ Mockito.verify(acknowledged).release();
+ Mockito.verify(unacknowledged, Mockito.never()).release();
+ // The next read starts after the skipped entry.
+ Mockito.verify(cursor).seek(PositionFactory.create(1, 91), true);
+ }
+
+ @Test
+ public void testEntriesUpToMarkDeletePositionAreKept() throws Exception {
+ // A read from the earliest position, such as the compactor's, returns the entries up to the mark-delete
+ // position, although the cursor reports them as deleted.
+ TopicCompactionService service = mockService(PositionFactory.create(1, 100));
+ ManagedCursorImpl cursor = mockCursor(PositionFactory.create(1, 96), PositionFactory.create(1, -1));
+ Mockito.doReturn(PositionFactory.create(1, 95)).when(cursor).getMarkDeletedPosition();
+ Mockito.doReturn(true).when(cursor).isMessageDeleted(Mockito.any(Position.class));
+ Entry first = mockEntry(PositionFactory.create(1, 85));
+ Entry last = mockEntry(PositionFactory.create(1, 95));
+ Mockito.doReturn(CompletableFuture.completedFuture(new ArrayList<>(List.of(first, last))))
+ .when(service).readCompactedEntries(Mockito.any(), Mockito.anyInt());
+
+ List<Entry> entries = CompactedTopicUtils.asyncReadCompactedEntries(service, cursor, 10, 1000,
+ PositionFactory.LATEST, true, false).get();
+
+ Assert.assertEquals(entries, List.of(first, last));
+ Mockito.verify(service).readCompactedEntries(Mockito.eq(PositionFactory.EARLIEST), Mockito.anyInt());
+ }
+
private static TopicCompactionService mockService(Position lastCompactedPosition) {
TopicCompactionService service = Mockito.mock(TopicCompactionService.class);
Mockito.doReturn(CompletableFuture.completedFuture(lastCompactedPosition)).when(service)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactionTest.java
index d2f8abd4b3f7..3b1e538636cd 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactionTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactionTest.java
@@ -3099,4 +3099,60 @@ public class CompactionTest extends MockedPulsarServiceBaseTest {
assertThatThrownBy(() -> service.getLastMessagePosition().get(5, TimeUnit.SECONDS))
.isInstanceOf(ExecutionException.class).hasCauseInstanceOf(BKException.class);
}
+
+ @Test
+ public void testIndividualAcknowledgeWithReconnection() throws Exception {
+ final String topicName = newUniqueName("persistent://my-tenant/my-ns/testIndividualAcknowledge");
+ final String subName = "my-sub";
+ final int numMessages = 10;
+ final int numKeys = 4;
+ // Compaction keeps the last message of each key. The others are never delivered nor acknowledged, so the
+ // individual acks below leave the mark-delete position before the first message.
+ final int backlog = numMessages - numKeys;
+
+ pulsarClient.newConsumer().topic(topicName).subscriptionName(subName).readCompacted(true).subscribe()
+ .close();
+
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .enableBatching(false).topic(topicName).create();
+
+ Map<String, String> expected = new HashMap<>();
+ for (int i = 0; i < numMessages; i++) {
+ String key = "key-" + (i % numKeys);
+ String value = "value-" + i;
+ producer.newMessage().key(key).value(value).send();
+ expected.put(key, value);
+ }
+ compact(topicName);
+
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING).topic(topicName)
+ .subscriptionName(subName).readCompacted(true).subscribe();
+
+ Map<String, String> results = new HashMap<>();
+ for (int i = 0; i < numKeys; i++) {
+ Message<String> message = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(message);
+ results.put(message.getKey(), message.getValue());
+ consumer.acknowledge(message);
+ }
+ assertEquals(results, expected);
+ Awaitility.await().untilAsserted(() -> assertEquals(
+ admin.topics().getStats(topicName, true).getSubscriptions().get(subName).getMsgBacklog(), backlog));
+
+ // After the reconnection, the dispatcher reads the compacted ledger again before the new message
+ admin.topics().unload(topicName);
+ producer.newMessage().key("key-new").value("value-new").send();
+ Message<String> message = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(message);
+ assertEquals(message.getValue(), "value-new");
+ consumer.acknowledge(message);
+ Awaitility.await().untilAsserted(() -> assertEquals(
+ admin.topics().getStats(topicName, true).getSubscriptions().get(subName).getMsgBacklog(), backlog));
+
+ // A redelivery rewinds the cursor to the mark-delete position
+ consumer.redeliverUnacknowledgedMessages();
+ assertNull(consumer.receive(3, TimeUnit.SECONDS));
+ }
}
(pulsar) 11/23: [fix][broker] Serialize outgoing commands before passing them to broker interceptors (#27054)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 4ae80f3534d0b3d2749f1a795f9c011e97eeca1d
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 02:46:24 2026 +0300
[fix][broker] Serialize outgoing commands before passing them to broker interceptors (#27054)
(cherry picked from commit d5daf9d3210ce1de846c19690ac152c1c9ff76b9)
---
.../broker/service/PulsarCommandSenderImpl.java | 71 ++++++-------
.../service/PulsarCommandSenderImplTest.java | 110 +++++++++++++++++++++
2 files changed, 141 insertions(+), 40 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
index dcbe1e91b077..61172cf34ae7 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
@@ -70,40 +70,35 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
@Override
public void sendPartitionMetadataResponse(ServerError error, String errorMsg, long requestId) {
BaseCommand command = Commands.newPartitionMetadataResponseCommand(error, errorMsg, requestId);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendPartitionMetadataResponse(int partitions, long requestId) {
BaseCommand command = Commands.newPartitionMetadataResponseCommand(partitions, requestId);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendSuccessResponse(long requestId) {
BaseCommand command = Commands.newSuccessCommand(requestId);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.UNSUBSCRIBE, requestId, true);
}
@Override
public void sendErrorResponse(long requestId, ServerError error, String message) {
BaseCommand command = Commands.newErrorCommand(requestId, error, message);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.UNSUBSCRIBE, requestId, false);
}
@Override
public void sendProducerSuccessResponse(long requestId, String producerName, SchemaVersion schemaVersion) {
BaseCommand command = Commands.newProducerSuccessCommand(requestId, producerName, schemaVersion);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -113,8 +108,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
boolean isProducerReady) {
BaseCommand command = Commands.newProducerSuccessCommand(requestId, producerName, lastSequenceId,
schemaVersion, topicEpoch, isProducerReady);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -123,16 +117,14 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
long entryId) {
BaseCommand command = Commands.newSendReceiptCommand(producerId, sequenceId, highestId, ledgerId,
entryId);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendSendError(long producerId, long sequenceId, ServerError error, String errorMsg) {
BaseCommand command = Commands.newSendErrorCommand(producerId, sequenceId, error, errorMsg);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -152,24 +144,21 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
@Override
public void sendGetSchemaResponse(long requestId, SchemaInfo schema, SchemaVersion version) {
BaseCommand command = Commands.newGetSchemaResponseCommand(requestId, schema, version);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendGetSchemaErrorResponse(long requestId, ServerError error, String errorMessage) {
BaseCommand command = Commands.newGetSchemaResponseErrorCommand(requestId, error, errorMessage);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendGetOrCreateSchemaResponse(long requestId, SchemaVersion schemaVersion) {
BaseCommand command = Commands.newGetOrCreateSchemaResponseCommand(requestId, schemaVersion);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -177,8 +166,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
public void sendGetOrCreateSchemaErrorResponse(long requestId, ServerError error, String errorMessage) {
BaseCommand command =
Commands.newGetOrCreateSchemaResponseErrorCommand(requestId, error, errorMessage);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -187,8 +175,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
boolean supportsScalableTopics) {
BaseCommand command = Commands.newConnectedCommand(
clientProtocolVersion, maxMessageSize, supportsTopicWatchers, supportsScalableTopics);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -198,16 +185,14 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
long requestId, boolean proxyThroughServiceUrl) {
BaseCommand command = Commands.newLookupResponseCommand(brokerServiceUrl, brokerServiceUrlTls,
authoritative, response, requestId, proxyThroughServiceUrl);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@Override
public void sendLookupResponse(ServerError error, String errorMsg, long requestId) {
BaseCommand command = Commands.newLookupErrorResponseCommand(error, errorMsg, requestId);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -408,8 +393,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
@Override
public void sendTcClientConnectResponse(long requestId, ServerError error, String message) {
BaseCommand command = Commands.newTcClientConnectResponse(requestId, error, message);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -422,8 +406,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
public void sendNewTxnResponse(long requestId, TxnID txnID, long tcID) {
BaseCommand command = Commands.newTxnResponse(requestId, txnID.getLeastSigBits(),
txnID.getMostSigBits());
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
if (this.interceptor != null) {
this.interceptor.txnOpened(tcID, txnID.toString());
@@ -433,8 +416,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
@Override
public void sendNewTxnErrorResponse(long requestId, long tcID, ServerError error, String message) {
BaseCommand command = Commands.newTxnResponse(requestId, tcID, error, message);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -442,8 +424,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
public void sendEndTxnResponse(long requestId, TxnID txnID, int txnAction) {
BaseCommand command = Commands.newEndTxnResponse(requestId, txnID.getLeastSigBits(),
txnID.getMostSigBits());
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
if (this.interceptor != null) {
this.interceptor.txnEnded(txnID.toString(), txnAction);
@@ -454,8 +435,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
public void sendEndTxnErrorResponse(long requestId, TxnID txnID, ServerError error, String message) {
BaseCommand command = Commands.newEndTxnResponse(requestId, txnID.getLeastSigBits(),
txnID.getMostSigBits(), error, message);
- safeIntercept(command, cnx);
- ByteBuf outBuf = Commands.serializeWithSize(command);
+ ByteBuf outBuf = serializeAndIntercept(command);
writeAndFlush(outBuf);
}
@@ -514,6 +494,17 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
NettyChannelUtil.writeAndFlushWithVoidPromise(cnx.ctx(), outBuf);
}
+ /**
+ * Serializes the command before passing it to the interceptors, as {@link ServerCnx#newMessageAndIntercept} does:
+ * the command is usually a thread-local one, which an interceptor can reuse, for example by sending a message
+ * with a producer, and the response would then be another command.
+ */
+ private ByteBuf serializeAndIntercept(BaseCommand command) {
+ ByteBuf outBuf = Commands.serializeWithSize(command);
+ safeIntercept(command, cnx);
+ return outBuf;
+ }
+
private void safeIntercept(BaseCommand command, ServerCnx cnx) {
if (this.interceptor != null) {
try {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PulsarCommandSenderImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PulsarCommandSenderImplTest.java
new file mode 100644
index 000000000000..d0a26844ad24
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PulsarCommandSenderImplTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.embedded.EmbeddedChannel;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pulsar.broker.intercept.BrokerInterceptor;
+import org.apache.pulsar.common.api.proto.BaseCommand;
+import org.apache.pulsar.common.protocol.Commands;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class PulsarCommandSenderImplTest {
+ private EmbeddedChannel channel;
+ private PulsarCommandSenderImpl commandSender;
+ private final List<BaseCommand.Type> interceptedTypes = new ArrayList<>();
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ interceptedTypes.clear();
+ channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
+ ServerCnx cnx = mock(ServerCnx.class);
+ when(cnx.ctx()).thenReturn(channel.pipeline().firstContext());
+ // an interceptor that builds another command on the same thread, as one that sends a message with a
+ // producer does: the commands built by Commands share a thread-local instance
+ BrokerInterceptor interceptor = mock(BrokerInterceptor.class);
+ doAnswer(invocation -> {
+ BaseCommand command = invocation.getArgument(0);
+ interceptedTypes.add(command.getType());
+ Commands.newSuccess(Long.MAX_VALUE).release();
+ return null;
+ }).when(interceptor).onPulsarCommand(any(), any());
+ commandSender = new PulsarCommandSenderImpl(interceptor, cnx, null);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void cleanup() {
+ if (channel != null) {
+ channel.finishAndReleaseAll();
+ }
+ }
+
+ @Test
+ public void testSendReceiptIsNotOverwrittenByInterceptor() {
+ commandSender.sendSendReceiptResponse(1, 2, 3, 4, 5);
+
+ BaseCommand response = readResponse();
+ assertThat(interceptedTypes).containsExactly(BaseCommand.Type.SEND_RECEIPT);
+ assertThat(response.getType()).isEqualTo(BaseCommand.Type.SEND_RECEIPT);
+ assertThat(response.getSendReceipt()).satisfies(receipt -> {
+ assertThat(receipt.getProducerId()).isEqualTo(1);
+ assertThat(receipt.getSequenceId()).isEqualTo(2);
+ assertThat(receipt.getHighestSequenceId()).isEqualTo(3);
+ assertThat(receipt.getMessageId().getLedgerId()).isEqualTo(4);
+ assertThat(receipt.getMessageId().getEntryId()).isEqualTo(5);
+ });
+ }
+
+ @Test
+ public void testPartitionMetadataResponseIsNotOverwrittenByInterceptor() {
+ commandSender.sendPartitionMetadataResponse(7, 42);
+
+ BaseCommand response = readResponse();
+ assertThat(interceptedTypes).containsExactly(BaseCommand.Type.PARTITIONED_METADATA_RESPONSE);
+ assertThat(response.getType()).isEqualTo(BaseCommand.Type.PARTITIONED_METADATA_RESPONSE);
+ assertThat(response.getPartitionMetadataResponse().getRequestId()).isEqualTo(42);
+ assertThat(response.getPartitionMetadataResponse().getPartitions()).isEqualTo(7);
+ }
+
+ private BaseCommand readResponse() {
+ channel.runPendingTasks();
+ ByteBuf frame = channel.readOutbound();
+ assertThat(frame).isNotNull();
+ try {
+ frame.readInt();
+ int commandSize = frame.readInt();
+ BaseCommand command = new BaseCommand();
+ command.parseFrom(frame, commandSize);
+ return command;
+ } finally {
+ frame.release();
+ }
+ }
+}
(pulsar) 22/23: [improve][broker] Index topic watcher notifications by namespace (#26969)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 5ce6346b1c0fd44ab8dde96da5e877d6d6fcae13
Author: P_K <96...@users.noreply.github.com>
AuthorDate: Fri Oct 23 10:59:09 2026 +0530
[improve][broker] Index topic watcher notifications by namespace (#26969)
(cherry picked from commit 6dc00c31229c270e5cc67783ef041586d6155cc3)
---
.../TopicResourcesNotificationBenchmark.java | 147 ++++++++
.../pulsar/broker/resources/package-info.java | 22 ++
.../pulsar/broker/resources/TopicResources.java | 107 ++++--
.../broker/resources/TopicResourcesTest.java | 394 +++++++++++++++++++++
4 files changed, 644 insertions(+), 26 deletions(-)
diff --git a/microbench/src/main/java/org/apache/pulsar/broker/resources/TopicResourcesNotificationBenchmark.java b/microbench/src/main/java/org/apache/pulsar/broker/resources/TopicResourcesNotificationBenchmark.java
new file mode 100644
index 000000000000..0c64de1e591b
--- /dev/null
+++ b/microbench/src/main/java/org/apache/pulsar/broker/resources/TopicResourcesNotificationBenchmark.java
@@ -0,0 +1,147 @@
+/*
+ * 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.resources;
+
+import static org.apache.pulsar.common.util.Codec.decode;
+import static org.mockito.Mockito.mock;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.naming.SystemTopicNames;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * Compares indexed notification dispatch with the original per-listener namespace-pattern scan.
+ */
+@State(Scope.Thread)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = 3, time = 1)
+@Measurement(iterations = 5, time = 1)
+@Fork(1)
+public class TopicResourcesNotificationBenchmark {
+
+ @Param({"1", "100", "1000"})
+ public int namespaceCount;
+
+ @Param({"1", "10"})
+ public int watchersPerNamespace;
+
+ @Param({"TOPIC", "SUBSCRIPTION"})
+ public String notificationKind;
+
+ private TopicResources topicResources;
+ private Map<TopicListener, Pattern> originalListeners;
+ private Notification[] notifications;
+ private final AtomicInteger dispatchedEvents = new AtomicInteger();
+ private int notificationCursor;
+
+ @Setup
+ public void setup() {
+ topicResources = new TopicResources(mock(MetadataStoreExtended.class));
+ originalListeners = new ConcurrentHashMap<>();
+ notifications = new Notification[namespaceCount];
+
+ for (int namespaceIndex = 0; namespaceIndex < namespaceCount; namespaceIndex++) {
+ NamespaceName namespace = NamespaceName.get("tenant/namespace-" + namespaceIndex);
+ String namespacePath = namespace.toString();
+ String notificationPath = "/managed-ledgers/" + namespacePath + "/persistent/topic";
+ if ("SUBSCRIPTION".equals(notificationKind)) {
+ notificationPath += "/sub";
+ }
+ notifications[namespaceIndex] = new Notification(NotificationType.Created, notificationPath);
+
+ Pattern namespacePattern = Pattern.compile("/managed-ledgers/("
+ + Pattern.quote(namespacePath) + ")/(persistent)/([^/]+)");
+ for (int watcher = 0; watcher < watchersPerNamespace; watcher++) {
+ TopicListener listener = new CountingListener(namespace);
+ topicResources.registerPersistentTopicListener(listener);
+ originalListeners.put(listener, namespacePattern);
+ }
+ }
+ }
+
+ @Benchmark
+ public int indexedDispatch() {
+ topicResources.handleNotification(nextNotification());
+ return dispatchedEvents.get();
+ }
+
+ @Benchmark
+ public int linearScanBaseline() {
+ Notification notification = nextNotification();
+ for (Map.Entry<TopicListener, Pattern> entry : originalListeners.entrySet()) {
+ Matcher matcher = entry.getValue().matcher(notification.getPath());
+ if (matcher.matches()) {
+ TopicName topicName = TopicName.get(
+ matcher.group(2), NamespaceName.get(matcher.group(1)), decode(matcher.group(3)));
+ if (!SystemTopicNames.isSystemTopic(topicName)) {
+ entry.getKey().onTopicEvent(topicName.toString(), notification.getType());
+ }
+ }
+ }
+ return dispatchedEvents.get();
+ }
+
+ private Notification nextNotification() {
+ return notifications[(notificationCursor++ & Integer.MAX_VALUE) % notifications.length];
+ }
+
+ private final class CountingListener implements TopicListener {
+ private final NamespaceName namespace;
+
+ private CountingListener(NamespaceName namespace) {
+ this.namespace = namespace;
+ }
+
+ @Override
+ public NamespaceName getNamespaceName() {
+ return namespace;
+ }
+
+ @Override
+ public void onTopicEvent(String topicName, NotificationType notificationType) {
+ dispatchedEvents.incrementAndGet();
+ }
+
+ @Override
+ public void onSessionEvent(SessionEvent sessionEvent) {
+ // Session events are not part of this notification benchmark.
+ }
+ }
+}
diff --git a/microbench/src/main/java/org/apache/pulsar/broker/resources/package-info.java b/microbench/src/main/java/org/apache/pulsar/broker/resources/package-info.java
new file mode 100644
index 000000000000..e04f75221144
--- /dev/null
+++ b/microbench/src/main/java/org/apache/pulsar/broker/resources/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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.
+ */
+/**
+ * Benchmarks for broker topic-resource notification dispatch.
+ */
+package org.apache.pulsar.broker.resources;
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
index c0d3e339f42a..de8066562e06 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
@@ -19,14 +19,14 @@
package org.apache.pulsar.broker.resources;
import static org.apache.pulsar.common.util.Codec.decode;
+import com.google.common.annotations.VisibleForTesting;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import java.util.stream.Collectors;
import lombok.CustomLog;
import org.apache.pulsar.common.naming.NamespaceName;
@@ -42,16 +42,26 @@ import org.apache.pulsar.metadata.api.extended.SessionEvent;
@CustomLog
public class TopicResources {
private static final String MANAGED_LEDGER_PATH = "/managed-ledgers";
+ private static final String MANAGED_LEDGER_TOPIC_PREFIX = MANAGED_LEDGER_PATH + "/";
+ private static final String PERSISTENT_TOPIC_PATH = "/" + TopicDomain.persistent + "/";
private final MetadataStoreExtended store;
- private final Map<TopicListener, Pattern> topicListeners;
+ // Keep the global registry for listener equality and session events, and index topic notifications
+ // by namespace. Mutations to both maps are serialized; callbacks do not hold this lock.
+ private final Map<TopicListener, ListenerRegistration> topicListeners;
+ private final Map<String, Set<TopicListener>> topicListenersByNamespace;
+ private final Object listenerRegistrationLock = new Object();
private final Runnable cancelListener;
private final Runnable cancelSessionListener;
+ private record ListenerRegistration(TopicListener listener, String namespace) {
+ }
+
public TopicResources(MetadataStoreExtended store) {
this.store = store;
topicListeners = new ConcurrentHashMap<>();
+ topicListenersByNamespace = new ConcurrentHashMap<>();
cancelListener = store.registerCancellableListener(this::handleNotification);
cancelSessionListener = store.registerCancellableSessionListener(this::handleSessionEvent);
}
@@ -154,37 +164,83 @@ public class TopicResources {
}
void handleNotification(Notification notification) {
- if (topicListeners.isEmpty()) {
+ if (topicListeners.isEmpty()
+ || (notification.getType() != NotificationType.Created
+ && notification.getType() != NotificationType.Deleted)) {
return;
}
- if (notification.getPath().startsWith(MANAGED_LEDGER_PATH)
- && (notification.getType() == NotificationType.Created
- || notification.getType() == NotificationType.Deleted)) {
- for (Map.Entry<TopicListener, Pattern> entry :
- topicListeners.entrySet()) {
- Matcher matcher = entry.getValue().matcher(notification.getPath());
- if (matcher.matches()) {
- TopicName topicName = TopicName.get(
- matcher.group(2), NamespaceName.get(matcher.group(1)), decode(matcher.group(3)));
- if (!SystemTopicNames.isSystemTopic(topicName)) {
- entry.getKey().onTopicEvent(topicName.toString(), notification.getType());
- }
+
+ String path = notification.getPath();
+ if (!path.startsWith(MANAGED_LEDGER_TOPIC_PREFIX)) {
+ return;
+ }
+
+ int domainStart = path.lastIndexOf(PERSISTENT_TOPIC_PATH);
+ if (domainStart <= MANAGED_LEDGER_TOPIC_PREFIX.length()) {
+ return;
+ }
+
+ int topicStart = domainStart + PERSISTENT_TOPIC_PATH.length();
+ if (topicStart == path.length() || path.indexOf('/', topicStart) != -1) {
+ return;
+ }
+
+ String namespace = path.substring(MANAGED_LEDGER_TOPIC_PREFIX.length(), domainStart);
+ Set<TopicListener> listeners = topicListenersByNamespace.get(namespace);
+ if (listeners == null || listeners.isEmpty()) {
+ return;
+ }
+
+ TopicName topicName = TopicName.get(TopicDomain.persistent.toString(),
+ NamespaceName.get(namespace), decode(path.substring(topicStart)));
+ if (!SystemTopicNames.isSystemTopic(topicName)) {
+ String topic = topicName.toString();
+ listeners.forEach(listener -> {
+ ListenerRegistration registration = topicListeners.get(listener);
+ if (registration != null && namespace.equals(registration.namespace())) {
+ listener.onTopicEvent(topic, notification.getType());
}
+ });
+ }
+ }
+
+ public void registerPersistentTopicListener(TopicListener listener) {
+ String namespace = listener.getNamespaceName().toString();
+ synchronized (listenerRegistrationLock) {
+ ListenerRegistration previous = topicListeners.get(listener);
+ TopicListener registeredListener = previous == null ? listener : previous.listener();
+ // Publish the new index entry before switching the authoritative registration.
+ // Dispatch validates the registration, so an overlapping entry cannot deliver
+ // notifications for a namespace that is no longer registered.
+ topicListenersByNamespace.computeIfAbsent(namespace, __ -> ConcurrentHashMap.newKeySet())
+ .add(registeredListener);
+ topicListeners.put(registeredListener, new ListenerRegistration(registeredListener, namespace));
+ if (previous != null && !previous.namespace().equals(namespace)) {
+ removeFromNamespace(previous);
}
}
}
- Pattern namespaceNameToTopicNamePattern(NamespaceName namespaceName) {
- return Pattern.compile(MANAGED_LEDGER_PATH + "/(" + Pattern.quote(namespaceName.toString()) + ")/("
- + TopicDomain.persistent + ")/(" + "[^/]+)");
+ public void deregisterPersistentTopicListener(TopicListener listener) {
+ synchronized (listenerRegistrationLock) {
+ ListenerRegistration registration = topicListeners.remove(listener);
+ if (registration != null) {
+ removeFromNamespace(registration);
+ }
+ }
}
- public void registerPersistentTopicListener(TopicListener listener) {
- topicListeners.put(listener, namespaceNameToTopicNamePattern(listener.getNamespaceName()));
+ private void removeFromNamespace(ListenerRegistration registration) {
+ Set<TopicListener> listeners = topicListenersByNamespace.get(registration.namespace());
+ listeners.remove(registration.listener());
+ if (listeners.isEmpty()) {
+ topicListenersByNamespace.remove(registration.namespace());
+ }
}
- public void deregisterPersistentTopicListener(TopicListener listener) {
- topicListeners.remove(listener);
+ @VisibleForTesting
+ int namespaceListenerBucketCount() {
+ return topicListenersByNamespace.size();
}
private void handleSessionEvent(SessionEvent sessionEvent) {
@@ -204,13 +260,12 @@ public class TopicResources {
@Deprecated
public void registerPersistentTopicListener(
NamespaceName namespaceName, BiConsumer<String, NotificationType> listener) {
- topicListeners.put(new BiConsumerTopicListener(listener, namespaceName),
- namespaceNameToTopicNamePattern(namespaceName));
+ registerPersistentTopicListener(new BiConsumerTopicListener(listener, namespaceName));
}
@Deprecated
public void deregisterPersistentTopicListener(BiConsumer<String, NotificationType> listener) {
- topicListeners.remove(new BiConsumerTopicListener(listener, null));
+ deregisterPersistentTopicListener(new BiConsumerTopicListener(listener, null));
}
// for backwards compatibility with broker plugins that could be using the BiConsumer based methods
diff --git a/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java b/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
index 6a46e25f1756..92d085cca174 100644
--- a/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
+++ b/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
@@ -20,17 +20,30 @@ package org.apache.pulsar.broker.resources;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
+import java.util.function.Consumer;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.metadata.api.Notification;
import org.apache.pulsar.metadata.api.NotificationType;
import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+import org.mockito.ArgumentCaptor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -168,6 +181,351 @@ public class TopicResourcesTest {
verify(listener).onTopicEvent("persistent://tenant/name.pace/topic", NotificationType.Created);
}
+ @Test
+ public void testListenersAreDispatchedOnlyWithinTheirNamespace() {
+ TopicListener first = mock(TopicListener.class);
+ TopicListener second = mock(TopicListener.class);
+ TopicListener other = mock(TopicListener.class);
+ when(first.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace"));
+ when(second.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace"));
+ when(other.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace2"));
+ topicResources.registerPersistentTopicListener(first);
+ topicResources.registerPersistentTopicListener(second);
+ topicResources.registerPersistentTopicListener(other);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/namespace/persistent/topic"));
+
+ verify(first).onTopicEvent("persistent://tenant/namespace/topic", NotificationType.Created);
+ verify(second).onTopicEvent("persistent://tenant/namespace/topic", NotificationType.Created);
+ verify(other, never()).onTopicEvent(any(), any());
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(2);
+ }
+
+ @Test
+ public void testInvalidMetadataPathsDoNotDispatchTopicEvents() {
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace"));
+ topicResources.registerPersistentTopicListener(listener);
+
+ for (String path : List.of(
+ "/managed-ledgers/tenant/namespace/persistent/",
+ "/managed-ledgers/tenant/namespace/persistent/topic/subscription",
+ "/managed-ledgers/tenant/namespace/persistent/topic/",
+ "/managed-ledgers/tenant/namespace/non-persistent/topic",
+ "/managed-ledgers/tenant/namespace/segment/topic",
+ "/managed-ledgers/tenant/namespace/segment/topic/persistent/descriptor",
+ "/managed-ledgers-extra/tenant/namespace/persistent/topic",
+ "/managed-ledgers/tenant/cluster/ns/persistent/topic",
+ "/managed-ledgers/tenant/namespace2/persistent/topic")) {
+ topicResources.handleNotification(new Notification(NotificationType.Created, path));
+ }
+
+ verify(listener).getNamespaceName();
+ verifyNoMoreInteractions(listener);
+ }
+
+ @Test
+ public void testNamespaceNamedPersistentIsMatchedCorrectly() {
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenReturn(NamespaceName.get("tenant/persistent"));
+ topicResources.registerPersistentTopicListener(listener);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/persistent/persistent/topic"));
+
+ verify(listener).onTopicEvent("persistent://tenant/persistent/topic", NotificationType.Created);
+ }
+
+ @Test
+ public void testTopicNamedPersistentIsDispatchedButItsSubscriptionIsIgnored() {
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace"));
+ topicResources.registerPersistentTopicListener(listener);
+
+ String topicPath = "/managed-ledgers/tenant/namespace/persistent/persistent";
+ topicResources.handleNotification(new Notification(NotificationType.Created, topicPath));
+ topicResources.handleNotification(new Notification(NotificationType.Deleted, topicPath));
+ topicResources.handleNotification(new Notification(NotificationType.Created, topicPath + "/sub"));
+ topicResources.handleNotification(new Notification(NotificationType.Deleted, topicPath + "/sub"));
+
+ verify(listener).getNamespaceName();
+ verify(listener).onTopicEvent("persistent://tenant/namespace/persistent", NotificationType.Created);
+ verify(listener).onTopicEvent("persistent://tenant/namespace/persistent", NotificationType.Deleted);
+ verifyNoMoreInteractions(listener);
+ }
+
+ @Test
+ public void testNamespaceAndTopicBothNamedPersistentDoNotConfusePathParsing() {
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenReturn(NamespaceName.get("tenant/persistent"));
+ topicResources.registerPersistentTopicListener(listener);
+
+ String topicPath = "/managed-ledgers/tenant/persistent/persistent/persistent";
+ topicResources.handleNotification(new Notification(NotificationType.Created, topicPath));
+ topicResources.handleNotification(new Notification(NotificationType.Created, topicPath + "/sub"));
+
+ verify(listener).getNamespaceName();
+ verify(listener).onTopicEvent("persistent://tenant/persistent/persistent", NotificationType.Created);
+ verifyNoMoreInteractions(listener);
+ }
+
+ @Test
+ public void testEqualListenerReregistrationMovesNamespaceAndRetainsOriginalCallback() {
+ CountingTopicListener original = new CountingTopicListener("same", NamespaceName.get("tenant/first"));
+ CountingTopicListener replacement = new CountingTopicListener("same", NamespaceName.get("tenant/second"));
+ topicResources.registerPersistentTopicListener(original);
+ topicResources.registerPersistentTopicListener(replacement);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/old"));
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/second/persistent/new"));
+
+ assertThat(original.events.get()).isEqualTo(1);
+ assertThat(replacement.events.get()).isZero();
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+
+ topicResources.deregisterPersistentTopicListener(replacement);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
+ @Test
+ public void testEqualListenerReregistrationInSameNamespaceDoesNotDuplicateCallbacks() {
+ NamespaceName namespace = NamespaceName.get("tenant/namespace");
+ CountingTopicListener original = new CountingTopicListener("same", namespace);
+ CountingTopicListener replacement = new CountingTopicListener("same", namespace);
+ topicResources.registerPersistentTopicListener(original);
+ topicResources.registerPersistentTopicListener(replacement);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/namespace/persistent/topic"));
+
+ assertThat(original.events.get()).isEqualTo(1);
+ assertThat(replacement.events.get()).isZero();
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+ }
+
+ @Test
+ public void testRepeatedNamespaceMigrationKeepsOriginalListenerAndReleasesOldBuckets() {
+ CountingTopicListener original = new CountingTopicListener("same", NamespaceName.get("tenant/first"));
+ CountingTopicListener second = new CountingTopicListener("same", NamespaceName.get("tenant/second"));
+ topicResources.registerPersistentTopicListener(original);
+ topicResources.registerPersistentTopicListener(second);
+ topicResources.registerPersistentTopicListener(original);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/second/persistent/old"));
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/current"));
+
+ assertThat(original.events.get()).isEqualTo(1);
+ assertThat(second.events.get()).isZero();
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+
+ topicResources.deregisterPersistentTopicListener(second);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
+ @Test
+ public void testListenerCanMigrateNamespaceDuringNotification() {
+ NamespaceName first = NamespaceName.get("tenant/first");
+ NamespaceName second = NamespaceName.get("tenant/second");
+ AtomicReference<NamespaceName> namespace = new AtomicReference<>(first);
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenAnswer(__ -> namespace.get());
+ doAnswer(__ -> {
+ namespace.set(second);
+ topicResources.registerPersistentTopicListener(listener);
+ return null;
+ }).when(listener).onTopicEvent("persistent://tenant/first/topic", NotificationType.Created);
+ topicResources.registerPersistentTopicListener(listener);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/topic"));
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/stale"));
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/second/persistent/current"));
+
+ verify(listener).onTopicEvent("persistent://tenant/first/topic", NotificationType.Created);
+ verify(listener, never()).onTopicEvent("persistent://tenant/first/stale", NotificationType.Created);
+ verify(listener).onTopicEvent("persistent://tenant/second/current", NotificationType.Created);
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+ }
+
+ @Test(timeOut = 15000)
+ public void testConcurrentNamespaceMigrationsAndNotifications() throws Exception {
+ NamespaceName first = NamespaceName.get("tenant/first");
+ NamespaceName second = NamespaceName.get("tenant/second");
+ AtomicReference<NamespaceName> namespace = new AtomicReference<>(first);
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenAnswer(__ -> namespace.get());
+ AtomicInteger eventCount = new AtomicInteger();
+ doAnswer(__ -> {
+ eventCount.incrementAndGet();
+ return null;
+ }).when(listener).onTopicEvent(any(), any());
+ topicResources.registerPersistentTopicListener(listener);
+
+ Notification firstNotification = new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/topic");
+ Notification secondNotification = new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/second/persistent/topic");
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<?> migration = executor.submit(() -> {
+ start.await();
+ for (int i = 0; i < 2000; i++) {
+ namespace.set((i & 1) == 0 ? second : first);
+ topicResources.registerPersistentTopicListener(listener);
+ }
+ return null;
+ });
+ Future<?> notifications = executor.submit(() -> {
+ start.await();
+ for (int i = 0; i < 2000; i++) {
+ topicResources.handleNotification(firstNotification);
+ topicResources.handleNotification(secondNotification);
+ }
+ return null;
+ });
+ start.countDown();
+ migration.get(10, TimeUnit.SECONDS);
+ notifications.get(10, TimeUnit.SECONDS);
+ } finally {
+ executor.shutdownNow();
+ }
+
+ namespace.set(first);
+ topicResources.registerPersistentTopicListener(listener);
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+ int previousEvents = eventCount.get();
+ topicResources.handleNotification(secondNotification);
+ assertThat(eventCount.get()).isEqualTo(previousEvents);
+ topicResources.handleNotification(firstNotification);
+ assertThat(eventCount.get()).isEqualTo(previousEvents + 1);
+ topicResources.deregisterPersistentTopicListener(listener);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
+ @Test
+ public void testRemovingLastListenerReleasesNamespaceBucket() {
+ TopicListener first = mock(TopicListener.class);
+ TopicListener second = mock(TopicListener.class);
+ when(first.getNamespaceName()).thenReturn(NamespaceName.get("tenant/one"));
+ when(second.getNamespaceName()).thenReturn(NamespaceName.get("tenant/two"));
+ topicResources.registerPersistentTopicListener(first);
+ topicResources.registerPersistentTopicListener(second);
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(2);
+
+ topicResources.deregisterPersistentTopicListener(first);
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+ topicResources.deregisterPersistentTopicListener(second);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+
+ topicResources.registerPersistentTopicListener(first);
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/one/persistent/recreated"));
+ verify(first).onTopicEvent("persistent://tenant/one/recreated", NotificationType.Created);
+ }
+
+ @SuppressWarnings({"deprecation", "unchecked"})
+ @Test
+ public void testLegacyBiConsumerReregistrationMovesNamespace() {
+ BiConsumer<String, NotificationType> callback = mock(BiConsumer.class);
+ topicResources.registerPersistentTopicListener(NamespaceName.get("tenant/first"), callback);
+ topicResources.registerPersistentTopicListener(NamespaceName.get("tenant/second"), callback);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/first/persistent/old"));
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/second/persistent/new"));
+
+ verify(callback).accept("persistent://tenant/second/new", NotificationType.Created);
+ verifyNoMoreInteractions(callback);
+ assertThat(topicResources.namespaceListenerBucketCount()).isEqualTo(1);
+
+ topicResources.deregisterPersistentTopicListener(callback);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Test
+ public void testSessionEventsReachAllNamespacesWhenOneListenerFails() {
+ TopicListener failing = mock(TopicListener.class);
+ TopicListener healthy = mock(TopicListener.class);
+ when(failing.getNamespaceName()).thenReturn(NamespaceName.get("tenant/one"));
+ when(healthy.getNamespaceName()).thenReturn(NamespaceName.get("tenant/two"));
+ topicResources.registerPersistentTopicListener(failing);
+ topicResources.registerPersistentTopicListener(healthy);
+ doThrow(new IllegalStateException("test failure"))
+ .when(failing).onSessionEvent(SessionEvent.Reconnected);
+
+ ArgumentCaptor<Consumer<SessionEvent>> sessionListener = ArgumentCaptor.forClass(Consumer.class);
+ verify(metadataStore).registerCancellableSessionListener(sessionListener.capture());
+ sessionListener.getValue().accept(SessionEvent.Reconnected);
+
+ verify(failing).onSessionEvent(SessionEvent.Reconnected);
+ verify(healthy).onSessionEvent(SessionEvent.Reconnected);
+ }
+
+ @Test
+ public void testListenerCanDeregisterItselfDuringNotification() {
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.getNamespaceName()).thenReturn(NamespaceName.get("tenant/namespace"));
+ doAnswer(__ -> {
+ topicResources.deregisterPersistentTopicListener(listener);
+ return null;
+ }).when(listener).onTopicEvent(any(), any());
+ topicResources.registerPersistentTopicListener(listener);
+
+ topicResources.handleNotification(new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/namespace/persistent/topic"));
+
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
+ @Test(timeOut = 15000)
+ public void testConcurrentRegistrationsAndNotifications() throws Exception {
+ CountingTopicListener listener = new CountingTopicListener("concurrent", NamespaceName.get("tenant/namespace"));
+ Notification notification = new Notification(NotificationType.Created,
+ "/managed-ledgers/tenant/namespace/persistent/topic");
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<?> registration = executor.submit(() -> {
+ start.await();
+ for (int i = 0; i < 2000; i++) {
+ topicResources.registerPersistentTopicListener(listener);
+ topicResources.deregisterPersistentTopicListener(listener);
+ }
+ return null;
+ });
+ Future<?> notifications = executor.submit(() -> {
+ start.await();
+ for (int i = 0; i < 2000; i++) {
+ topicResources.handleNotification(notification);
+ }
+ return null;
+ });
+ start.countDown();
+ registration.get(10, TimeUnit.SECONDS);
+ notifications.get(10, TimeUnit.SECONDS);
+ } finally {
+ executor.shutdownNow();
+ }
+
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ topicResources.registerPersistentTopicListener(listener);
+ int eventsBefore = listener.events.get();
+ topicResources.handleNotification(notification);
+ assertThat(listener.events.get()).isEqualTo(eventsBefore + 1);
+ topicResources.deregisterPersistentTopicListener(listener);
+ assertThat(topicResources.namespaceListenerBucketCount()).isZero();
+ }
+
@SuppressWarnings({"deprecation", "unchecked"})
@Test
public void testBiConsumerListenerNotInvokedAfterDeregistered() {
@@ -198,4 +556,40 @@ public class TopicResourcesTest {
"segment://tenant/namespace/topic/8000-ffff-2",
"segment://tenant/namespace/my topic/0000-ffff-0");
}
+
+ private static final class CountingTopicListener implements TopicListener {
+ private final String identity;
+ private final NamespaceName namespace;
+ private final AtomicInteger events = new AtomicInteger();
+
+ private CountingTopicListener(String identity, NamespaceName namespace) {
+ this.identity = identity;
+ this.namespace = namespace;
+ }
+
+ @Override
+ public NamespaceName getNamespaceName() {
+ return namespace;
+ }
+
+ @Override
+ public void onTopicEvent(String topicName, NotificationType notificationType) {
+ events.incrementAndGet();
+ }
+
+ @Override
+ public void onSessionEvent(SessionEvent sessionEvent) {
+ // No session state is required by these test listeners.
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof CountingTopicListener other && identity.equals(other.identity);
+ }
+
+ @Override
+ public int hashCode() {
+ return identity.hashCode();
+ }
+ }
}
(pulsar) 06/23: [fix][broker] Don't count unread fixed-delay entries in msgBacklogNoDelayed (#23353)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 8db7583d0c7d34cad620a53811a6c284ebdca3b1
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Oct 23 06:43:00 2026 +0800
[fix][broker] Don't count unread fixed-delay entries in msgBacklogNoDelayed (#23353)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit bfe6650db0d283c223205c84aa171da6ff9c36e9)
---
...tractPersistentDispatcherMultipleConsumers.java | 6 ++
.../PersistentDispatcherMultipleConsumers.java | 10 ++
.../service/persistent/PersistentSubscription.java | 6 ++
.../stats/prometheus/NamespaceStatsAggregator.java | 2 +-
.../DelayedDeliveryFixedDelayStatsTest.java | 119 +++++++++++++++++++++
5 files changed, 142 insertions(+), 1 deletion(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/AbstractPersistentDispatcherMultipleConsumers.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/AbstractPersistentDispatcherMultipleConsumers.java
index 911e5a2d2abf..d31cc90dc96d 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/AbstractPersistentDispatcherMultipleConsumers.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/AbstractPersistentDispatcherMultipleConsumers.java
@@ -108,6 +108,12 @@ public abstract class AbstractPersistentDispatcherMultipleConsumers extends Abst
public abstract long getNumberOfMessagesInReplay();
+ /**
+ * Whether reads are paused because the delayed delivery tracker detected that all messages have a fixed delay,
+ * so that the entries not read yet are delayed messages too.
+ */
+ public abstract boolean isReadPausedByDelayTracker();
+
public abstract boolean isHavePendingRead();
public abstract boolean isHavePendingReplayRead();
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
index 41b4869161fb..d61f4f5fc1e9 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
@@ -104,6 +104,9 @@ public class PersistentDispatcherMultipleConsumers extends AbstractPersistentDis
private volatile CompletableFuture<Void> delayedDeliveryTrackerCreateFuture = null;
// Guarded by this. A concurrent map only so that stats can read its size without taking the dispatcher lock.
private final Map<Position, Long> messagesPendingDelayedDeliveryTracker = new ConcurrentHashMap<>();
+ // Whether the last read pass was skipped because the tracker paused all deliveries, i.e. it detected fixed delays
+ // and the entries not read yet are delayed too. Volatile so that stats can read it without the dispatcher lock.
+ private volatile boolean readPausedByDelayTracker = false;
private final Backoff delayedDeliveryTrackerCreateBackoff = Backoff.builder()
.initialDelay(Duration.ofSeconds(1))
.maxBackoff(Duration.ofMinutes(1))
@@ -402,9 +405,11 @@ public class PersistentDispatcherMultipleConsumers extends AbstractPersistentDis
shouldRewindBeforeReadingOrReplaying = false;
}
if (shouldPauseDeliveryForDelayTracker()) {
+ readPausedByDelayTracker = delayedDeliveryTrackerCreateFuture == null;
log.debug("Skipping read due to pause delivery for delay tracker");
return;
}
+ readPausedByDelayTracker = false;
if (topic.isTransferring()) {
// Do not deliver messages for topics that are undergoing transfer, as the acknowledgments would be ignored.
return;
@@ -1620,6 +1625,11 @@ public class PersistentDispatcherMultipleConsumers extends AbstractPersistentDis
|| delayedDeliveryTracker.map(DelayedDeliveryTracker::shouldPauseAllDeliveries).orElse(false);
}
+ @Override
+ public boolean isReadPausedByDelayTracker() {
+ return readPausedByDelayTracker;
+ }
+
@Override
public long getNumberOfDelayedMessages() {
return delayedDeliveryTracker.map(DelayedDeliveryTracker::getNumberOfDelayedMessages).orElse(0L)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentSubscription.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentSubscription.java
index 3facfbcd8067..52e0d0e1f227 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentSubscription.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentSubscription.java
@@ -1568,6 +1568,12 @@ public class PersistentSubscription extends AbstractSubscription {
subStats.backlogSize = -1;
}
subStats.msgBacklogNoDelayed = subStats.msgBacklog - subStats.msgDelayed;
+ if (Subscription.isIndividualAckMode(subType)
+ && dispatcher instanceof AbstractPersistentDispatcherMultipleConsumers d
+ && d.isReadPausedByDelayTracker()) {
+ // The tracker only holds the delayed messages read so far: the entries not read yet are delayed too
+ subStats.msgBacklogNoDelayed = Math.max(0, subStats.msgBacklogNoDelayed - cursor.getNumberOfEntries());
+ }
subStats.msgRateExpired = expiryMonitor.getMessageExpiryRate();
subStats.msgExpired = expiryMonitor.getMessageExpiryCount();
subStats.totalMsgExpired = expiryMonitor.getTotalMessageExpired();
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/NamespaceStatsAggregator.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/NamespaceStatsAggregator.java
index 8185967ccb26..79f039a2aa65 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/NamespaceStatsAggregator.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/NamespaceStatsAggregator.java
@@ -159,7 +159,7 @@ public class NamespaceStatsAggregator {
subsStats.msgInReplay = subscriptionStats.msgInReplay;
subsStats.msgRateExpired = subscriptionStats.msgRateExpired;
subsStats.totalMsgExpired = subscriptionStats.totalMsgExpired;
- subsStats.msgBacklogNoDelayed = subsStats.msgBacklog - subsStats.msgDelayed;
+ subsStats.msgBacklogNoDelayed = subscriptionStats.msgBacklogNoDelayed;
subsStats.lastExpireTimestamp = subscriptionStats.lastExpireTimestamp;
subsStats.lastAckedTimestamp = subscriptionStats.lastAckedTimestamp;
subsStats.lastConsumedFlowTimestamp = subscriptionStats.lastConsumedFlowTimestamp;
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryFixedDelayStatsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryFixedDelayStatsTest.java
new file mode 100644
index 000000000000..a9a830faf899
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryFixedDelayStatsTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.service.persistent;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import lombok.Cleanup;
+import org.apache.pulsar.broker.BrokerTestUtil;
+import org.apache.pulsar.client.api.Consumer;
+import org.apache.pulsar.client.api.Message;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.ProducerConsumerBase;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.SubscriptionType;
+import org.apache.pulsar.common.policies.data.SubscriptionStats;
+import org.awaitility.Awaitility;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class DelayedDeliveryFixedDelayStatsTest extends ProducerConsumerBase {
+
+ private static final int FIXED_DELAY_DETECTION_LOOKAHEAD = 10;
+
+ @Override
+ @BeforeClass
+ public void setup() throws Exception {
+ conf.setDelayedDeliveryFixedDelayDetectionLookahead(FIXED_DELAY_DETECTION_LOOKAHEAD);
+ super.internalSetup();
+ super.producerBaseSetup();
+ }
+
+ @Override
+ @AfterClass(alwaysRun = true)
+ public void cleanup() throws Exception {
+ super.internalCleanup();
+ }
+
+ @Test
+ public void testMsgBacklogNoDelayedWhenReadsPausedForFixedDelays() throws Exception {
+ final String topic = BrokerTestUtil.newUniqueName("persistent://public/default/fixed-delay-stats");
+ final String subName = "sub";
+ final int numNotDelayed = 15;
+ final int numDelayed = FIXED_DELAY_DETECTION_LOOKAHEAD * 10;
+
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topic)
+ .subscriptionName(subName)
+ .subscriptionType(SubscriptionType.Shared)
+ // Few permits, so that the dispatcher reads the delayed messages a few at a time
+ .receiverQueueSize(numNotDelayed + 5)
+ .subscribe();
+
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topic)
+ .enableBatching(false)
+ .create();
+ for (int i = 0; i < numNotDelayed; i++) {
+ producer.send("not-delayed-" + i);
+ }
+ // The same delay for all messages makes the tracker pause reads once it holds the lookahead
+ for (int i = 0; i < numDelayed; i++) {
+ producer.newMessage().value("delayed-" + i).deliverAfter(1, TimeUnit.HOURS).send();
+ }
+
+ List<Message<String>> received = new ArrayList<>();
+ for (int i = 0; i < numNotDelayed; i++) {
+ Message<String> msg = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(msg);
+ received.add(msg);
+ }
+
+ PersistentTopic persistentTopic =
+ (PersistentTopic) pulsar.getBrokerService().getTopicReference(topic).get();
+ AbstractPersistentDispatcherMultipleConsumers dispatcher =
+ (AbstractPersistentDispatcherMultipleConsumers) persistentTopic.getSubscription(subName)
+ .getDispatcher();
+ Awaitility.await().until(dispatcher::isReadPausedByDelayTracker);
+
+ SubscriptionStats stats = admin.topics().getStats(topic).getSubscriptions().get(subName);
+ assertEquals(stats.getMsgBacklog(), numNotDelayed + numDelayed);
+ // Only the delayed messages read so far are tracked
+ assertTrue(stats.getMsgDelayed() >= FIXED_DELAY_DETECTION_LOOKAHEAD, "msgDelayed=" + stats.getMsgDelayed());
+ assertTrue(stats.getMsgDelayed() < numDelayed, "msgDelayed=" + stats.getMsgDelayed());
+ assertEquals(stats.getMsgBacklogNoDelayed(), numNotDelayed);
+
+ for (Message<String> msg : received) {
+ consumer.acknowledge(msg);
+ }
+ Awaitility.await().untilAsserted(() -> {
+ SubscriptionStats s = admin.topics().getStats(topic).getSubscriptions().get(subName);
+ assertEquals(s.getMsgBacklog(), numDelayed);
+ assertEquals(s.getMsgBacklogNoDelayed(), 0);
+ });
+ }
+}
(pulsar) 17/23: [fix][broker] Don't swap the local metadata store's synchronizer when configurationMetadataSyncEventTopic is updated on a shared store (#22695)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit d8f3da9d71edab9f368bdee6d042673074aa0849
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Oct 23 09:41:48 2026 +0800
[fix][broker] Don't swap the local metadata store's synchronizer when configurationMetadataSyncEventTopic is updated on a shared store (#22695)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit ec8456bb04397538de7f678f5c4700d9bb3a1360)
---
.../org/apache/pulsar/broker/PulsarService.java | 17 +++++
.../pulsar/broker/admin/impl/BrokersBase.java | 6 ++
.../SyncConfigStoreSharedWithLocalTest.java | 89 ++++++++++++++++++++++
3 files changed, 112 insertions(+)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/PulsarService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/PulsarService.java
index 0bfeeb4e9a5e..8da321abf029 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/PulsarService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/PulsarService.java
@@ -2451,6 +2451,14 @@ public class PulsarService implements AutoCloseable, ShutdownService {
}
}
+ /**
+ * Whether the configuration metadata store and the local metadata store are the same instance, which happens
+ * when both use the same URL.
+ */
+ public boolean isConfigurationMetadataStoreSharedWithLocal() {
+ return configurationMetadataStore == localMetadataStore;
+ }
+
public void initConfigMetadataSynchronizerIfNeeded() {
mutex.lock();
try {
@@ -2464,6 +2472,15 @@ public class PulsarService implements AutoCloseable, ShutdownService {
+ " does not support.");
return;
}
+ // Skip if the configuration metadata store is the local one: swapping its synchronizer would make every
+ // local metadata write depend on the configuration sync topic.
+ if (isConfigurationMetadataStoreSharedWithLocal()) {
+ log.warn()
+ .attr("topic", newTopic)
+ .log("Skip to update Metadata Synchronizer because the Configuration Metadata Store is the"
+ + " same as the Local Metadata Store.");
+ return;
+ }
// Skip if no changes.
// case-1: both null.
// case-2: both topics are the same.
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/BrokersBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/BrokersBase.java
index 12ab07609757..d38484492365 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/BrokersBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/BrokersBase.java
@@ -342,6 +342,12 @@ public class BrokersBase extends AdminResource {
return FutureUtil
.failedFuture(new RestException(Status.PRECONDITION_FAILED, " Invalid dynamic-config value"));
}
+ if ("configurationMetadataSyncEventTopic".equals(configName)
+ && pulsar().isConfigurationMetadataStoreSharedWithLocal()) {
+ return FutureUtil.failedFuture(new RestException(Status.PRECONDITION_FAILED,
+ "Can't update configurationMetadataSyncEventTopic because the configuration metadata store is"
+ + " the same as the local metadata store"));
+ }
if (pulsar().getBrokerService().isDynamicConfiguration(configName)) {
return dynamicConfigurationResources().setDynamicConfigurationWithCreateAsync(old -> {
Map<String, String> configurationMap = old.orElseGet(Maps::newHashMap);
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SyncConfigStoreSharedWithLocalTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SyncConfigStoreSharedWithLocalTest.java
new file mode 100644
index 000000000000..8edf063584d0
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SyncConfigStoreSharedWithLocalTest.java
@@ -0,0 +1,89 @@
+/*
+ * 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.service;
+
+import static org.apache.pulsar.common.naming.NamespaceName.SYSTEM_NAMESPACE;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.common.naming.TopicDomain;
+import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble;
+import org.apache.pulsar.zookeeper.ZookeeperServerTest;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+/**
+ * Covers brokers whose configuration metadata store URL is the same as the local one, so both use one store instance.
+ */
+@Test(groups = "broker")
+public class SyncConfigStoreSharedWithLocalTest extends GeoReplicationWithConfigurationSyncTestBase {
+
+ private static final String CONF_NAME_SYNC_EVENT_TOPIC = "configurationMetadataSyncEventTopic";
+ private static final String SYNC_EVENT_TOPIC = TopicDomain.persistent.value() + "://" + SYSTEM_NAMESPACE
+ + "/__sync_config_meta";
+
+ @Override
+ @BeforeClass(alwaysRun = true, timeOut = 300000)
+ public void setup() throws Exception {
+ super.setup();
+ }
+
+ @Override
+ @AfterClass(alwaysRun = true, timeOut = 300000)
+ public void cleanup() throws Exception {
+ super.cleanup();
+ }
+
+ @Override
+ protected void setConfigDefaults(ServiceConfiguration config, String clusterName,
+ LocalBookkeeperEnsemble bookkeeperEnsemble, ZookeeperServerTest brokerConfigZk) {
+ super.setConfigDefaults(config, clusterName, bookkeeperEnsemble, brokerConfigZk);
+ config.setConfigurationMetadataStoreUrl(config.getMetadataStoreUrl());
+ }
+
+ @Test
+ public void testRejectDynamicUpdateOfConfigurationMetadataSyncEventTopic() throws Exception {
+ assertTrue(pulsar1.isConfigurationMetadataStoreSharedWithLocal());
+
+ assertThrows(PulsarAdminException.PreconditionFailedException.class,
+ () -> admin1.brokers().updateDynamicConfiguration(CONF_NAME_SYNC_EVENT_TOPIC, SYNC_EVENT_TOPIC));
+ assertFalse(admin1.brokers().getAllDynamicConfigurations().containsKey(CONF_NAME_SYNC_EVENT_TOPIC));
+ }
+
+ @Test
+ public void testSkipSynchronizerSwapKeepsLocalWritesWorking() throws Exception {
+ // The value can still reach the broker without the admin endpoint, e.g. persisted before an upgrade.
+ pulsar1.getConfig().setConfigurationMetadataSyncEventTopic(SYNC_EVENT_TOPIC);
+ try {
+ pulsar1.initConfigMetadataSynchronizerIfNeeded();
+ assertNull(pulsar1.getConfigMetadataSynchronizer());
+
+ // Without the guard, these writes fail because the shared store waits for the sync topic producer.
+ admin1.namespaces().createNamespace(defaultTenant + "/ns-after-sync-skip");
+ admin1.topics().createNonPartitionedTopic(
+ "persistent://" + defaultTenant + "/ns-after-sync-skip/tp-after-sync-skip");
+ } finally {
+ pulsar1.getConfig().setConfigurationMetadataSyncEventTopic(null);
+ }
+ }
+}
(pulsar) 05/23: [fix][ml] Move the read position atomically when a replay is at it (#22803)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 80f000b03aa45d99b5c4cccd91535526a7f04b8f
Author: 道君- Tao Jiuming <da...@apache.org>
AuthorDate: Fri Oct 23 06:37:10 2026 +0800
[fix][ml] Move the read position atomically when a replay is at it (#22803)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 551a0c91e2e4ec6efb2ec5b37ab6d1c1d4548b64)
---
.../bookkeeper/mledger/impl/ManagedCursorImpl.java | 18 ++++---
.../bookkeeper/mledger/impl/ManagedCursorTest.java | 57 ++++++++++++++++++++++
2 files changed, 69 insertions(+), 6 deletions(-)
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
index 4311e408c983..9a86cdb6f962 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
@@ -1971,12 +1971,18 @@ public class ManagedCursorImpl implements ManagedCursor {
List<Position> validPositions = new ArrayList<>(totalValidPositions);
positions.stream().filter(position -> !alreadyAcknowledgedPositions.contains(position))
.forEach(p ->{
- if (p.compareTo(this.readPosition) == 0) {
- this.setReadPosition(this.readPosition.getNext());
- log.warn()
- .attr("replayPosition", p)
- .attr("readPosition", this.readPosition)
- .log("Replay position equals read position, setting next readPosition");
+ // A normal read can complete concurrently and move the read position past p: only move it from p
+ // to the next position atomically, so that it never goes backward nor skips an entry
+ Position currentReadPosition = this.readPosition;
+ if (p.compareTo(currentReadPosition) == 0) {
+ Position nextReadPosition = p.getNext();
+ if (READ_POSITION_UPDATER.compareAndSet(this, currentReadPosition, nextReadPosition)) {
+ ledger.onCursorReadPositionUpdated(this, nextReadPosition);
+ log.warn()
+ .attr("replayPosition", p)
+ .attr("readPosition", nextReadPosition)
+ .log("Replay position equals read position, setting next readPosition");
+ }
}
validPositions.add(p);
});
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java
index 8a852e8ab3a5..ff6908d75ed7 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java
@@ -4178,6 +4178,63 @@ public class ManagedCursorTest extends MockedBookKeeperTestCase {
}
}
+ @Test(timeOut = 20000)
+ void testReplayAtReadPositionMovesReadPositionForwardOnce() throws Exception {
+ ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("test_replay_at_read_position");
+ ManagedCursorImpl cursor = (ManagedCursorImpl) ledger.openCursor("c1");
+ List<Position> added = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ added.add(ledger.addEntry(("entry-" + i).getBytes(Encoding)));
+ }
+ assertEquals(cursor.getReadPosition(), added.get(0));
+
+ // a replay of the read position moves it to the next position, so that a normal read doesn't read it again
+ cursor.replayEntries(Set.of(added.get(0))).forEach(Entry::release);
+ assertEquals(cursor.getReadPosition(), added.get(1));
+
+ // a normal read of the entries 1 and 2 completes while a replay of the entry 1 compares it with the read
+ // position: the replay must neither move the read position back to the entry 2 nor past the entry 3
+ Position afterNormalRead = added.get(2).getNext();
+ Position replayed = added.get(1);
+ AtomicBoolean normalReadCompleted = new AtomicBoolean();
+ Position racingReplayPosition = new Position() {
+ @Override
+ public long getLedgerId() {
+ return replayed.getLedgerId();
+ }
+
+ @Override
+ public long getEntryId() {
+ return replayed.getEntryId();
+ }
+
+ @Override
+ public int compareTo(Position that) {
+ int result = replayed.compareTo(that);
+ if (that == cursor.readPosition && normalReadCompleted.compareAndSet(false, true)) {
+ cursor.setReadPosition(afterNormalRead);
+ }
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return replayed.equals(obj);
+ }
+
+ @Override
+ public int hashCode() {
+ return replayed.hashCode();
+ }
+ };
+ List<Entry> entries = cursor.replayEntries(Set.of(racingReplayPosition));
+ assertEquals(entries.size(), 1);
+ assertEquals(new String(entries.get(0).getData(), Encoding), "entry-1");
+ entries.forEach(Entry::release);
+ assertTrue(normalReadCompleted.get());
+ assertEquals(cursor.getReadPosition(), afterNormalRead);
+ }
+
@Test(timeOut = 20000)
void testReadsOfAnInactiveCursorAreNotCached() throws Exception {
ManagedLedgerConfig config = initManagedLedgerConfig(defaultConfig());
(pulsar) 15/23: [improve][conf] Add BookKeeper DirectIO entry logger settings to bookkeeper.conf (#20929)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit a0f1d2c292c665c4684d11e9f0f534adc2e55453
Author: grayson <91...@qq.com>
AuthorDate: Fri Oct 23 09:39:26 2026 +0800
[improve][conf] Add BookKeeper DirectIO entry logger settings to bookkeeper.conf (#20929)
Co-authored-by: graysonzeng <gr...@tencent.com>
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 474bd7ab860328b2c9b611122474b04853398b49)
---
conf/bookkeeper.conf | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/conf/bookkeeper.conf b/conf/bookkeeper.conf
index 29b1be30d46e..8dfbb0cb7cb1 100644
--- a/conf/bookkeeper.conf
+++ b/conf/bookkeeper.conf
@@ -768,6 +768,29 @@ dbStorage_readAheadCacheMaxSizeMb=
# redelivered one, costs as many entry reads as this. 100 keeps most of the benefit for sequential reads.
dbStorage_readAheadCacheBatchSize=100
+## DirectIO entry logger
+## Writes and reads the entry log files with O_DIRECT, bypassing the OS page cache.
+## It needs the BookKeeper native-io library, which is only available on Linux
+## (x86_64 and aarch64, glibc).
+
+# Enable the DirectIO entry logger instead of the default entry logger.
+dbStorage_directIOEntryLogger=false
+
+# Total size of the write buffers, in MB, split evenly across the ledger directories.
+# By default it will be allocated to 1/8th of the available direct memory
+dbStorage_directIOEntryLoggerTotalWriteBufferSizeMB=
+
+# Total size of the read buffers, in MB, split evenly across the ledger directories.
+# By default it will be allocated to 1/8th of the available direct memory
+dbStorage_directIOEntryLoggerTotalReadBufferSizeMB=
+
+# Size, in MB, of the buffer each reader uses to read from an entry log file.
+# Each entry log file has one reader.
+dbStorage_directIOEntryLoggerReadBufferSizeMB=8
+
+# How long, in seconds, a reader for an entry log file stays cached after its last access.
+dbStorage_directIOEntryLoggerMaxFdCacheTimeSeconds=300
+
## RocksDB specific configurations
## DbLedgerStorage uses RocksDB to store the indexes from
## (ledgerId, entryId) -> (entryLog, offset)
(pulsar) 02/23: [fix][client] Client interceptors close method not called after producer/consumer/reader close (#23830)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 2a3665e2487255dd38552f3e26407e6432bac461
Author: Yike Xiao <km...@live.com>
AuthorDate: Fri Oct 23 04:28:28 2026 +0800
[fix][client] Client interceptors close method not called after producer/consumer/reader close (#23830)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit a883ea4b1d7df9b10d7806189a0acb203126e7c8)
---
.../apache/pulsar/client/api/InterceptorsTest.java | 88 ++++++++++++++++++++++
.../pulsar/client/api/ConsumerInterceptor.java | 3 +
.../pulsar/client/api/ProducerInterceptor.java | 3 +
.../pulsar/client/api/ReaderInterceptor.java | 3 +
.../api/interceptor/ProducerInterceptor.java | 3 +
.../apache/pulsar/client/impl/ConsumerBase.java | 10 +++
.../apache/pulsar/client/impl/ConsumerImpl.java | 6 +-
.../pulsar/client/impl/ConsumerInterceptors.java | 3 +-
.../client/impl/MultiTopicsConsumerImpl.java | 5 +-
.../client/impl/PartitionedProducerImpl.java | 32 +++++++-
.../apache/pulsar/client/impl/ProducerBase.java | 11 +++
.../apache/pulsar/client/impl/ProducerImpl.java | 3 +
.../pulsar/client/impl/ProducerInterceptors.java | 3 +-
.../pulsar/client/impl/ConsumerImplTest.java | 11 +++
.../pulsar/client/impl/ProducerImplTest.java | 24 +++++-
15 files changed, 197 insertions(+), 11 deletions(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/InterceptorsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/InterceptorsTest.java
index 622542a621ca..b72016fddce9 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/InterceptorsTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/InterceptorsTest.java
@@ -18,6 +18,12 @@
*/
package org.apache.pulsar.client.api;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -1113,6 +1119,88 @@ public class InterceptorsTest extends SharedPulsarBaseTest {
consumer.close();
}
+ @Test(dataProvider = "topicPartition")
+ public void testProducerInterceptorClosedOnceOnProducerClose(int topicPartition) throws Exception {
+ String topic = newTopicName();
+ if (topicPartition > 0) {
+ admin.topics().createPartitionedTopic(topic, topicPartition);
+ }
+ org.apache.pulsar.client.api.interceptor.ProducerInterceptor interceptor =
+ mock(org.apache.pulsar.client.api.interceptor.ProducerInterceptor.class);
+ when(interceptor.eligible(any())).thenReturn(true);
+ when(interceptor.beforeSend(any(), any())).thenAnswer(invocation -> invocation.getArgument(1));
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topic)
+ .intercept(interceptor)
+ .create();
+ producer.send("msg");
+ verify(interceptor).beforeSend(any(), any());
+ verify(interceptor, never()).close();
+
+ producer.close();
+ producer.close();
+
+ verify(interceptor).close();
+ }
+
+ @Test
+ public void testProducerInterceptorSharedByTwoProducersClosedForEach() throws Exception {
+ String topic = newTopicName();
+ org.apache.pulsar.client.api.interceptor.ProducerInterceptor interceptor =
+ mock(org.apache.pulsar.client.api.interceptor.ProducerInterceptor.class);
+ ProducerBuilder<String> builder = pulsarClient.newProducer(Schema.STRING)
+ .topic(topic)
+ .intercept(interceptor);
+ Producer<String> producer1 = builder.create();
+ Producer<String> producer2 = builder.create();
+
+ producer1.close();
+ verify(interceptor).close();
+
+ producer2.close();
+ verify(interceptor, times(2)).close();
+ }
+
+ @Test(dataProvider = "topicPartition")
+ public void testConsumerInterceptorClosedOnceOnConsumerClose(int topicPartition) throws Exception {
+ String topic = newTopicName();
+ if (topicPartition > 0) {
+ admin.topics().createPartitionedTopic(topic, topicPartition);
+ }
+ ConsumerInterceptor<String> interceptor = mock(ConsumerInterceptor.class);
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topic)
+ .subscriptionName("my-subscription")
+ .intercept(interceptor)
+ .subscribe();
+ verify(interceptor, never()).close();
+
+ consumer.close();
+ consumer.close();
+
+ verify(interceptor).close();
+ }
+
+ @Test(dataProvider = "topicPartition")
+ public void testReaderInterceptorClosedOnceOnReaderClose(int topicPartition) throws Exception {
+ String topic = newTopicName();
+ if (topicPartition > 0) {
+ admin.topics().createPartitionedTopic(topic, topicPartition);
+ }
+ ReaderInterceptor<String> interceptor = mock(ReaderInterceptor.class);
+ Reader<String> reader = pulsarClient.newReader(Schema.STRING)
+ .topic(topic)
+ .startMessageId(MessageId.earliest)
+ .intercept(interceptor)
+ .create();
+ verify(interceptor, never()).close();
+
+ reader.close();
+ reader.close();
+
+ verify(interceptor).close();
+ }
+
private void produceAndConsume(int msgCount, Producer<byte[]> producer, Reader<byte[]> reader)
throws PulsarClientException {
for (int i = 0; i < msgCount; i++) {
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ConsumerInterceptor.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ConsumerInterceptor.java
index 1beea3adba23..c17e99ac35d0 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ConsumerInterceptor.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ConsumerInterceptor.java
@@ -38,6 +38,9 @@ public interface ConsumerInterceptor<T> extends AutoCloseable {
/**
* Close the interceptor.
+ *
+ * <p>This method is called once when the consumer that this interceptor is attached to is closed. An interceptor
+ * instance that is attached to several consumers is closed once for each of them.
*/
void close();
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ProducerInterceptor.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ProducerInterceptor.java
index 4989e80cf4b9..ba25f10f9026 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ProducerInterceptor.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ProducerInterceptor.java
@@ -39,6 +39,9 @@ public interface ProducerInterceptor<T> extends AutoCloseable {
/**
* Close the interceptor.
+ *
+ * <p>This method is called once when the producer that this interceptor is attached to is closed. An interceptor
+ * instance that is attached to several producers is closed once for each of them.
*/
void close();
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ReaderInterceptor.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ReaderInterceptor.java
index 3a2e93d9c35a..a56c9d6c56ef 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ReaderInterceptor.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/ReaderInterceptor.java
@@ -31,6 +31,9 @@ public interface ReaderInterceptor<T> {
/**
* Close the interceptor.
+ *
+ * <p>This method is called once when the reader that this interceptor is attached to is closed. An interceptor
+ * instance that is attached to several readers is closed once for each of them.
*/
void close();
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/interceptor/ProducerInterceptor.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/interceptor/ProducerInterceptor.java
index 3eb7e7d897d7..44f075a6dc4e 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/interceptor/ProducerInterceptor.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/interceptor/ProducerInterceptor.java
@@ -46,6 +46,9 @@ public interface ProducerInterceptor extends AutoCloseable {
/**
* Close the interceptor.
+ *
+ * <p>This method is called once when the producer that this interceptor is attached to is closed. An interceptor
+ * instance that is attached to several producers is closed once for each of them.
*/
void close();
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerBase.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerBase.java
index fbccb61a0db6..b558abf15dd9 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerBase.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerBase.java
@@ -110,6 +110,7 @@ public abstract class ConsumerBase<T> extends HandlerState implements Consumer<T
AtomicIntegerFieldUpdater.newUpdater(ConsumerBase.class, "currentReceiverQueueSize");
protected final Schema<T> schema;
protected final ConsumerInterceptors<T> interceptors;
+ private final AtomicBoolean interceptorsClosed = new AtomicBoolean();
protected final BatchReceivePolicy batchReceivePolicy;
protected final ConcurrentLinkedQueue<OpBatchReceive<T>> pendingBatchReceives;
@SuppressWarnings("rawtypes")
@@ -993,6 +994,15 @@ public abstract class ConsumerBase<T> extends HandlerState implements Consumer<T
}
}
+ /**
+ * Close the interceptors once this consumer is closed. Later calls do nothing.
+ */
+ protected void closeInterceptors() {
+ if (interceptors != null && interceptorsClosed.compareAndSet(false, true)) {
+ interceptors.close();
+ }
+ }
+
protected boolean canEnqueueMessage(Message<T> message) {
// Default behavior, can be overridden in subclasses
return true;
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
index 19da8d98f1d5..df9f1987d5a1 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java
@@ -1221,7 +1221,10 @@ public class ConsumerImpl<T> extends ConsumerBase<T> implements ConnectionHandle
closeConsumerTasks();
deregisterFromClientCnx();
client.cleanupConsumer(this);
- failPendingReceive().whenComplete((r, t) -> closeFuture.complete(null));
+ failPendingReceive().whenComplete((r, t) -> {
+ closeInterceptors();
+ closeFuture.complete(null);
+ });
return compositeCloseFuture;
}
@@ -1261,6 +1264,7 @@ public class ConsumerImpl<T> extends ConsumerBase<T> implements ConnectionHandle
// fail all pending-receive futures to notify application
failPendingReceive().whenComplete((r, t) -> {
+ closeInterceptors();
if (exception != null) {
closeFuture.completeExceptionally(exception);
} else {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerInterceptors.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerInterceptors.java
index c2dc61e7fe94..c10a03162770 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerInterceptors.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerInterceptors.java
@@ -19,7 +19,6 @@
package org.apache.pulsar.client.impl;
import java.io.Closeable;
-import java.io.IOException;
import java.util.List;
import java.util.Set;
import lombok.CustomLog;
@@ -213,7 +212,7 @@ public class ConsumerInterceptors<T> implements Closeable {
}
@Override
- public void close() throws IOException {
+ public void close() {
for (int i = 0, interceptorsSize = interceptors.size(); i < interceptorsSize; i++) {
try {
interceptors.get(i).close();
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImpl.java
index 323eeac0839a..95218f6730a1 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImpl.java
@@ -27,7 +27,6 @@ import com.google.common.collect.Lists;
import io.github.merlimat.slog.Logger;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -677,6 +676,7 @@ public class MultiTopicsConsumerImpl<T> extends ConsumerBase<T> {
return failPendingReceive();
}, internalPinnedExecutor)
.whenComplete((r, ex) -> {
+ closeInterceptors();
if (ex == null) {
closeFuture.complete(null);
} else {
@@ -1703,8 +1703,7 @@ public class MultiTopicsConsumerImpl<T> extends ConsumerBase<T> {
}
@Override
- public void close() throws IOException {
- multiTopicInterceptors.close();
+ public void close() {
}
};
}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PartitionedProducerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PartitionedProducerImpl.java
index 3d8e7cb20456..2e66e691a1f4 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PartitionedProducerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PartitionedProducerImpl.java
@@ -63,6 +63,7 @@ public class PartitionedProducerImpl<T> extends ProducerBase<T> {
private final Map<Integer, ProducerImpl<T>> producers = new ConcurrentHashMap<>();
private final MessageRouter routerPolicy;
private final PartitionedTopicProducerStatsRecorderImpl stats;
+ private final ProducerInterceptors internalProducerInterceptors;
private TopicMetadata topicMetadata;
private final int firstPartitionIndex;
private String overrideProducerName;
@@ -82,6 +83,9 @@ public class PartitionedProducerImpl<T> extends ProducerBase<T> {
.build();
this.topicMetadata = new TopicMetadataImpl(numPartitions);
this.routerPolicy = getMessageRouter();
+ this.internalProducerInterceptors = interceptors != null
+ ? createInternalProducerInterceptors(interceptors)
+ : null;
stats = client.getConfiguration().getStatsIntervalSeconds() > 0
? new PartitionedTopicProducerStatsRecorderImpl()
: null;
@@ -233,7 +237,7 @@ public class PartitionedProducerImpl<T> extends ProducerBase<T> {
return producers.computeIfAbsent(partitionIndex, (idx) -> {
String partitionName = TopicName.get(topic).getPartition(idx).toString();
return client.newProducerImpl(partitionName, idx,
- conf, schema, interceptors, new CompletableFuture<>(), overrideProducerName);
+ conf, schema, internalProducerInterceptors, new CompletableFuture<>(), overrideProducerName);
});
}
@@ -353,6 +357,7 @@ public class PartitionedProducerImpl<T> extends ProducerBase<T> {
closeFail.compareAndSet(null, ex);
}
if (completed.decrementAndGet() == 0) {
+ closeInterceptors();
if (closeFail.get() == null) {
setState(State.Closed);
closeFuture.complete(null);
@@ -483,6 +488,31 @@ public class PartitionedProducerImpl<T> extends ProducerBase<T> {
}
}
+ private ProducerInterceptors createInternalProducerInterceptors(ProducerInterceptors interceptors) {
+ return new ProducerInterceptors(Collections.emptyList()) {
+ @Override
+ public Message beforeSend(Producer producer, Message message) {
+ return interceptors.beforeSend(producer, message);
+ }
+
+ @Override
+ public void onSendAcknowledgement(Producer producer, Message message, MessageId msgId,
+ Throwable exception) {
+ interceptors.onSendAcknowledgement(producer, message, msgId, exception);
+ }
+
+ @Override
+ public void onPartitionsChange(String topicName, int partitions) {
+ // do nothing
+ }
+
+ @Override
+ public void close() {
+ // do nothing
+ }
+ };
+ }
+
private TimerTask partitionsAutoUpdateTimerTask = new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
index b7085d28ee2a..7cfcec64e896 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerBase.java
@@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
@@ -41,6 +42,7 @@ public abstract class ProducerBase<T> extends HandlerState implements Producer<T
protected final ProducerConfigurationData conf;
protected final Schema<T> schema;
protected final ProducerInterceptors interceptors;
+ private final AtomicBoolean interceptorsClosed = new AtomicBoolean();
protected final Map<SchemaHash, byte[]> schemaCache = new ConcurrentHashMap<>();
protected volatile MultiSchemaMode multiSchemaMode = MultiSchemaMode.Auto;
@@ -178,6 +180,15 @@ public abstract class ProducerBase<T> extends HandlerState implements Producer<T
}
}
+ /**
+ * Close the interceptors once this producer is closed. Later calls do nothing.
+ */
+ protected void closeInterceptors() {
+ if (interceptors != null && interceptorsClosed.compareAndSet(false, true)) {
+ interceptors.close();
+ }
+ }
+
@Override
public String toString() {
return "ProducerBase{" + "topic='" + topic + '\'' + '}';
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
index 3bbdee956b47..393b685e8525 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java
@@ -1459,6 +1459,7 @@ public class ProducerImpl<T> extends ProducerBase<T> implements TimerTask, Conne
if (cnx == null || (currentState != State.Ready && currentState != State.RegisteringSchema)) {
log.info("Closed Producer (not connected)");
closeAndClearPendingMessages();
+ closeInterceptors();
return CompletableFuture.completedFuture(null);
}
@@ -1472,8 +1473,10 @@ public class ProducerImpl<T> extends ProducerBase<T> implements TimerTask, Conne
// connection did break in the meantime. In any case, the producer is gone.
log.info("Closed Producer");
closeAndClearPendingMessages();
+ closeInterceptors();
closeFuture.complete(null);
} else {
+ closeInterceptors();
closeFuture.completeExceptionally(exception);
}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerInterceptors.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerInterceptors.java
index 9d7519343bb7..c87cadee8dcc 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerInterceptors.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerInterceptors.java
@@ -19,7 +19,6 @@
package org.apache.pulsar.client.impl;
import java.io.Closeable;
-import java.io.IOException;
import java.util.List;
import lombok.CustomLog;
import org.apache.pulsar.client.api.Message;
@@ -114,7 +113,7 @@ public class ProducerInterceptors implements Closeable {
}
@Override
- public void close() throws IOException {
+ public void close() {
for (ProducerInterceptor interceptor : interceptors) {
try {
interceptor.close();
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java
index 8ada68d3ef73..9221add8590c 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java
@@ -607,6 +607,17 @@ public class ConsumerImplTest {
}
}
+ @Test
+ public void testCloseNotConnectedConsumerClosesInterceptorsOnce() throws Exception {
+ ConsumerInterceptor<byte[]> interceptor = mock(ConsumerInterceptor.class);
+ createConsumer(new ConsumerConfigurationData<>(), topic, interceptor);
+
+ consumer.closeAsync().get(5, TimeUnit.SECONDS);
+ consumer.closeAsync().get(5, TimeUnit.SECONDS);
+
+ verify(interceptor).close();
+ }
+
@Test
public void testMessageEnqueuedAfterCloseIsDiscarded() {
consumerConf = new ConsumerConfigurationData<>();
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
index 02be50b81ccf..a881701e6bcc 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ProducerImplTest.java
@@ -69,6 +69,7 @@ import org.apache.pulsar.client.api.MessageCrypto;
import org.apache.pulsar.client.api.ProducerCryptoFailureAction;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.interceptor.ProducerInterceptor;
import org.apache.pulsar.client.impl.ProducerImpl.OpSendMsg;
import org.apache.pulsar.client.impl.ProducerImpl.OpSendMsgQueue;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
@@ -305,6 +306,20 @@ public class ProducerImplTest {
connectionFuture.completeExceptionally(new PulsarClientException("producer closed during connect"));
}
+ @Test
+ public void testCloseNotConnectedProducerClosesInterceptorsOnce() throws Exception {
+ PulsarClientImpl client = mockedPulsarClient();
+ when(client.getConnection(Mockito.anyString(), Mockito.anyInt())).thenReturn(new CompletableFuture<>());
+ ProducerInterceptor interceptor = mock(ProducerInterceptor.class);
+ ProducerImpl<byte[]> producer = constructProducer(client, new ProducerConfigurationData(),
+ new ProducerInterceptors(Collections.singletonList(interceptor)));
+
+ producer.closeAsync().get(5, TimeUnit.SECONDS);
+ producer.closeAsync().get(5, TimeUnit.SECONDS);
+
+ verify(interceptor).close();
+ }
+
private ProducerConfigurationData encryptedProducerConf() {
ProducerConfigurationData conf = new ProducerConfigurationData();
conf.setEncryptionKeys(new TreeSet<>(Collections.singleton("key")));
@@ -336,12 +351,17 @@ public class ProducerImplTest {
* {@code msgCrypto} fields hold real values instead of needing reflection: {@code conf.setMessageCrypto()}
* installs a test crypto through the same constructor branch production uses.
*/
- @SuppressWarnings("unchecked")
private static ProducerImpl<byte[]> constructProducer(PulsarClientImpl client,
ProducerConfigurationData conf) {
+ return constructProducer(client, conf, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static ProducerImpl<byte[]> constructProducer(PulsarClientImpl client,
+ ProducerConfigurationData conf, ProducerInterceptors interceptors) {
return mock(ProducerImpl.class, withSettings()
.useConstructor(client, "persistent://public/default/producer-impl-test", conf,
- new CompletableFuture<>(), 0, Schema.BYTES, null, Optional.empty())
+ new CompletableFuture<>(), 0, Schema.BYTES, interceptors, Optional.empty())
.defaultAnswer(CALLS_REAL_METHODS));
}
(pulsar) 04/23: [fix][proxy] Answer failed partition metadata and lookup requests with their own response type (#26607)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 7f5e884d4eef51a569b0d45eb768a6d3977c5477
Author: void-ptr974 <vo...@protonmail.com>
AuthorDate: Fri Oct 23 05:32:12 2026 +0800
[fix][proxy] Answer failed partition metadata and lookup requests with their own response type (#26607)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit c019a2d414c0d50b68cf90f5ea19b53ca7b307ec)
---
.../pulsar/proxy/server/LookupProxyHandler.java | 143 ++++--
.../proxy/server/LookupProxyHandlerTest.java | 571 +++++++++++++++++++++
2 files changed, 664 insertions(+), 50 deletions(-)
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
index 75dd59e86210..b0456d09f853 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
@@ -23,6 +23,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import io.prometheus.client.Counter;
+import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
@@ -33,6 +34,8 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeoutException;
+import java.util.function.BiConsumer;
import java.util.function.BooleanSupplier;
import lombok.CustomLog;
import org.apache.commons.lang3.StringUtils;
@@ -41,6 +44,7 @@ import org.apache.pulsar.broker.topiclistlimit.TopicListSizeResultCache;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.impl.BinaryProtoLookupService;
import org.apache.pulsar.client.impl.ClientCnx;
+import org.apache.pulsar.client.impl.ConnectionPool;
import org.apache.pulsar.common.api.proto.BaseCommand;
import org.apache.pulsar.common.api.proto.CommandGetSchema;
import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace;
@@ -124,7 +128,7 @@ public class LookupProxyHandler {
if (lookupRequestSemaphore.tryAcquire()) {
try {
LOOKUP_REQUESTS.inc();
- String serviceUrl = getBrokerServiceUrl(clientRequestId);
+ String serviceUrl = getBrokerServiceUrl(lookupErrorResponse(clientRequestId));
if (serviceUrl != null) {
performLookup(clientRequestId, lookup.getTopic(), serviceUrl, false, 10);
}
@@ -152,16 +156,10 @@ public class LookupProxyHandler {
return;
}
- URI brokerURI;
- try {
- brokerURI = new URI(brokerServiceUrl);
- } catch (URISyntaxException e) {
- writeAndFlush(
- Commands.newLookupErrorResponse(ServerError.MetadataError, e.getMessage(), clientRequestId));
+ InetSocketAddress addr = getAddr(brokerServiceUrl, lookupErrorResponse(clientRequestId));
+ if (addr == null) {
return;
}
-
- InetSocketAddress addr = InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort());
log.debug()
.attr("addr", addr)
.attr("topic", topic)
@@ -251,15 +249,15 @@ public class LookupProxyHandler {
private void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata partitionMetadata,
long clientRequestId) {
String topicName = TopicName.toFullTopicName(partitionMetadata.getTopic());
+ boolean metadataAutoCreationEnabled = partitionMetadata.isMetadataAutoCreationEnabled();
+ BiConsumer<ServerError, String> onError = (error, message) ->
+ writeAndFlush(Commands.newPartitionMetadataResponse(error, message, clientRequestId));
- String serviceUrl = getBrokerServiceUrl(clientRequestId);
+ String serviceUrl = getBrokerServiceUrl(onError);
if (serviceUrl == null) {
- log.warn()
- .attr("topic", topicName)
- .log("No available broker for to lookup partition metadata");
return;
}
- InetSocketAddress addr = getAddr(serviceUrl, clientRequestId);
+ InetSocketAddress addr = getAddr(serviceUrl, onError);
if (addr == null) {
return;
}
@@ -269,35 +267,61 @@ public class LookupProxyHandler {
.attr("topic", topicName)
.attr("clientRequestId", clientRequestId)
.log("Getting connection for partition metadata lookup");
- proxyConnection.getConnectionPool().getConnection(addr).thenAccept(clientCnx -> {
- // Connected to backend broker
- long requestId = proxyConnection.newRequestId();
- ByteBuf command;
- command = Commands.newPartitionMetadataRequest(topicName.toString(), requestId,
- partitionMetadata.isMetadataAutoCreationEnabled());
- clientCnx.newLookup(command, requestId).whenComplete((r, t) -> {
- if (t != null) {
- log.warn()
- .attr("topic", topicName)
- .exception(t)
- .log("failed to get Partitioned");
- PulsarClientException pce = PulsarClientException.unwrap(t);
- writeAndFlush(Commands.newLookupErrorResponse(ClientCnx.revertClientExToErrorCode(pce),
- t.getMessage(), clientRequestId));
- } else {
- writeAndFlush(
- Commands.newPartitionMetadataResponse(r.partitions, clientRequestId));
- }
- proxyConnection.getConnectionPool().releaseConnection(clientCnx);
- });
- }).exceptionally(ex -> {
- // Failed to connect to backend broker
- writeAndFlush(Commands.newPartitionMetadataResponse(getServerError(ex),
- ex.getMessage(), clientRequestId));
- return null;
+ // The frontend connection can clear its pool while the backend request is pending.
+ ConnectionPool connectionPool = proxyConnection.getConnectionPool();
+ FutureUtil.supplySafely(() -> connectionPool.getConnection(addr)).whenComplete((clientCnx, connectionError) -> {
+ if (connectionError != null) {
+ writePartitionMetadataError(connectionError, clientRequestId, ServerError.ServiceNotReady);
+ return;
+ }
+ FutureUtil.supplySafely(() -> {
+ long requestId = proxyConnection.newRequestId();
+ ByteBuf command = Commands.newPartitionMetadataRequest(topicName, requestId,
+ metadataAutoCreationEnabled);
+ return clientCnx.newLookup(command, requestId);
+ }).whenComplete((result, error) -> connectionPool.releaseConnection(clientCnx))
+ .whenComplete((result, error) -> {
+ if (error != null) {
+ log.warn()
+ .attr("topic", topicName)
+ .exception(error)
+ .log("failed to get Partitioned");
+ writePartitionMetadataError(error, clientRequestId, ServerError.UnknownError);
+ } else {
+ writeAndFlush(Commands.newPartitionMetadataResponse(result.partitions, clientRequestId));
+ }
+ });
});
}
+ private BiConsumer<ServerError, String> lookupErrorResponse(long clientRequestId) {
+ return (error, message) -> writeAndFlush(Commands.newLookupErrorResponse(error, message, clientRequestId));
+ }
+
+ private void writePartitionMetadataError(Throwable error, long clientRequestId, ServerError fallbackError) {
+ Throwable cause = FutureUtil.unwrapCompletionException(error);
+ if (cause == null) {
+ cause = error;
+ }
+ ServerError serverError;
+ if (cause instanceof PulsarClientException.TimeoutException
+ || cause instanceof PulsarClientException.ConnectException
+ || cause instanceof PulsarClientException.NotConnectedException
+ || cause instanceof PulsarClientException.AlreadyClosedException
+ || cause instanceof TimeoutException
+ || (cause instanceof IOException && !(cause instanceof PulsarClientException))) {
+ serverError = ServerError.ServiceNotReady;
+ } else if (cause instanceof PulsarClientException clientException) {
+ serverError = ClientCnx.revertClientExToErrorCode(clientException);
+ if (serverError == ServerError.UnknownError) {
+ serverError = fallbackError;
+ }
+ } else {
+ serverError = fallbackError;
+ }
+ writeAndFlush(Commands.newPartitionMetadataResponse(serverError, cause.getMessage(), clientRequestId));
+ }
+
public void handleGetTopicsOfNamespace(CommandGetTopicsOfNamespace commandGetTopicsOfNamespace) {
GET_TOPICS_OF_NAMESPACE_REQUESTS.inc();
log.debug()
@@ -561,6 +585,11 @@ public class LookupProxyHandler {
* Get default broker service url or discovery an available broker.
**/
private String getBrokerServiceUrl(long clientRequestId) {
+ return getBrokerServiceUrl((error, message) ->
+ writeAndFlush(Commands.newError(clientRequestId, error, message)));
+ }
+
+ private String getBrokerServiceUrl(BiConsumer<ServerError, String> onError) {
if (StringUtils.isNotBlank(brokerServiceURL)) {
return brokerServiceURL;
}
@@ -573,24 +602,38 @@ public class LookupProxyHandler {
.attr("e", e.getMessage())
.exception(e)
.log("Failed to get next active broker");
- writeAndFlush(Commands.newError(
- clientRequestId, ServerError.ServiceNotReady, e.getMessage()
- ));
+ onError.accept(ServerError.ServiceNotReady, e.getMessage());
return null;
}
- return this.connectWithTLS ? availableBroker.getPulsarServiceUrlTls() : availableBroker.getPulsarServiceUrl();
+ String serviceUrl = availableBroker == null ? null
+ : (connectWithTLS ? availableBroker.getPulsarServiceUrlTls() : availableBroker.getPulsarServiceUrl());
+ if (StringUtils.isBlank(serviceUrl)) {
+ onError.accept(ServerError.ServiceNotReady, "No broker service URL available");
+ return null;
+ }
+ return serviceUrl;
}
private InetSocketAddress getAddr(String brokerServiceUrl, long clientRequestId) {
- URI brokerURI;
+ return getAddr(brokerServiceUrl, (error, message) ->
+ writeAndFlush(Commands.newError(clientRequestId, error, message)));
+ }
+
+ private InetSocketAddress getAddr(String brokerServiceUrl, BiConsumer<ServerError, String> onError) {
+ if (StringUtils.isBlank(brokerServiceUrl)) {
+ onError.accept(ServerError.ServiceNotReady, "No broker service URL available");
+ return null;
+ }
try {
- brokerURI = new URI(brokerServiceUrl);
- } catch (URISyntaxException e) {
- writeAndFlush(
- Commands.newError(clientRequestId, ServerError.MetadataError, e.getMessage()));
+ URI brokerURI = new URI(brokerServiceUrl);
+ if (StringUtils.isBlank(brokerURI.getHost()) || brokerURI.getPort() <= 0) {
+ throw new IllegalArgumentException("Invalid broker service URL: " + brokerServiceUrl);
+ }
+ return InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort());
+ } catch (URISyntaxException | IllegalArgumentException e) {
+ onError.accept(ServerError.MetadataError, e.getMessage());
return null;
}
- return InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort());
}
private ServerError getServerError(Throwable error) {
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
new file mode 100644
index 000000000000..9c4de0c917c9
--- /dev/null
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
@@ -0,0 +1,571 @@
+/*
+ * 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.proxy.server;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelException;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.EncoderException;
+import java.net.InetSocketAddress;
+import java.nio.channels.ClosedChannelException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeoutException;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.client.api.PulsarClientException;
+import org.apache.pulsar.client.impl.BinaryProtoLookupService.LookupDataResult;
+import org.apache.pulsar.client.impl.ClientCnx;
+import org.apache.pulsar.client.impl.ConnectionPool;
+import org.apache.pulsar.common.api.proto.BaseCommand;
+import org.apache.pulsar.common.api.proto.CommandGetSchema;
+import org.apache.pulsar.common.api.proto.CommandLookupTopic;
+import org.apache.pulsar.common.api.proto.CommandLookupTopicResponse;
+import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadata;
+import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadataResponse;
+import org.apache.pulsar.common.api.proto.ServerError;
+import org.apache.pulsar.policies.data.loadbalancer.LoadManagerReport;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class LookupProxyHandlerTest {
+ private static final long CLIENT_REQUEST_ID = 10L;
+ private static final long BROKER_REQUEST_ID = 20L;
+ private static final String TOPIC = "persistent://tenant/ns/topic";
+
+ private ProxyConfiguration configuration;
+ private ProxyService proxyService;
+ private ProxyConnection proxyConnection;
+ private CompletableFuture<LookupDataResult> metadataFuture;
+ private CompletableFuture<ClientCnx> connectionFuture;
+ private ClientCnx clientCnx;
+ private ConnectionPool connectionPool;
+ private EmbeddedChannel channel;
+ private LookupProxyHandler handler;
+ private ByteBuf forwardedRequest;
+
+ @BeforeMethod
+ public void setup() {
+ configuration = new ProxyConfiguration();
+ configuration.setBrokerServiceURL("pulsar://broker:6650");
+ proxyService = mock(ProxyService.class);
+ when(proxyService.getConfiguration()).thenReturn(configuration);
+ when(proxyService.getLookupRequestSemaphore()).thenReturn(new Semaphore(1));
+
+ metadataFuture = new CompletableFuture<>();
+ clientCnx = mock(ClientCnx.class);
+ doAnswer(invocation -> {
+ ByteBuf request = invocation.getArgument(0);
+ try {
+ forwardedRequest = request.copy();
+ return metadataFuture;
+ } finally {
+ request.release();
+ }
+ }).when(clientCnx).newLookup(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+ connectionFuture = new CompletableFuture<>();
+ connectionPool = mock(ConnectionPool.class);
+ when(connectionPool.getConnection(any(InetSocketAddress.class))).thenReturn(connectionFuture);
+ proxyConnection = mock(ProxyConnection.class);
+ when(proxyConnection.getConnectionPool()).thenReturn(connectionPool);
+ when(proxyConnection.newRequestId()).thenReturn(BROKER_REQUEST_ID);
+
+ channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
+ when(proxyConnection.ctx()).thenReturn(channel.pipeline().firstContext());
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void cleanup() {
+ if (forwardedRequest != null) {
+ forwardedRequest.release();
+ forwardedRequest = null;
+ }
+ if (channel != null) {
+ channel.finishAndReleaseAll();
+ }
+ }
+
+ @DataProvider
+ public Object[][] partitionMetadataErrors() {
+ Object[][] errors = {
+ {new PulsarClientException.AuthorizationException("Not authorized"), ServerError.AuthorizationError,
+ "Not authorized"},
+ {new CompletionException(new PulsarClientException.AuthenticationException("Authentication failed")),
+ ServerError.AuthenticationError, "Authentication failed"},
+ {new ExecutionException(new PulsarClientException.TopicDoesNotExistException("Topic does not exist")),
+ ServerError.TopicNotFound, "Topic does not exist"},
+ {new PulsarClientException.TooManyRequestsException("Too many requests"), ServerError.TooManyRequests,
+ "Too many requests"},
+ {new EncoderException("Encoding failed"), ServerError.UnknownError, "Encoding failed"},
+ {new CompletionException(new EncoderException("Encoding failed")),
+ ServerError.UnknownError, "Encoding failed"},
+ {new CompletionException(new IllegalStateException("Unexpected broker failure")),
+ ServerError.UnknownError, "Unexpected broker failure"},
+ {new PulsarClientException((String) null), ServerError.UnknownError, null},
+ {new PulsarClientException.TimeoutException("Lookup timed out"), ServerError.ServiceNotReady,
+ "Lookup timed out"},
+ {new PulsarClientException.ConnectException("Disconnected"), ServerError.ServiceNotReady,
+ "Disconnected"},
+ {new PulsarClientException.AlreadyClosedException("Connection closed"), ServerError.ServiceNotReady,
+ "Connection closed"},
+ {new PulsarClientException.NotConnectedException("Not connected"), ServerError.ServiceNotReady,
+ "Not connected"},
+ {new TimeoutException("Lookup timed out"), ServerError.ServiceNotReady, "Lookup timed out"},
+ {new ClosedChannelException(), ServerError.ServiceNotReady, null}
+ };
+ List<Object[]> cases = new ArrayList<>();
+ for (Object[] error : errors) {
+ for (boolean alreadyFailed : new boolean[] {false, true}) {
+ cases.add(new Object[] {error[0], error[1], error[2], alreadyFailed});
+ }
+ }
+ return cases.toArray(new Object[0][]);
+ }
+
+ @Test(dataProvider = "partitionMetadataErrors")
+ public void testPartitionMetadataErrorResponse(Throwable error, ServerError expectedError, String expectedMessage,
+ boolean alreadyFailed) {
+ if (alreadyFailed) {
+ metadataFuture.completeExceptionally(error);
+ }
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.complete(clientCnx);
+ assertForwardedRequest(false);
+ if (!alreadyFailed) {
+ assertThat(channel.outboundMessages()).as("Responses before the broker completes").isEmpty();
+ metadataFuture.completeExceptionally(error);
+ }
+
+ assertErrorResponse(expectedError, expectedMessage);
+ verify(clientCnx).newLookup(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ @DataProvider
+ public Object[][] metadataAutoCreationFlags() {
+ return new Object[][] {
+ {false, false}, {false, true}, {true, false}, {true, true}, {null, false}, {null, true}
+ };
+ }
+
+ @Test(dataProvider = "metadataAutoCreationFlags")
+ public void testPartitionMetadataPreservesAutoCreationFlag(Boolean autoCreationEnabled, boolean alreadyConnected) {
+ CommandPartitionedTopicMetadata request = new CommandPartitionedTopicMetadata()
+ .setTopic(TOPIC).setRequestId(CLIENT_REQUEST_ID);
+ if (autoCreationEnabled != null) {
+ request.setMetadataAutoCreationEnabled(autoCreationEnabled);
+ }
+ if (alreadyConnected) {
+ connectionFuture.complete(clientCnx);
+ }
+ handler.handlePartitionMetadataResponse(request);
+ // The decoder clears its reusable command as soon as the handler returns.
+ request.clear();
+ if (!alreadyConnected) {
+ connectionFuture.complete(clientCnx);
+ }
+ assertForwardedRequest(autoCreationEnabled == null || autoCreationEnabled);
+ metadataFuture.complete(new LookupDataResult(4));
+
+ assertThat(readMetadataResponse().getPartitions()).as("Partition count").isEqualTo(4);
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ @DataProvider
+ public Object[][] partitionCounts() {
+ return new Object[][] {{0}, {4}};
+ }
+
+ @Test(dataProvider = "partitionCounts")
+ public void testPartitionMetadataSuccessResponse(int partitions) {
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.complete(clientCnx);
+ assertForwardedRequest(false);
+ metadataFuture.complete(new LookupDataResult(partitions));
+
+ CommandPartitionedTopicMetadataResponse response = readMetadataResponse();
+ assertThat(response.getResponse()).as("Metadata lookup result")
+ .isEqualTo(CommandPartitionedTopicMetadataResponse.LookupType.Success);
+ assertThat(response.getPartitions()).as("Partition count").isEqualTo(partitions);
+ assertThat(response.hasError()).as("Success response error").isFalse();
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ @DataProvider
+ public Object[][] connectionErrors() {
+ return new Object[][] {
+ {new PulsarClientException("Connection already closed"),
+ ServerError.ServiceNotReady, "Connection already closed"},
+ {new ChannelException("Connection failed"), ServerError.ServiceNotReady, "Connection failed"},
+ {new PulsarClientException.ConnectException("Connection failed"),
+ ServerError.ServiceNotReady, "Connection failed"},
+ {new CompletionException(new PulsarClientException.AuthenticationException("Authentication failed")),
+ ServerError.AuthenticationError, "Authentication failed"},
+ {new ExecutionException(new CompletionException(
+ new PulsarClientException.AuthorizationException("Not authorized"))),
+ ServerError.AuthorizationError, "Not authorized"},
+ {new PulsarClientException.TimeoutException("Connection timed out"),
+ ServerError.ServiceNotReady, "Connection timed out"},
+ {new PulsarClientException.AlreadyClosedException("Connection closed"),
+ ServerError.ServiceNotReady, "Connection closed"},
+ {new PulsarClientException.NotConnectedException("Not connected"), ServerError.ServiceNotReady,
+ "Not connected"},
+ {new TimeoutException("Connection timed out"), ServerError.ServiceNotReady, "Connection timed out"},
+ {new ClosedChannelException(), ServerError.ServiceNotReady, null}
+ };
+ }
+
+ @Test(dataProvider = "connectionErrors")
+ public void testPartitionMetadataConnectionFailureResponse(Throwable error, ServerError expectedError,
+ String expectedMessage) {
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.completeExceptionally(error);
+
+ assertErrorResponse(expectedError, expectedMessage);
+ verifyNoBackendLookup();
+ verify(connectionPool, never()).releaseConnection(any(ClientCnx.class));
+ }
+
+ @Test
+ public void testPartitionMetadataDiscoveryFailureResponse() throws Exception {
+ BrokerDiscoveryProvider discoveryProvider = mock(BrokerDiscoveryProvider.class);
+ when(discoveryProvider.nextBroker()).thenThrow(new PulsarServerException("No active broker is available"));
+ configuration.setBrokerServiceURL(null);
+ when(proxyService.getDiscoveryProvider()).thenReturn(discoveryProvider);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handlePartitionMetadataResponse(newRequest());
+
+ assertErrorResponse(ServerError.ServiceNotReady, "No active broker is available");
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ verifyNoBackendLookup();
+ }
+
+ @DataProvider
+ public Object[][] missingBrokerServiceUrls() {
+ return new Object[][] {{false, null}, {true, null}, {false, ""}, {true, ""}};
+ }
+
+ @Test(dataProvider = "missingBrokerServiceUrls")
+ public void testPartitionMetadataMissingBrokerServiceUrl(boolean useTls, String serviceUrl) throws Exception {
+ BrokerDiscoveryProvider discoveryProvider = mock(BrokerDiscoveryProvider.class);
+ LoadManagerReport broker = mock(LoadManagerReport.class);
+ when(broker.getPulsarServiceUrl()).thenReturn(useTls ? "pulsar://broker:6650" : serviceUrl);
+ when(broker.getPulsarServiceUrlTls()).thenReturn(useTls ? serviceUrl : "pulsar+ssl://broker:6651");
+ when(discoveryProvider.nextBroker()).thenReturn(broker);
+ when(proxyService.getDiscoveryProvider()).thenReturn(discoveryProvider);
+ configuration.setBrokerServiceURL(null);
+ configuration.setTlsEnabledWithBroker(useTls);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handlePartitionMetadataResponse(newRequest());
+
+ CommandPartitionedTopicMetadataResponse response = assertErrorResponse(ServerError.ServiceNotReady);
+ assertThat(response.getMessage()).as("Missing broker service URL error").isNotBlank();
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ verifyNoBackendLookup();
+ }
+
+ @DataProvider
+ public Object[][] invalidBrokerServiceUrls() {
+ return new Object[][] {
+ {"pulsar://bad host:6650"}, {"pulsar:///broker:6650"}, {"pulsar://broker"},
+ {"pulsar://broker:0"}, {"pulsar://broker:65536"}
+ };
+ }
+
+ @Test(dataProvider = "invalidBrokerServiceUrls")
+ public void testPartitionMetadataInvalidBrokerServiceUrl(String serviceUrl) {
+ configuration.setBrokerServiceURL(serviceUrl);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handlePartitionMetadataResponse(newRequest());
+
+ CommandPartitionedTopicMetadataResponse response = assertErrorResponse(ServerError.MetadataError);
+ assertThat(response.getMessage()).as("Invalid broker service URL error").isNotBlank();
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ verifyNoBackendLookup();
+ }
+
+ @Test
+ public void testPartitionMetadataReleasesOriginalConnectionPoolAfterDisconnect() {
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.complete(clientCnx);
+ assertForwardedRequest(false);
+ // ProxyConnection clears its pool when the client disconnects.
+ when(proxyConnection.getConnectionPool()).thenReturn(null);
+ metadataFuture.complete(new LookupDataResult(4));
+
+ assertThat(readMetadataResponse().getPartitions()).as("Partition count").isEqualTo(4);
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ @Test
+ public void testPartitionMetadataReleasesConnectionOnSynchronousLookupFailure() {
+ doAnswer(invocation -> {
+ ByteBuf request = invocation.getArgument(0);
+ request.release();
+ throw new EncoderException("Encoding failed");
+ }).when(clientCnx).newLookup(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.complete(clientCnx);
+
+ assertErrorResponse(ServerError.UnknownError, "Encoding failed");
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ @Test
+ public void testPartitionMetadataReleasesConnectionOnResponseWriteFailure() {
+ ChannelHandlerContext context = mock(ChannelHandlerContext.class);
+ ChannelPromise promise = mock(ChannelPromise.class);
+ when(context.voidPromise()).thenReturn(promise);
+ doAnswer(invocation -> {
+ ByteBuf response = invocation.getArgument(0);
+ response.release();
+ throw new IllegalStateException("Response write failed");
+ }).when(context).writeAndFlush(any(ByteBuf.class), eq(promise));
+ when(proxyConnection.ctx()).thenReturn(context);
+ handler.handlePartitionMetadataResponse(newRequest());
+ connectionFuture.complete(clientCnx);
+ assertForwardedRequest(false);
+ metadataFuture.complete(new LookupDataResult(4));
+
+ verify(context).writeAndFlush(any(ByteBuf.class), eq(promise));
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ private void verifyNoBackendLookup() {
+ verify(clientCnx, never()).newLookup(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+ }
+
+ @Test
+ public void testSchemaDiscoveryFailurePreservesGenericErrorResponse() throws Exception {
+ BrokerDiscoveryProvider discoveryProvider = mock(BrokerDiscoveryProvider.class);
+ when(discoveryProvider.nextBroker()).thenThrow(new PulsarServerException("No active broker is available"));
+ configuration.setBrokerServiceURL(null);
+ when(proxyService.getDiscoveryProvider()).thenReturn(discoveryProvider);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handleGetSchema(new CommandGetSchema().setTopic(TOPIC).setRequestId(CLIENT_REQUEST_ID));
+
+ assertGenericErrorResponse(ServerError.ServiceNotReady);
+ }
+
+ @Test
+ public void testSchemaInvalidBrokerUrlPreservesGenericErrorResponse() {
+ configuration.setBrokerServiceURL("pulsar://broker");
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handleGetSchema(new CommandGetSchema().setTopic(TOPIC).setRequestId(CLIENT_REQUEST_ID));
+
+ assertGenericErrorResponse(ServerError.MetadataError);
+ }
+
+ @Test
+ public void testLookupDiscoveryFailureResponse() throws Exception {
+ BrokerDiscoveryProvider discoveryProvider = mock(BrokerDiscoveryProvider.class);
+ when(discoveryProvider.nextBroker()).thenThrow(new PulsarServerException("No active broker is available"));
+ configuration.setBrokerServiceURL(null);
+ when(proxyService.getDiscoveryProvider()).thenReturn(discoveryProvider);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handleLookup(newLookupRequest());
+
+ assertThat(readLookupErrorResponse(ServerError.ServiceNotReady).getMessage())
+ .as("Lookup error message").isEqualTo("No active broker is available");
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ }
+
+ @Test(dataProvider = "missingBrokerServiceUrls")
+ public void testLookupMissingBrokerServiceUrl(boolean useTls, String serviceUrl) throws Exception {
+ BrokerDiscoveryProvider discoveryProvider = mock(BrokerDiscoveryProvider.class);
+ LoadManagerReport broker = mock(LoadManagerReport.class);
+ when(broker.getPulsarServiceUrl()).thenReturn(useTls ? "pulsar://broker:6650" : serviceUrl);
+ when(broker.getPulsarServiceUrlTls()).thenReturn(useTls ? serviceUrl : "pulsar+ssl://broker:6651");
+ when(discoveryProvider.nextBroker()).thenReturn(broker);
+ when(proxyService.getDiscoveryProvider()).thenReturn(discoveryProvider);
+ configuration.setBrokerServiceURL(null);
+ configuration.setTlsEnabledWithBroker(useTls);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handleLookup(newLookupRequest());
+
+ readLookupErrorResponse(ServerError.ServiceNotReady);
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ }
+
+ @Test(dataProvider = "invalidBrokerServiceUrls")
+ public void testLookupInvalidBrokerServiceUrl(String serviceUrl) {
+ configuration.setBrokerServiceURL(serviceUrl);
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+
+ handler.handleLookup(newLookupRequest());
+
+ readLookupErrorResponse(ServerError.MetadataError);
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ }
+
+ @DataProvider
+ public Object[][] invalidRedirectBrokerUrls() {
+ return new Object[][] {{null, ServerError.ServiceNotReady}, {"pulsar://broker2", ServerError.MetadataError}};
+ }
+
+ @Test(dataProvider = "invalidRedirectBrokerUrls")
+ public void testLookupRedirectToInvalidBrokerUrl(String redirectUrl, ServerError expectedError) {
+ handler.handleLookup(newLookupRequest());
+ connectionFuture.complete(clientCnx);
+ CommandLookupTopicResponse redirect = new CommandLookupTopicResponse()
+ .setRequestId(BROKER_REQUEST_ID)
+ .setResponse(CommandLookupTopicResponse.LookupType.Redirect);
+ if (redirectUrl != null) {
+ redirect.setBrokerServiceUrl(redirectUrl);
+ }
+ metadataFuture.complete(new LookupDataResult(redirect));
+
+ readLookupErrorResponse(expectedError);
+ verify(connectionPool).releaseConnection(clientCnx);
+ }
+
+ private CommandLookupTopic newLookupRequest() {
+ return new CommandLookupTopic().setTopic(TOPIC).setRequestId(CLIENT_REQUEST_ID);
+ }
+
+ private CommandLookupTopicResponse readLookupErrorResponse(ServerError expectedError) {
+ ByteBuf buffer = channel.readOutbound();
+ assertThat(buffer).as("Lookup response").isNotNull();
+ try {
+ BaseCommand command = decodeCommand(buffer);
+ assertThat(command.getType()).as("Response command type")
+ .isEqualTo(BaseCommand.Type.LOOKUP_RESPONSE);
+ CommandLookupTopicResponse response = command.getLookupTopicResponse();
+ assertThat(response.getRequestId()).as("Client request ID").isEqualTo(CLIENT_REQUEST_ID);
+ assertThat(response.getResponse()).as("Lookup result")
+ .isEqualTo(CommandLookupTopicResponse.LookupType.Failed);
+ assertThat(response.getError()).as("Lookup error code").isEqualTo(expectedError);
+ assertThat(response.getMessage()).as("Lookup error message").isNotBlank();
+ assertThat(channel.outboundMessages()).as("Additional responses").isEmpty();
+ return new CommandLookupTopicResponse().copyFrom(response);
+ } finally {
+ buffer.release();
+ }
+ }
+
+ private void assertGenericErrorResponse(ServerError expectedError) {
+ ByteBuf buffer = channel.readOutbound();
+ assertThat(buffer).as("Schema error response").isNotNull();
+ try {
+ BaseCommand command = decodeCommand(buffer);
+ assertThat(command.getType()).as("Response command type").isEqualTo(BaseCommand.Type.ERROR);
+ assertThat(command.getError().getRequestId()).as("Client request ID").isEqualTo(CLIENT_REQUEST_ID);
+ assertThat(command.getError().getError()).as("Error code").isEqualTo(expectedError);
+ assertThat(channel.outboundMessages()).as("Additional responses").isEmpty();
+ } finally {
+ buffer.release();
+ }
+ verify(connectionPool, never()).getConnection(any(InetSocketAddress.class));
+ verifyNoBackendLookup();
+ }
+
+ private CommandPartitionedTopicMetadata newRequest() {
+ return new CommandPartitionedTopicMetadata()
+ .setTopic(TOPIC)
+ .setRequestId(CLIENT_REQUEST_ID)
+ .setMetadataAutoCreationEnabled(false);
+ }
+
+ private void assertForwardedRequest(boolean autoCreationEnabled) {
+ assertThat(forwardedRequest).as("Forwarded request").isNotNull();
+ try {
+ BaseCommand command = decodeCommand(forwardedRequest);
+ assertThat(command.getType()).as("Forwarded command type")
+ .isEqualTo(BaseCommand.Type.PARTITIONED_METADATA);
+ assertThat(command.getPartitionMetadata().getRequestId()).as("Broker request ID")
+ .isEqualTo(BROKER_REQUEST_ID);
+ assertThat(command.getPartitionMetadata().getTopic()).as("Forwarded topic").isEqualTo(TOPIC);
+ assertThat(command.getPartitionMetadata().isMetadataAutoCreationEnabled())
+ .as("Metadata auto creation flag").isEqualTo(autoCreationEnabled);
+ } finally {
+ forwardedRequest.release();
+ forwardedRequest = null;
+ }
+ }
+
+ private BaseCommand decodeCommand(ByteBuf buffer) {
+ int frameSize = buffer.readInt();
+ assertThat(frameSize).as("Frame size").isEqualTo(buffer.readableBytes());
+ int commandSize = buffer.readInt();
+ BaseCommand command = new BaseCommand();
+ command.parseFrom(buffer, commandSize);
+ assertThat(buffer.isReadable()).as("Bytes after the command").isFalse();
+ return command;
+ }
+
+ private CommandPartitionedTopicMetadataResponse readMetadataResponse() {
+ ByteBuf buffer = channel.readOutbound();
+ assertThat(buffer).as("Partition metadata response").isNotNull();
+ try {
+ BaseCommand command = decodeCommand(buffer);
+ assertThat(command.getType()).as("Response command type")
+ .isEqualTo(BaseCommand.Type.PARTITIONED_METADATA_RESPONSE);
+ assertThat(command.hasPartitionMetadataResponse()).as("Partition metadata response payload").isTrue();
+ assertThat(command.hasLookupTopicResponse()).as("Topic lookup response payload").isFalse();
+ CommandPartitionedTopicMetadataResponse response = command.getPartitionMetadataResponse();
+ assertThat(response.getRequestId()).as("Client request ID").isEqualTo(CLIENT_REQUEST_ID);
+ assertThat(channel.outboundMessages()).as("Additional responses").isEmpty();
+ return new CommandPartitionedTopicMetadataResponse().copyFrom(response);
+ } finally {
+ buffer.release();
+ }
+ }
+
+ private CommandPartitionedTopicMetadataResponse assertErrorResponse(ServerError expectedError) {
+ CommandPartitionedTopicMetadataResponse response = readMetadataResponse();
+ assertThat(response.getResponse()).as("Metadata lookup result")
+ .isEqualTo(CommandPartitionedTopicMetadataResponse.LookupType.Failed);
+ assertThat(response.hasPartitions()).as("Partition count in an error response").isFalse();
+ assertThat(response.hasError()).as("Error code presence").isTrue();
+ assertThat(response.getError()).as("Broker error code").isEqualTo(expectedError);
+ return response;
+ }
+
+ private void assertErrorResponse(ServerError expectedError, String expectedMessage) {
+ CommandPartitionedTopicMetadataResponse response = assertErrorResponse(expectedError);
+ assertThat(response.hasMessage()).as("Error message presence").isEqualTo(expectedMessage != null);
+ if (expectedMessage != null) {
+ assertThat(response.getMessage()).as("Broker error message").isEqualTo(expectedMessage);
+ }
+ }
+}
(pulsar) 10/23: [fix][txn] Fix reuse of recycled pooled objects in transaction code paths (#27057)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 1a314116cd8d0b58e44c3d8d12d02e11bad3456b
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 02:27:01 2026 +0300
[fix][txn] Fix reuse of recycled pooled objects in transaction code paths (#27057)
(cherry picked from commit 4c0b9bd68f532ad7462677f296272ff7a4c2eaf1)
---
.../broker/service/persistent/PersistentTopic.java | 39 ++++++++++----
.../pulsar/broker/service/PersistentTopicTest.java | 29 ++++++++++
.../client/impl/TransactionMetaStoreHandler.java | 20 ++++++-
.../impl/TransactionMetaStoreHandlerTest.java | 40 ++++++++++++++
.../coordinator/impl/TxnLogBufferedWriter.java | 13 ++++-
.../coordinator/impl/TxnLogBufferedWriterTest.java | 63 ++++++++++++++++++++++
6 files changed, 191 insertions(+), 13 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
index bf06351f270b..9b691a9fe13c 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
@@ -5331,25 +5331,42 @@ public class PersistentTopic extends AbstractTopic implements Topic, AddEntryCal
messageDeduplication.isDuplicate(publishContext, headersAndPayload);
switch (status) {
case NotDup:
+ // Handle success and failure in a single stage so that an exception thrown while handling the
+ // success can't complete the (recycled) publish context a second time as a failure.
transactionBuffer.appendBufferToTxn(txnID, publishContext.getSequenceId(), headersAndPayload)
- .thenAccept(position -> {
+ .handle((position, throwable) -> {
+ if (throwable != null) {
+ throwable = FutureUtil.unwrapCompletionException(throwable);
+ if (throwable instanceof NotAllowedException) {
+ publishContext.completed((NotAllowedException) throwable, -1, -1);
+ decrementPendingWriteOpsAndCheck();
+ } else {
+ addFailed(ManagedLedgerException.getManagedLedgerException(throwable),
+ publishContext);
+ }
+ return null;
+ }
// Message has been successfully persisted
- messageDeduplication.recordMessagePersisted(publishContext,
- position);
- publishContext.setProperty("txn_id", txnID.toString());
+ try {
+ messageDeduplication.recordMessagePersisted(publishContext,
+ position);
+ publishContext.setProperty("txn_id", txnID.toString());
+ } catch (Throwable t) {
+ // The publish context hasn't been completed yet, so it can still be failed once
+ addFailed(ManagedLedgerException.getManagedLedgerException(t), publishContext);
+ return null;
+ }
publishContext.completed(null, position.getLedgerId(),
position.getEntryId());
decrementPendingWriteOpsAndCheck();
+ return null;
})
.exceptionally(throwable -> {
- throwable = FutureUtil.unwrapCompletionException(throwable);
- if (throwable instanceof NotAllowedException) {
- publishContext.completed((NotAllowedException) throwable, -1, -1);
- decrementPendingWriteOpsAndCheck();
- } else {
- addFailed(ManagedLedgerException.getManagedLedgerException(throwable), publishContext);
- }
+ // Only reached when the handler above throws; the publish context is not completed again.
+ log.warn().attr("txnId", txnID)
+ .exception(throwable)
+ .log("Failed to handle the result of appending a transactional message");
return null;
});
break;
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java
index a10bdd3be585..ab9fbb133d9b 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java
@@ -31,6 +31,7 @@ import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.matches;
import static org.mockito.Mockito.mock;
@@ -74,6 +75,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -114,6 +116,8 @@ import org.apache.pulsar.broker.service.persistent.PersistentSubscription;
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.broker.service.persistent.PulsarCompactorSubscription;
import org.apache.pulsar.broker.testcontext.PulsarTestContext;
+import org.apache.pulsar.broker.transaction.buffer.TransactionBuffer;
+import org.apache.pulsar.broker.transaction.buffer.TransactionBufferProvider;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.Topics;
import org.apache.pulsar.client.api.MessageId;
@@ -362,6 +366,31 @@ public class PersistentTopicTest extends MockedBookKeeperTestCase {
"Topics without a replicated-subscription controller should not maintain the snapshot timestamp");
}
+ @Test
+ public void testPublishTxnMessageCompletesPublishContextOnce() throws Exception {
+ pulsarTestContext.getConfig().setTransactionCoordinatorEnabled(true);
+ TransactionBuffer transactionBuffer = mock(TransactionBuffer.class);
+ doReturn(CompletableFuture.completedFuture(PositionFactory.create(1, 2)))
+ .when(transactionBuffer).appendBufferToTxn(any(), anyLong(), any());
+ TransactionBufferProvider transactionBufferProvider = mock(TransactionBufferProvider.class);
+ doReturn(transactionBuffer).when(transactionBufferProvider).newTransactionBuffer(any());
+ doReturn(transactionBufferProvider).when(pulsarTestContext.getPulsarService()).getTransactionBufferProvider();
+ PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService);
+ assertThat(topic.getTransactionBuffer()).isSameAs(transactionBuffer);
+
+ // Completing the publish context fails after it may have already handed itself over, e.g. when the
+ // connection's executor rejects the task.
+ Topic.PublishContext publishContext = mock(Topic.PublishContext.class);
+ doThrow(new RejectedExecutionException("rejected"))
+ .when(publishContext).completed(any(), anyLong(), anyLong());
+
+ topic.publishTxnMessage(new TxnID(1, 2), Unpooled.wrappedBuffer("content".getBytes()), publishContext);
+
+ // The failure must not complete the publish context a second time.
+ verify(publishContext, times(1)).completed(any(), anyLong(), anyLong());
+ verify(publishContext).completed(null, 1, 2);
+ }
+
@Test
public void testDispatcherMultiConsumerReadFailed() {
PersistentTopic topic =
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java
index 64dd7ef43449..6c144fdccbd2 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java
@@ -29,6 +29,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
+import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -213,7 +214,7 @@ public class TransactionMetaStoreHandler extends HandlerState
.log("Transaction coordinator client connect success! tcId");
if (registerToConnection(cnx)) {
this.connectionHandler.resetBackoff();
- pendingRequests.forEach((requestID, opBase) -> checkStateAndSendRequest(opBase));
+ resendPendingRequests();
}
future.complete(null);
});
@@ -260,6 +261,18 @@ public class TransactionMetaStoreHandler extends HandlerState
}
}
+ private void resendPendingRequests() {
+ // this method is executed in internalPinnedExecutor.
+ List<Long> failedRequestIds = new ArrayList<>();
+ pendingRequests.forEach((requestId, op) -> {
+ if (!checkStateAndSendRequest(op)) {
+ // The op has been completed and recycled, it must not stay in pendingRequests.
+ failedRequestIds.add(requestId);
+ }
+ });
+ failedRequestIds.forEach(pendingRequests::remove);
+ }
+
private void failPendingRequest() {
// this method is executed in internalPinnedExecutor.
pendingRequests.forEach((k, op) -> {
@@ -884,6 +897,11 @@ public class TransactionMetaStoreHandler extends HandlerState
this.setState(State.Closed);
}
+ @VisibleForTesting
+ int getPendingRequestsCount() {
+ return (int) pendingRequests.size();
+ }
+
@VisibleForTesting
public State getConnectHandleState() {
return getState();
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java
index 218a2781b7df..5bee521b6a8a 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java
@@ -18,8 +18,10 @@
*/
package org.apache.pulsar.client.impl;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -29,7 +31,12 @@ import static org.testng.Assert.assertTrue;
import io.netty.channel.Channel;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import lombok.Cleanup;
import org.apache.pulsar.client.api.PulsarClient;
+import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException;
+import org.apache.pulsar.client.api.transaction.TxnID;
import org.awaitility.Awaitility;
import org.testng.annotations.Test;
@@ -62,4 +69,37 @@ public class TransactionMetaStoreHandlerTest {
client.close();
}
+
+ @Test
+ public void testFailedResendOnReconnectRemovesPendingRequest() throws Exception {
+ @Cleanup
+ final PulsarClientImpl client = (PulsarClientImpl) PulsarClient.builder()
+ .serviceUrl("pulsar://localhost:6650").build();
+ final CompletableFuture<Void> connectFuture = new CompletableFuture<>();
+ final TransactionMetaStoreHandler handler = new TransactionMetaStoreHandler(
+ 0L, client, "topic", connectFuture);
+
+ // Not connected yet: the request stays queued until the connection is opened.
+ final CompletableFuture<TxnID> txnFuture = handler.newTransactionAsync(1, TimeUnit.MINUTES);
+ Awaitility.await().untilAsserted(() -> assertEquals(handler.getPendingRequestsCount(), 1));
+
+ final ClientCnx cnx = mock(ClientCnx.class);
+ when(cnx.getRemoteEndpointProtocolVersion()).thenReturn(19);
+ when(cnx.sendRequestWithId(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
+ when(cnx.channel()).thenReturn(mock(Channel.class));
+ // The handler is closed concurrently after it switched to Ready, but before it resends the pending
+ // requests, so resending them fails.
+ doAnswer(invocation -> {
+ handler.close();
+ return null;
+ }).when(cnx).registerTransactionMetaStoreHandler(anyLong(), any());
+
+ handler.connectionOpened(cnx).get(10, TimeUnit.SECONDS);
+
+ assertThat(txnFuture).failsWithin(Duration.ofSeconds(10))
+ .withThrowableOfType(ExecutionException.class)
+ .withCauseInstanceOf(TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException.class);
+ // The failed request has been completed and its op recycled, so it must not stay pending.
+ assertEquals(handler.getPendingRequestsCount(), 0);
+ }
}
diff --git a/pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java b/pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java
index 08a6df8f3aff..250af6237e32 100644
--- a/pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java
+++ b/pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java
@@ -19,6 +19,7 @@
package org.apache.pulsar.transaction.coordinator.impl;
import static org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerInterceptException;
+import com.google.common.annotations.VisibleForTesting;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.Recycler;
@@ -274,9 +275,15 @@ public class TxnLogBufferedWriter<T> {
trigFlushIfReachMaxRecordsOrMaxSize();
}
- private void trigFlushByTimingTask(){
+ @VisibleForTesting
+ void trigFlushByTimingTask(){
CompletableFuture
.runAsync(() -> {
+ // A timing flush that was queued before "close()" may run after the close task has recycled the
+ // flush context, which may already be reused by another writer that shares this executor.
+ if (state == State.CLOSING || state == State.CLOSED) {
+ return;
+ }
if (flushContext.asyncAddArgsList.isEmpty()) {
return;
}
@@ -390,6 +397,10 @@ public class TxnLogBufferedWriter<T> {
new ManagedLedgerException.ManagedLedgerFencedException(
new Exception("Transaction log buffered write has closed")
));
+ // The recycled flush context may be reused by another writer, don't keep a reference to it.
+ flushContext = null;
+ dataArray.clear();
+ bytesSize = 0;
// Cancel the timing task.
if (!timeout.isCancelled()) {
this.timeout.cancel();
diff --git a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java
index 2ff730cf4e3e..d7cab618c51e 100644
--- a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java
+++ b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java
@@ -40,6 +40,8 @@ import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@@ -544,6 +546,67 @@ public class TxnLogBufferedWriterTest extends MockedBookKeeperTestCase {
threadPoolExecutor.shutdown();
}
+ /**
+ * A timing flush that runs after {@link TxnLogBufferedWriter#close()} must not touch the flush context that the
+ * close task recycled: writers share the executor thread, so another writer may already be using the recycled
+ * flush context.
+ */
+ @Test
+ public void testTimingFlushAfterCloseDoesNotAffectOtherWriter() throws Exception {
+ ManagedLedger managedLedger = Mockito.mock(ManagedLedger.class);
+ Mockito.when(managedLedger.getName()).thenReturn(mlName);
+ Mockito.doAnswer(invocation -> {
+ AsyncCallbacks.AddEntryCallback callback = invocation.getArgument(1);
+ callback.addComplete(PositionFactory.create(1, 1), invocation.getArgument(0),
+ invocation.getArgument(2));
+ return null;
+ }).when(managedLedger).asyncAddEntry(Mockito.any(ByteBuf.class), Mockito.any(), Mockito.any());
+ // Both writers share the same single thread, like the writers of the topics that share a ML executor.
+ ExecutorService sharedExecutor =
+ Executors.newSingleThreadExecutor(new DefaultThreadFactory("txn-shared-executor"));
+ HashedWheelTimer transactionTimer = new HashedWheelTimer(new DefaultThreadFactory("transaction-timer"),
+ 1, TimeUnit.MILLISECONDS);
+ SumStrDataSerializer dataSerializer = new SumStrDataSerializer();
+ TxnLogBufferedWriter.AddDataCallback callbackA = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class);
+ TxnLogBufferedWriter.AddDataCallback callbackB = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class);
+ try {
+ TxnLogBufferedWriter<Integer> writerA = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor,
+ transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true,
+ DISABLED_BUFFERED_WRITER_METRICS);
+ // Flush once, so that writer A's current flush context is obtained on the shared executor thread.
+ writerA.asyncAddData(1, callbackA, 1);
+ writerA.asyncAddData(1, callbackA, 2);
+ Awaitility.await().untilAsserted(() ->
+ Mockito.verify(callbackA, Mockito.times(2)).addComplete(Mockito.any(), Mockito.any()));
+ // Closing recycles writer A's current flush context on the shared executor thread.
+ writerA.close().get();
+
+ TxnLogBufferedWriter<Integer> writerB = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor,
+ transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true,
+ DISABLED_BUFFERED_WRITER_METRICS);
+ // The flush obtains a new flush context, which may be the one that writer A recycled.
+ writerB.asyncAddData(1, callbackB, 1);
+ writerB.asyncAddData(1, callbackB, 2);
+ // This request stays in writer B's current flush context.
+ writerB.asyncAddData(1, callbackB, 3);
+ sharedExecutor.submit(() -> { }).get();
+
+ // A timing flush of the closed writer A, e.g. one that was queued before the close task ran.
+ writerA.trigFlushByTimingTask();
+ sharedExecutor.submit(() -> { }).get();
+ Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any());
+
+ writerB.trigFlushByTimingTask();
+ Awaitility.await().untilAsserted(() ->
+ Mockito.verify(callbackB, Mockito.times(3)).addComplete(Mockito.any(), Mockito.any()));
+ Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any());
+ writerB.close().get();
+ } finally {
+ transactionTimer.stop();
+ sharedExecutor.shutdownNow();
+ }
+ }
+
private static class JsonDataSerializer implements TxnLogBufferedWriter.DataSerializer<Integer>{
private static ObjectMapper objectMapper = new ObjectMapper();
(pulsar) 18/23: [fix][ml] Don't trim ledgers while cursors are lazily recovering (#20814)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit d3bd6b6fa44e91977d14eb541d28c70ed97f8a90
Author: lifepuzzlefun <wj...@163.com>
AuthorDate: Fri Oct 23 09:44:41 2026 +0800
[fix][ml] Don't trim ledgers while cursors are lazily recovering (#20814)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 4aa22863c231ca3afb5cbb14541741ef44506561)
---
.../bookkeeper/mledger/impl/ManagedLedgerImpl.java | 99 +++++++++------
.../bookkeeper/mledger/impl/ManagedLedgerTest.java | 136 +++++++++++++++++++++
2 files changed, 201 insertions(+), 34 deletions(-)
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
index b26fed3e4d45..13be9dd146f2 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
@@ -228,6 +228,10 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
// uninitialized cursor future from the 1st request
final Map<String, CompletableFuture<ManagedCursor>> uninitializedCursors;
+ // Cursors whose lazy recovery failed: they are recovered again when opened, and until then they block trimming,
+ // since their mark-delete position is unknown
+ final Set<String> failedLazyRecoveryCursors;
+
final EntryCache entryCache;
private ScheduledFuture<?> timeoutTask;
@@ -453,6 +457,7 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
this.waitingCursors = Queues.newConcurrentLinkedQueue();
this.waitingEntryCallBacks = Queues.newConcurrentLinkedQueue();
this.uninitializedCursors = new HashMap<>();
+ this.failedLazyRecoveryCursors = new HashSet<>();
this.clock = config.getClock();
// Get the next rollover time. Add a random value upto 5% to avoid rollover multiple ledgers at the same time
@@ -815,38 +820,7 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
} else {
// Lazily recover cursors by put them to uninitializedCursors map.
for (final String cursorName : consumers) {
- log.debug().attr("cursorName", cursorName).log("Recovering cursor lazily");
- final ManagedCursorImpl cursor;
- cursor = createCursor(ManagedLedgerImpl.this.bookKeeper, cursorName);
- final long timestampStartRecoverCursor = System.currentTimeMillis();
- CompletableFuture<ManagedCursor> cursorRecoveryFuture = new CompletableFuture<>();
- uninitializedCursors.put(cursorName, cursorRecoveryFuture);
-
- cursor.recover(new VoidCallback() {
- @Override
- public void operationComplete() {
- log.info().attr("cursorName", cursorName)
- .attr("position", cursor.getMarkDeletedPosition())
- .attr("remaining", cursorCount.get() - 1)
- .attr("cost ms", System.currentTimeMillis() - timestampStartRecoverCursor)
- .log("Lazy recovery for cursor completed");
- cursor.setActive();
- synchronized (ManagedLedgerImpl.this) {
- addCursor(cursor);
- uninitializedCursors.remove(cursor.getName()).complete(cursor);
- }
- }
-
- @Override
- public void operationFailed(ManagedLedgerException exception) {
- log.warn().attr("cursorName", cursorName).exception(exception)
- .attr("cost ms", System.currentTimeMillis() - timestampStartRecoverCursor)
- .log("Lazy recovery for cursor failed");
- synchronized (ManagedLedgerImpl.this) {
- uninitializedCursors.remove(cursor.getName()).completeExceptionally(exception);
- }
- }
- });
+ recoverCursorLazily(cursorName);
}
// Complete ledger recovery.
callback.initializeComplete();
@@ -861,6 +835,42 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
});
}
+ private synchronized CompletableFuture<ManagedCursor> recoverCursorLazily(String cursorName) {
+ log.debug().attr("cursorName", cursorName).log("Recovering cursor lazily");
+ final ManagedCursorImpl cursor = createCursor(bookKeeper, cursorName);
+ final long timestampStartRecoverCursor = System.currentTimeMillis();
+ CompletableFuture<ManagedCursor> cursorRecoveryFuture = new CompletableFuture<>();
+ uninitializedCursors.put(cursorName, cursorRecoveryFuture);
+
+ cursor.recover(new VoidCallback() {
+ @Override
+ public void operationComplete() {
+ log.info().attr("cursorName", cursorName)
+ .attr("position", cursor.getMarkDeletedPosition())
+ .attr("cost ms", System.currentTimeMillis() - timestampStartRecoverCursor)
+ .log("Lazy recovery for cursor completed");
+ cursor.setActive();
+ synchronized (ManagedLedgerImpl.this) {
+ failedLazyRecoveryCursors.remove(cursorName);
+ addCursor(cursor);
+ uninitializedCursors.remove(cursorName).complete(cursor);
+ }
+ }
+
+ @Override
+ public void operationFailed(ManagedLedgerException exception) {
+ log.warn().attr("cursorName", cursorName).exception(exception)
+ .attr("cost ms", System.currentTimeMillis() - timestampStartRecoverCursor)
+ .log("Lazy recovery for cursor failed");
+ synchronized (ManagedLedgerImpl.this) {
+ failedLazyRecoveryCursors.add(cursorName);
+ uninitializedCursors.remove(cursorName).completeExceptionally(exception);
+ }
+ }
+ });
+ return cursorRecoveryFuture;
+ }
+
private void addCursor(ManagedCursorImpl cursor) {
Position positionForOrdering = null;
if (cursor.isDurable()) {
@@ -1192,8 +1202,12 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
return;
}
- if (uninitializedCursors.containsKey(cursorName)) {
- uninitializedCursors.get(cursorName).thenAccept(cursor -> callback.openCursorComplete(cursor, ctx))
+ // A cursor whose lazy recovery failed still has its position persisted: recover it again rather than
+ // replacing it with a new one
+ CompletableFuture<ManagedCursor> uninitializedCursor = failedLazyRecoveryCursors.contains(cursorName)
+ ? recoverCursorLazily(cursorName) : uninitializedCursors.get(cursorName);
+ if (uninitializedCursor != null) {
+ uninitializedCursor.thenAccept(cursor -> callback.openCursorComplete(cursor, ctx))
.exceptionally(ex -> {
callback.openCursorFailed(ManagedLedgerException
.getManagedLedgerException(FutureUtil.unwrapCompletionException(ex)), ctx);
@@ -3721,6 +3735,23 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
promise.completeExceptionally(new ManagedLedgerFencedException("Can't trim fenced ledger"));
return;
}
+ // The slowest position below only covers the cursors in the container: a cursor that is still being
+ // recovered (or created) isn't there yet, and its mark-delete position may be in any ledger
+ if (!uninitializedCursors.isEmpty()) {
+ log.debug().attr("cursors", uninitializedCursors.keySet())
+ .log("Deferring trimming until the cursors are initialized");
+ trimmerMutex.unlock();
+ scheduleDeferredTrimming(isTruncate, promise);
+ return;
+ }
+ if (!failedLazyRecoveryCursors.isEmpty()) {
+ log.debug().attr("cursors", failedLazyRecoveryCursors)
+ .log("Ignoring trimming request since cursors failed to recover");
+ trimmerMutex.unlock();
+ promise.completeExceptionally(new ManagedLedgerException(
+ "Can't trim ledger until cursors are recovered: " + failedLazyRecoveryCursors));
+ return;
+ }
// A terminated managed ledger has no current ledger once its final ledger was deleted from BookKeeper,
// and that final ledger is then kept like a current one
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
index da6129044abc..2fc27515256c 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
@@ -77,10 +77,12 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -3592,6 +3594,140 @@ public class ManagedLedgerTest extends MockedBookKeeperTestCase {
assertEquals(cursor.getMarkDeletedPosition(), p1);
}
+ /**
+ * Returns a factory whose managed ledgers recover each cursor once the future of its name in
+ * {@code recoveryGates} completes, and fail its recovery if that future fails.
+ */
+ private ManagedLedgerFactoryImpl createFactoryWithGatedCursorRecovery(
+ Map<String, CompletableFuture<Void>> recoveryGates) throws Exception {
+ return new ManagedLedgerFactoryImpl(metadataStore, bkc) {
+ @Override
+ protected ManagedLedgerImpl createManagedLedger(BookKeeper bk, MetaStore store, String name,
+ ManagedLedgerConfig config,
+ Supplier<CompletableFuture<Boolean>> mlOwnershipChecker) {
+ return new ManagedLedgerImpl(this, bk, store, config, scheduledExecutor, name, mlOwnershipChecker) {
+ @Override
+ protected ManagedCursorImpl createCursor(BookKeeper bookKeeper, String cursorName) {
+ return new ManagedCursorImpl(bookKeeper, this, cursorName) {
+ @Override
+ void recover(VoidCallback callback) {
+ recoveryGates.get(cursorName).whenComplete((__, ex) -> {
+ if (ex != null) {
+ callback.operationFailed(new ManagedLedgerException(ex));
+ } else {
+ super.recover(callback);
+ }
+ });
+ }
+ };
+ }
+ };
+ }
+ };
+ }
+
+ @Test
+ public void testLazyCursorRecoveryDefersTrimming() throws Exception {
+ ManagedLedgerConfig config = initManagedLedgerConfig(defaultConfig()).setMaxEntriesPerLedger(2);
+ ManagedLedger ledger = factory.open("testLazyCursorRecoveryDefersTrimming", config);
+ ManagedCursor slowCursor = ledger.openCursor("slow-cursor");
+ ManagedCursor fastCursor = ledger.openCursor("fast-cursor");
+ Position lastPosition = null;
+ for (int i = 0; i < 6; i++) {
+ lastPosition = ledger.addEntry(("entry-" + i).getBytes());
+ }
+ Position slowPosition = slowCursor.getMarkDeletedPosition();
+ fastCursor.markDelete(lastPosition);
+ ledger.close();
+
+ Map<String, CompletableFuture<Void>> recoveryGates = new ConcurrentHashMap<>();
+ recoveryGates.put("slow-cursor", new CompletableFuture<>());
+ recoveryGates.put("fast-cursor", new CompletableFuture<>());
+ @Cleanup("shutdown")
+ ManagedLedgerFactoryImpl factory2 = createFactoryWithGatedCursorRecovery(recoveryGates);
+ ManagedLedgerImpl reopened = (ManagedLedgerImpl) factory2.open("testLazyCursorRecoveryDefersTrimming",
+ initManagedLedgerConfig(defaultConfig()).setMaxEntriesPerLedger(2).setLazyCursorRecovery(true));
+ List<Long> ledgerIds = new ArrayList<>(reopened.getLedgersInfo().keySet());
+
+ // No cursor recovered yet: trimming must not see the managed ledger as having no durable cursors
+ CompletableFuture<Void> trimmed = new CompletableFuture<>();
+ reopened.trimConsumedLedgersInBackground(trimmed);
+ Awaitility.await().during(500, TimeUnit.MILLISECONDS).atMost(5, TimeUnit.SECONDS)
+ .until(() -> !trimmed.isDone());
+ assertEquals(new ArrayList<>(reopened.getLedgersInfo().keySet()), ledgerIds);
+
+ // Only the fast cursor recovered: its position alone must not decide the trimming
+ recoveryGates.get("fast-cursor").complete(null);
+ assertEquals(reopened.openCursor("fast-cursor").getMarkDeletedPosition(), lastPosition);
+ Awaitility.await().during(500, TimeUnit.MILLISECONDS).atMost(5, TimeUnit.SECONDS)
+ .until(() -> !trimmed.isDone());
+ assertEquals(new ArrayList<>(reopened.getLedgersInfo().keySet()), ledgerIds);
+
+ // Once the slow cursor recovered, the deferred trimming completes and keeps the ledgers it needs
+ recoveryGates.get("slow-cursor").complete(null);
+ trimmed.get(5, TimeUnit.SECONDS);
+ ManagedCursor recoveredSlowCursor = reopened.openCursor("slow-cursor");
+ assertEquals(recoveredSlowCursor.getMarkDeletedPosition(), slowPosition);
+ assertEquals(new ArrayList<>(reopened.getLedgersInfo().keySet()), ledgerIds);
+ assertEquals(recoveredSlowCursor.getNumberOfEntriesInBacklog(false), 6);
+
+ // Trimming proceeds normally after the slow cursor acknowledges everything
+ recoveredSlowCursor.markDelete(lastPosition);
+ CompletableFuture<Void> trimmedAfterAck = new CompletableFuture<>();
+ reopened.trimConsumedLedgersInBackground(trimmedAfterAck);
+ trimmedAfterAck.get(5, TimeUnit.SECONDS);
+ assertTrue(reopened.getLedgersInfo().size() < ledgerIds.size());
+ }
+
+ @Test
+ public void testFailedLazyCursorRecoveryBlocksTrimmingUntilRecovered() throws Exception {
+ ManagedLedgerConfig config = initManagedLedgerConfig(defaultConfig()).setMaxEntriesPerLedger(2);
+ ManagedLedger ledger = factory.open("testFailedLazyCursorRecovery", config);
+ ManagedCursor cursor = ledger.openCursor("cursor");
+ Position lastPosition = null;
+ for (int i = 0; i < 6; i++) {
+ lastPosition = ledger.addEntry(("entry-" + i).getBytes());
+ }
+ Position markDeletePosition = cursor.getMarkDeletedPosition();
+ ledger.close();
+
+ Map<String, CompletableFuture<Void>> recoveryGates = new ConcurrentHashMap<>();
+ recoveryGates.put("cursor", CompletableFuture.failedFuture(new Exception("recovery failed")));
+ @Cleanup("shutdown")
+ ManagedLedgerFactoryImpl factory2 = createFactoryWithGatedCursorRecovery(recoveryGates);
+ ManagedLedgerImpl reopened = (ManagedLedgerImpl) factory2.open("testFailedLazyCursorRecovery",
+ initManagedLedgerConfig(defaultConfig()).setMaxEntriesPerLedger(2).setLazyCursorRecovery(true));
+ List<Long> ledgerIds = new ArrayList<>(reopened.getLedgersInfo().keySet());
+
+ // The failed cursor isn't known to the managed ledger, but its position still protects the ledgers
+ Awaitility.await().until(() -> {
+ synchronized (reopened) {
+ return reopened.uninitializedCursors.isEmpty();
+ }
+ });
+ CompletableFuture<Void> trimmed = new CompletableFuture<>();
+ reopened.trimConsumedLedgersInBackground(trimmed);
+ try {
+ trimmed.get(5, TimeUnit.SECONDS);
+ fail("Trimming should fail while a cursor isn't recovered");
+ } catch (ExecutionException e) {
+ assertTrue(e.getCause() instanceof ManagedLedgerException);
+ }
+ assertEquals(new ArrayList<>(reopened.getLedgersInfo().keySet()), ledgerIds);
+
+ // Opening the cursor recovers it again instead of creating it at the end of the managed ledger
+ recoveryGates.put("cursor", CompletableFuture.completedFuture(null));
+ ManagedCursor recovered = reopened.openCursor("cursor");
+ assertEquals(recovered.getMarkDeletedPosition(), markDeletePosition);
+ assertEquals(recovered.getNumberOfEntriesInBacklog(false), 6);
+
+ recovered.markDelete(lastPosition);
+ CompletableFuture<Void> trimmedAfterAck = new CompletableFuture<>();
+ reopened.trimConsumedLedgersInBackground(trimmedAfterAck);
+ trimmedAfterAck.get(5, TimeUnit.SECONDS);
+ assertTrue(reopened.getLedgersInfo().size() < ledgerIds.size());
+ }
+
@Test
public void testConcurrentOpenCursor() throws Exception {
ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("testConcurrentOpenCursor",
(pulsar) 09/23: [fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit ab530fa967bca16531ee8d60586c5a155080bf9f
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 02:26:26 2026 +0300
[fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)
(cherry picked from commit aeaf47e5458af76c900e3dccbbe9ac1a575f2750)
---
.../bookkeeper/mledger/impl/ManagedLedgerImpl.java | 14 ++++-
.../bookkeeper/mledger/impl/ManagedLedgerTest.java | 72 ++++++++++++++++++++++
2 files changed, 85 insertions(+), 1 deletion(-)
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
index 643afc6a4ebd..b26fed3e4d45 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
@@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Math.min;
import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.pulsar.common.util.Runnables.catchingAndLoggingThrowables;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.BoundType;
import com.google.common.collect.Lists;
@@ -5460,10 +5461,21 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
if (config.getAddEntryTimeoutSeconds() > 0) {
long timeoutSec = config.getAddEntryTimeoutSeconds();
this.timeoutTask = this.scheduledExecutor.scheduleAtFixedRate(
- this::checkAddTimeout, timeoutSec, timeoutSec, TimeUnit.SECONDS);
+ catchingAndLoggingThrowables(this::scheduleAddTimeoutCheck), timeoutSec, timeoutSec,
+ TimeUnit.SECONDS);
}
}
+ /**
+ * Runs the add timeout check on the managed ledger executor. The pending adds complete and get recycled on that
+ * executor, so checking the head of the queue from the scheduler thread could read a recycled, possibly reused,
+ * OpAddEntry. An exception must not escape to the scheduler, or the periodic check would stop for good.
+ */
+ @VisibleForTesting
+ void scheduleAddTimeoutCheck() {
+ executor.execute(catchingAndLoggingThrowables(this::checkAddTimeout));
+ }
+
private void checkAddTimeout() {
final State state = STATE_UPDATER.get(this);
if (state == State.Closed
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
index c1017299783c..da6129044abc 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
@@ -4103,6 +4103,78 @@ public class ManagedLedgerTest extends MockedBookKeeperTestCase {
factory.delete(ledger.name);
}
+ /**
+ * The add timeout check runs on the managed ledger executor, after the add completions already queued there. The
+ * check must not act on an add that has completed: once its completion runs, the add is recycled and may be
+ * reused by another add, possibly of another managed ledger.
+ */
+ @Test(timeOut = 30000)
+ public void testAddTimeoutCheckRunsAfterQueuedAddCompletion() throws Exception {
+ // A timeout this long keeps the periodic check from running by itself: the test triggers it.
+ ManagedLedgerConfig config = initManagedLedgerConfig(defaultConfig()).setAddEntryTimeoutSeconds(3600);
+ ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("add_timeout_check_after_completion", config);
+
+ // Hold the bookie's add response, to deliver it at a chosen moment.
+ record BookieAdd(AddCallback callback, Object ctx) {
+ }
+ CompletableFuture<BookieAdd> bookieAdd = new CompletableFuture<>();
+ LedgerHandle spyLedger = spy(ledger.currentLedger);
+ doAnswer(invocation -> {
+ ((ByteBuf) invocation.getArgument(0)).release();
+ bookieAdd.complete(new BookieAdd(invocation.getArgument(1), invocation.getArgument(2)));
+ return null;
+ }).when(spyLedger).asyncAddEntry(any(ByteBuf.class), any(AddCallback.class), any());
+ ledger.currentLedger = spyLedger;
+
+ CompletableFuture<Position> addResult = new CompletableFuture<>();
+ ledger.asyncAddEntry("entry".getBytes(UTF_8), new AddEntryCallback() {
+ @Override
+ public void addComplete(Position position, ByteBuf entryData, Object ctx) {
+ addResult.complete(position);
+ }
+
+ @Override
+ public void addFailed(ManagedLedgerException exception, Object ctx) {
+ addResult.completeExceptionally(exception);
+ }
+ }, null);
+ BookieAdd pendingBookieAdd = bookieAdd.get(10, TimeUnit.SECONDS);
+ OpAddEntry op = ledger.pendingAddEntries.peek();
+ assertThat(op).isNotNull();
+ // Make the add older than the timeout.
+ op.lastInitTime = System.nanoTime() - TimeUnit.HOURS.toNanos(2);
+
+ CountDownLatch executorBlocked = new CountDownLatch(1);
+ CountDownLatch releaseExecutor = new CountDownLatch(1);
+ ledger.getExecutor().execute(() -> {
+ executorBlocked.countDown();
+ try {
+ releaseExecutor.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ assertThat(executorBlocked.await(10, TimeUnit.SECONDS)).isTrue();
+ try {
+ // The bookie confirms the add, whose completion queues on the managed ledger executor...
+ pendingBookieAdd.callback().addComplete(BKException.Code.OK, spyLedger, 0, pendingBookieAdd.ctx());
+ // ...and the periodic timeout check fires before that completion has run.
+ ledger.scheduleAddTimeoutCheck();
+ assertThat(ledger.currentLedgerTimeoutTriggered)
+ .as("timeout applied to an add whose completion is queued")
+ .isFalse();
+ } finally {
+ releaseExecutor.countDown();
+ }
+
+ assertThat(addResult.get(10, TimeUnit.SECONDS)).isEqualTo(PositionFactory.create(spyLedger.getId(), 0));
+ // Wait for the timeout check queued after the completion.
+ CompletableFuture.runAsync(() -> { }, ledger.getExecutor()).get(10, TimeUnit.SECONDS);
+ assertThat(ledger.currentLedgerTimeoutTriggered).isFalse();
+ assertThat(ledger.pendingAddEntries).isEmpty();
+ assertThat(ledger.currentLedger).isSameAs(spyLedger);
+ }
+
private static class CollectCtxAddEntryCallback implements AddEntryCallback {
public List<Object> addCompleteCtxList = new CopyOnWriteArrayList<>();
(pulsar) 08/23: [fix][broker] Reply to failed GetLastMessageId with the original request id (#27053)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 8c88cd2f1e841844f6ac620330e74070ffba362b
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 02:24:45 2026 +0300
[fix][broker] Reply to failed GetLastMessageId with the original request id (#27053)
(cherry picked from commit 014d4070e8c3e876f1979542b9aedcde97dc5f98)
---
.../apache/pulsar/broker/service/ServerCnx.java | 8 ++++--
.../pulsar/broker/service/ServerCnxTest.java | 32 ++++++++++++++++++++++
2 files changed, 37 insertions(+), 3 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
index e1a60b419a1c..d2f37d78fa2b 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
@@ -3464,11 +3464,13 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
protected void handleGetLastMessageId(CommandGetLastMessageId getLastMessageId) {
checkArgument(state == State.Connected);
+ // Capture command fields up front: the decoder reuses the command object for the next frame,
+ // so it must not be read from the async continuations below.
+ final long requestId = getLastMessageId.getRequestId();
CompletableFuture<Consumer> consumerFuture = consumers.get(getLastMessageId.getConsumerId());
if (consumerFuture != null && consumerFuture.isDone() && !consumerFuture.isCompletedExceptionally()) {
Consumer consumer = consumerFuture.getNow(null);
- long requestId = getLastMessageId.getRequestId();
Topic topic = consumer.getSubscription().getTopic();
topic.checkIfTransactionBufferRecoverCompletely()
@@ -3492,12 +3494,12 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
consumer.readCompacted());
return null;
}).exceptionally(e -> {
- writeAndFlush(Commands.newError(getLastMessageId.getRequestId(),
+ writeAndFlush(Commands.newError(requestId,
ServerError.UnknownError, "Failed to recover Transaction Buffer."));
return null;
});
} else {
- writeAndFlush(Commands.newError(getLastMessageId.getRequestId(),
+ writeAndFlush(Commands.newError(requestId,
ServerError.MetadataError, "Consumer not found"));
}
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java
index 1c7d7b99763c..c115c33079d6 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java
@@ -3030,6 +3030,38 @@ public class ServerCnxTest {
assertNull(channel.outboundMessages().peek());
channel.finish();
}
+
+ @Test(timeOut = 30000)
+ public void testGetLastMessageIdAsyncFailureRepliesWithOriginalRequestId() throws Exception {
+ CompletableFuture<Position> lastDispatchablePositionFuture = new CompletableFuture<>();
+ doReturn(lastDispatchablePositionFuture).when(ledgerMock)
+ .getLastDispatchablePosition(any(), any());
+
+ resetChannel();
+ setChannelConnected();
+
+ ByteBuf clientCommand = Commands.newSubscribe(successTopicName, successSubName, //
+ 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, 0, "test" /* consumer name */,
+ 0 /* avoid reseting cursor */);
+ channel.writeInbound(clientCommand);
+ assertTrue(getResponse() instanceof CommandSuccess);
+
+ long getLastMessageIdRequestId = 42;
+ channel.writeInbound(Commands.newGetLastMessageId(1 /* consumer id */, getLastMessageIdRequestId));
+ assertNull(channel.outboundMessages().peek());
+
+ // The next frame on the same connection makes the decoder clear and reuse its command object
+ channel.writeInbound(Commands.newFlow(1 /* consumer id */, 1 /* message permits */));
+
+ lastDispatchablePositionFuture.completeExceptionally(new RuntimeException("injected failure"));
+
+ Object response = getResponse();
+ assertThat(response).isInstanceOfSatisfying(CommandError.class, error -> {
+ assertThat(error.getRequestId()).isEqualTo(getLastMessageIdRequestId);
+ assertThat(error.getError()).isEqualTo(ServerError.UnknownError);
+ });
+ channel.finish();
+ }
@SuppressWarnings("deprecation")
@Test(timeOut = 30000)
(pulsar) 23/23: [fix][proxy] Copy GetTopicsOfNamespace properties before the broker connection completes (#27055)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 71b758c4fca2a96474c6c65554f2ddffafae9142
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 08:40:18 2026 +0300
[fix][proxy] Copy GetTopicsOfNamespace properties before the broker connection completes (#27055)
(cherry picked from commit 17166c820bf011ce7dd8b2b6795cc9c62e734af7)
---
.../pulsar/proxy/server/LookupProxyHandler.java | 20 +++---
.../proxy/server/LookupProxyHandlerTest.java | 78 ++++++++++++++++++++++
2 files changed, 88 insertions(+), 10 deletions(-)
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
index b0456d09f853..8bff0868caad 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java
@@ -29,7 +29,6 @@ import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -360,9 +359,14 @@ public class LookupProxyHandler {
? commandGetTopicsOfNamespace.getTopicsPattern() : null;
String topicsHash = commandGetTopicsOfNamespace.hasTopicsHash()
? commandGetTopicsOfNamespace.getTopicsHash() : null;
+ // The decoder reuses the command and releases its buffer once this handler returns, so the properties
+ // must be copied before the connection future completes.
+ Map<String, String> properties = new HashMap<>();
+ for (KeyValue kv : commandGetTopicsOfNamespace.getPropertiesList()) {
+ properties.put(kv.getKey(), kv.getValue());
+ }
performGetTopicsOfNamespace(clientRequestId, commandGetTopicsOfNamespace.getNamespace(), serviceUrl,
- 10, topicsPattern, topicsHash, commandGetTopicsOfNamespace.getMode(),
- commandGetTopicsOfNamespace.getPropertiesList());
+ 10, topicsPattern, topicsHash, commandGetTopicsOfNamespace.getMode(), properties);
}
private void performGetTopicsOfNamespace(long clientRequestId,
@@ -372,7 +376,7 @@ public class LookupProxyHandler {
String topicsPattern,
String topicsHash,
CommandGetTopicsOfNamespace.Mode mode,
- List<KeyValue> properties) {
+ Map<String, String> properties) {
if (numberOfRetries == 0) {
writeAndFlush(Commands.newError(clientRequestId, ServerError.ServiceNotReady,
"Reached max number of redirections"));
@@ -394,14 +398,10 @@ public class LookupProxyHandler {
// Connected to backend broker
long requestId = proxyConnection.newRequestId();
ByteBuf command;
- Map<String, String> propertiesMap = new HashMap<>();
- for (KeyValue kv : properties) {
- propertiesMap.put(kv.getKey(), kv.getValue());
- }
command = Commands.newGetTopicsOfNamespaceRequest(namespaceName, requestId, mode,
- topicsPattern, topicsHash, propertiesMap);
+ topicsPattern, topicsHash, properties);
- internalPerformGetTopicsOfNamespace(clientRequestId, namespaceName, mode, propertiesMap, clientCnx,
+ internalPerformGetTopicsOfNamespace(clientRequestId, namespaceName, mode, properties, clientCnx,
command, requestId);
proxyConnection.getConnectionPool().releaseConnection(clientCnx);
}).exceptionally(ex -> {
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
index 9c4de0c917c9..e1159976b54e 100644
--- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/LookupProxyHandlerTest.java
@@ -24,6 +24,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf;
@@ -36,24 +37,32 @@ import io.netty.handler.codec.EncoderException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeoutException;
import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.topiclistlimit.TopicListSizeResultCache;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.impl.BinaryProtoLookupService.LookupDataResult;
import org.apache.pulsar.client.impl.ClientCnx;
import org.apache.pulsar.client.impl.ConnectionPool;
import org.apache.pulsar.common.api.proto.BaseCommand;
import org.apache.pulsar.common.api.proto.CommandGetSchema;
+import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace;
import org.apache.pulsar.common.api.proto.CommandLookupTopic;
import org.apache.pulsar.common.api.proto.CommandLookupTopicResponse;
import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadata;
import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadataResponse;
+import org.apache.pulsar.common.api.proto.KeyValue;
import org.apache.pulsar.common.api.proto.ServerError;
+import org.apache.pulsar.common.lookup.GetTopicsResult;
+import org.apache.pulsar.common.protocol.Commands;
+import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiterImpl;
import org.apache.pulsar.policies.data.loadbalancer.LoadManagerReport;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -64,6 +73,7 @@ public class LookupProxyHandlerTest {
private static final long CLIENT_REQUEST_ID = 10L;
private static final long BROKER_REQUEST_ID = 20L;
private static final String TOPIC = "persistent://tenant/ns/topic";
+ private static final String NAMESPACE = "tenant/ns";
private ProxyConfiguration configuration;
private ProxyService proxyService;
@@ -75,6 +85,7 @@ public class LookupProxyHandlerTest {
private EmbeddedChannel channel;
private LookupProxyHandler handler;
private ByteBuf forwardedRequest;
+ private AsyncDualMemoryLimiterImpl topicListLimiter;
@BeforeMethod
public void setup() {
@@ -109,6 +120,10 @@ public class LookupProxyHandlerTest {
@AfterMethod(alwaysRun = true)
public void cleanup() {
+ if (topicListLimiter != null) {
+ topicListLimiter.close();
+ topicListLimiter = null;
+ }
if (forwardedRequest != null) {
forwardedRequest.release();
forwardedRequest = null;
@@ -367,6 +382,69 @@ public class LookupProxyHandlerTest {
verify(connectionPool).releaseConnection(clientCnx);
}
+ @Test
+ public void testGetTopicsOfNamespaceCopiesPropertiesBeforeConnecting() {
+ topicListLimiter = new AsyncDualMemoryLimiterImpl(Long.MAX_VALUE, 100, 10_000,
+ Long.MAX_VALUE, 100, 10_000);
+ when(proxyService.getMaxTopicListInFlightLimiter()).thenReturn(topicListLimiter);
+ when(proxyService.getTopicListSizeResultCache()).thenReturn(new TopicListSizeResultCache());
+ handler = new LookupProxyHandler(proxyService, proxyConnection);
+ CompletableFuture<GetTopicsResult> topicsFuture = new CompletableFuture<>();
+ doAnswer(invocation -> {
+ ByteBuf request = invocation.getArgument(0);
+ try {
+ forwardedRequest = request.copy();
+ return topicsFuture;
+ } finally {
+ request.release();
+ }
+ }).when(clientCnx).newGetTopicsOfNamespace(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+
+ // The decoder parses every frame into the same command and releases the frame after the handler returns.
+ BaseCommand decoderCommand = new BaseCommand();
+ ByteBuf firstFrame = newGetTopicsOfNamespaceFrame(Map.of("key1", "value1", "key2", "value2"));
+ ByteBuf secondFrame = newGetTopicsOfNamespaceFrame(Map.of("other", "other-value"));
+ try {
+ parseFrame(decoderCommand, firstFrame);
+ handler.handleGetTopicsOfNamespace(decoderCommand.getGetTopicsOfNamespace());
+ firstFrame.release();
+ firstFrame = null;
+ parseFrame(decoderCommand, secondFrame);
+
+ connectionFuture.complete(clientCnx);
+
+ verify(clientCnx, timeout(10_000)).newGetTopicsOfNamespace(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
+ BaseCommand command = decodeCommand(forwardedRequest);
+ assertThat(command.getType()).as("Forwarded command type")
+ .isEqualTo(BaseCommand.Type.GET_TOPICS_OF_NAMESPACE);
+ CommandGetTopicsOfNamespace forwarded = command.getGetTopicsOfNamespace();
+ assertThat(forwarded.getRequestId()).as("Broker request ID").isEqualTo(BROKER_REQUEST_ID);
+ assertThat(forwarded.getNamespace()).as("Forwarded namespace").isEqualTo(NAMESPACE);
+ Map<String, String> forwardedProperties = new HashMap<>();
+ for (KeyValue kv : forwarded.getPropertiesList()) {
+ forwardedProperties.put(kv.getKey(), kv.getValue());
+ }
+ assertThat(forwardedProperties).as("Forwarded properties")
+ .containsExactlyInAnyOrderEntriesOf(Map.of("key1", "value1", "key2", "value2"));
+ } finally {
+ if (firstFrame != null) {
+ firstFrame.release();
+ }
+ secondFrame.release();
+ }
+ }
+
+ private static ByteBuf newGetTopicsOfNamespaceFrame(Map<String, String> properties) {
+ return Commands.newGetTopicsOfNamespaceRequest(NAMESPACE, CLIENT_REQUEST_ID,
+ CommandGetTopicsOfNamespace.Mode.PERSISTENT, null, null, properties);
+ }
+
+ private static void parseFrame(BaseCommand command, ByteBuf frame) {
+ int frameSize = frame.readInt();
+ assertThat(frameSize).as("Frame size").isEqualTo(frame.readableBytes());
+ command.parseFrom(frame, frame.readInt());
+ }
+
private void verifyNoBackendLookup() {
verify(clientCnx, never()).newLookup(any(ByteBuf.class), eq(BROKER_REQUEST_ID));
}
(pulsar) 19/23: [fix][broker] Reject namespace-level partitioned topic creation on a remote partition conflict (#22577)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 09487c394cbb916f169819e055c69a99782b4298
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Oct 23 09:46:37 2026 +0800
[fix][broker] Reject namespace-level partitioned topic creation on a remote partition conflict (#22577)
Signed-off-by: Matteo Merli <mm...@apache.org>
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit 290e78276555a3237c3590e3e0dd2b23cae12e46)
---
.../apache/pulsar/broker/admin/AdminResource.java | 92 ++++++++++++++--------
.../broker/service/OneWayReplicatorTest.java | 20 +++++
...OneWayReplicatorUsingGlobalPartitionedTest.java | 6 ++
.../service/OneWayReplicatorUsingGlobalZKTest.java | 5 ++
4 files changed, 92 insertions(+), 31 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java
index 7b90a65ad1db..ea50d798b7d0 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java
@@ -39,6 +39,7 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.mledger.ManagedLedgerException;
@@ -645,20 +646,17 @@ public abstract class AdminResource extends PulsarWebResource {
})
.thenCompose(__ -> provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties))
.thenCompose(__ -> tryCreatePartitionsAsync(numPartitions))
- .thenRun(() -> {
+ .thenCompose(__ -> {
if (!createLocalTopicOnly
&& pulsar().getConfig().isCreateTopicToRemoteClusterForReplication()) {
- internalCreatePartitionedTopicToReplicatedClustersInBackground(numPartitions);
- log.info()
- .attr("topic", topicName)
- .log("Successfully created partitioned for topic for the remote clusters");
- } else {
- log.info()
- .attr("topic", topicName)
- .log("Skip creating partitioned for topic for the remote clusters");
+ return internalCreatePartitionedTopicToReplicatedClusters(numPartitions);
}
- asyncResponse.resume(Response.noContent().build());
+ log.info()
+ .attr("topic", topicName)
+ .log("Skip creating partitioned for topic for the remote clusters");
+ return CompletableFuture.completedFuture(null);
})
+ .thenRun(() -> asyncResponse.resume(Response.noContent().build()))
.exceptionally(ex -> {
if (AdminResource.isConflictException(ex)) {
log.info()
@@ -696,11 +694,38 @@ public abstract class AdminResource extends PulsarWebResource {
return CompletableFuture.completedFuture(-1);
}
- private void internalCreatePartitionedTopicToReplicatedClustersInBackground(int numPartitions) {
- getNamespaceReplicatedClustersAsync(namespaceName)
- .thenAccept(clusters -> {
- // this call happens in the background without async composition. completion is logged.
- internalCreatePartitionedTopicToReplicatedClustersInBackground(clusters, numPartitions);
+ /**
+ * Creates the partitioned topic on the other replication clusters of the namespace. Only an existing remote topic
+ * with a different number of partitions fails the returned future; other errors are logged and ignored, because
+ * the replicator creates the remote topic when it starts. The wait is bounded so that an unreachable remote
+ * cluster does not hold the request until the remote admin client times out.
+ */
+ private CompletableFuture<Void> internalCreatePartitionedTopicToReplicatedClusters(int numPartitions) {
+ return getNamespaceReplicatedClustersAsync(namespaceName)
+ .thenCompose(clusters -> {
+ List<CompletableFuture<Void>> futures = new ArrayList<>();
+ internalCreatePartitionedTopicToReplicatedClustersInBackground(clusters, numPartitions)
+ .values().forEach(future -> futures.add(future.exceptionally(ex -> {
+ Throwable cause = FutureUtil.unwrapCompletionException(ex);
+ if (cause instanceof RestException re
+ && re.getResponse().getStatus() == Status.PRECONDITION_FAILED.getStatusCode()) {
+ throw new RestException(Status.PRECONDITION_FAILED, re.getMessage()
+ + ". The topic has been created on the local cluster only");
+ }
+ return null;
+ })));
+ return FutureUtil.waitForAll(futures)
+ .orTimeout(pulsar().getConfig().getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS)
+ .exceptionally(ex -> {
+ if (FutureUtil.unwrapCompletionException(ex) instanceof TimeoutException) {
+ log.warn()
+ .attr("topic", topicName)
+ .log("Timed out waiting for the remote clusters to create the partitioned"
+ + " topic");
+ return null;
+ }
+ throw FutureUtil.wrapToCompletionException(ex);
+ });
});
}
@@ -742,19 +767,10 @@ public abstract class AdminResource extends PulsarWebResource {
TopicsImpl topics = (TopicsImpl) remotePulsarAdmin.topics();
topics.createPartitionedTopicAsync(shortTopicName, numPartitions, true, null)
.whenComplete((ignore, ex2) -> {
- if (ex2 == null) {
- // Create success.
- log.info()
- .attr("topic", topicName)
- .attr("cluster", cluster)
- .log("Successfully created partitioned topic in cluster");
- createRemoteTopicFuture.complete(null);
- return;
- }
- // Create topic on the remote cluster error.
- Throwable unwrapEx2 = FutureUtil.unwrapCompletionException(ex2);
- // The topic has been created before, check the partitions count is expected.
- if (unwrapEx2 instanceof PulsarAdminException.ConflictException) {
+ Throwable unwrapEx2 = ex2 == null ? null : FutureUtil.unwrapCompletionException(ex2);
+ // Check the partitions count is expected, also after a successful creation: the remote cluster
+ // accepts a local-only creation of an existing partitioned topic with fewer partitions.
+ if (unwrapEx2 == null || unwrapEx2 instanceof PulsarAdminException.ConflictException) {
topics.getPartitionedTopicMetadataAsync(shortTopicName).whenComplete((topicMeta, ex3) -> {
if (ex3 != null) {
// Unexpected error, such as NPE. Catch all error to avoid the
@@ -765,10 +781,24 @@ public abstract class AdminResource extends PulsarWebResource {
.exception(ex3)
.log("Failed to check remote-cluster's topic metadata when creating"
+ " partitioned topic in cluster .");
- createRemoteTopicFuture.completeExceptionally(new RestException(ex3));
+ if (unwrapEx2 == null) {
+ // The creation succeeded, only the extra check failed.
+ createRemoteTopicFuture.complete(null);
+ } else {
+ createRemoteTopicFuture.completeExceptionally(new RestException(ex3));
+ }
+ return;
}
- // Call get partitioned metadata of remote cluster success.
- if (topicMeta.partitions == numPartitions) {
+ // Call get partitioned metadata of remote cluster success. After a successful creation,
+ // 0 partitions is a stale read of a missing topic, not a non-partitioned topic.
+ if (unwrapEx2 == null
+ && (topicMeta.partitions == numPartitions || topicMeta.partitions == 0)) {
+ log.info()
+ .attr("topic", topicName)
+ .attr("cluster", cluster)
+ .log("Successfully created partitioned topic in cluster");
+ createRemoteTopicFuture.complete(null);
+ } else if (topicMeta.partitions == numPartitions) {
log.info()
.attr("topic", topicName)
.attr("cluster", cluster)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
index dadedc0b932a..256c98481aa1 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
@@ -1378,6 +1378,26 @@ public class OneWayReplicatorTest extends OneWayReplicatorTestBase {
admin2.topics().deletePartitionedTopic(topicName);
}
+ @Test
+ public void testNamespaceLevelReplicationRemoteConflictTopicExist() throws Exception {
+ final String topicName = BrokerTestUtil.newUniqueName("persistent://" + replicatedNamespace + "/tp_");
+ admin2.topics().createPartitionedTopic(topicName, 1);
+ try {
+ admin1.topics().createPartitionedTopic(topicName, 2);
+ fail("Expected error due to a conflict partitioned topic already exists.");
+ } catch (PulsarAdminException.PreconditionFailedException ex) {
+ assertTrue(ex.getMessage().contains("with different partitions"));
+ }
+ // The topic is created on the local cluster, and the remote topic is unchanged.
+ assertEquals(admin1.topics().getPartitionedTopicMetadata(topicName).partitions, 2);
+ assertEquals(admin2.topics().getPartitionedTopicMetadata(topicName).partitions, 1);
+ // cleanup.
+ cleanupTopics(() -> {
+ admin1.topics().deletePartitionedTopic(topicName);
+ admin2.topics().deletePartitionedTopic(topicName);
+ });
+ }
+
/**
* See the description and execution flow: https://github.com/apache/pulsar/pull/21948.
* Steps:
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalPartitionedTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalPartitionedTest.java
index 29016df07b24..1237fbad5269 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalPartitionedTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalPartitionedTest.java
@@ -163,6 +163,12 @@ public class OneWayReplicatorUsingGlobalPartitionedTest extends OneWayReplicator
super.testPartitionedTopicLevelReplicationRemoteConflictTopicExist();
}
+ @Override
+ @Test(enabled = false)
+ public void testNamespaceLevelReplicationRemoteConflictTopicExist() throws Exception {
+ super.testNamespaceLevelReplicationRemoteConflictTopicExist();
+ }
+
@Override
@Test(enabled = false)
public void testConcurrencyOfUnloadBundleAndRecreateProducer2() throws Exception {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
index 6ae881126c3d..99494456f25c 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
@@ -407,6 +407,11 @@ public class OneWayReplicatorUsingGlobalZKTest extends OneWayReplicatorTest {
super.testPartitionedTopicLevelReplicationRemoteConflictTopicExist();
}
+ @Test(enabled = false)
+ public void testNamespaceLevelReplicationRemoteConflictTopicExist() throws Exception {
+ super.testNamespaceLevelReplicationRemoteConflictTopicExist();
+ }
+
@Test(enabled = false)
public void testConcurrencyOfUnloadBundleAndRecreateProducer2() throws Exception {
super.testConcurrencyOfUnloadBundleAndRecreateProducer2();
(pulsar) 20/23: [fix][client] Read the OAuth2 private key without requiring a content type (#20824)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 6f26ad38abc72aa867da8c6df0f7e30ee615a6f4
Author: Ozan Gunalp <oz...@gmail.com>
AuthorDate: Fri Oct 23 03:48:17 2026 +0200
[fix][client] Read the OAuth2 private key without requiring a content type (#20824)
Co-authored-by: Matteo Merli <mm...@apache.org>
(cherry picked from commit baf5ac0320ef50ecd3583215c0c3cadd99de309b)
---
.../impl/auth/oauth2/ClientCredentialsFlow.java | 32 ++++----
.../auth/oauth2/ClientCredentialsFlowTest.java | 94 ++++++++++++++++++++++
pulsar-client/src/test/resources/oauth2_key.json | 7 ++
3 files changed, 119 insertions(+), 14 deletions(-)
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlow.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlow.java
index 735b655194a7..00067101b254 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlow.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlow.java
@@ -18,8 +18,8 @@
*/
package org.apache.pulsar.client.impl.auth.oauth2;
+import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
-import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URISyntaxException;
@@ -123,22 +123,12 @@ class ClientCredentialsFlow extends FlowBase {
* @return
* @throws IOException
*/
- private static KeyFile loadPrivateKey(String privateKeyURL) throws IOException {
+ @VisibleForTesting
+ static KeyFile loadPrivateKey(String privateKeyURL) throws IOException {
try {
URLConnection urlConnection = new org.apache.pulsar.client.api.url.URL(privateKeyURL).openConnection();
try {
- String protocol = urlConnection.getURL().getProtocol();
- String contentType = urlConnection.getContentType();
- if ("data".equals(protocol) && !"application/json".equals(contentType)) {
- throw new IllegalArgumentException(
- "Unsupported media type or encoding format: " + urlConnection.getContentType());
- }
- KeyFile privateKey;
- try (Reader r = new InputStreamReader((InputStream) urlConnection.getContent(),
- StandardCharsets.UTF_8)) {
- privateKey = KeyFile.fromJson(r);
- }
- return privateKey;
+ return loadPrivateKey(urlConnection);
} finally {
IOUtils.close(urlConnection);
}
@@ -147,6 +137,20 @@ class ClientCredentialsFlow extends FlowBase {
}
}
+ @VisibleForTesting
+ static KeyFile loadPrivateKey(URLConnection urlConnection) throws IOException {
+ String protocol = urlConnection.getURL().getProtocol();
+ if ("data".equals(protocol) && !"application/json".equals(urlConnection.getContentType())) {
+ throw new IllegalArgumentException(
+ "Unsupported media type or encoding format: " + urlConnection.getContentType());
+ }
+ // Read the stream directly: getContent() needs a content type to pick a handler, which not every
+ // URL handler reports
+ try (Reader r = new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8)) {
+ return KeyFile.fromJson(r);
+ }
+ }
+
@Override
public void initialize() throws PulsarClientException {
super.initialize();
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlowTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlowTest.java
new file mode 100644
index 000000000000..46955dd85883
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/auth/oauth2/ClientCredentialsFlowTest.java
@@ -0,0 +1,94 @@
+/*
+ * 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.client.impl.auth.oauth2;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertThrows;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLConnection;
+import org.testng.annotations.Test;
+
+public class ClientCredentialsFlowTest {
+
+ private static final String KEY_JSON_BASE64 = "ewogICJ0eXBlIjogInR5cGUiLAogICJjbGllbnRfaWQiOiAiY2xpZW50LWlkIiwKICAi"
+ + "Y2xpZW50X3NlY3JldCI6ICJjbGllbnQtc2VjcmV0IiwKICAiY2xpZW50X2VtYWlsIjogImNsaWVudC1lbWFpbCIsCiAgImlzc3Vl"
+ + "cl91cmwiOiAiaHR0cHM6Ly9pc3N1ZXItdXJsLyIKfQ==";
+
+ private static void assertKeyFile(KeyFile keyFile) {
+ assertEquals(keyFile.getType(), "type");
+ assertEquals(keyFile.getClientId(), "client-id");
+ assertEquals(keyFile.getClientSecret(), "client-secret");
+ assertEquals(keyFile.getClientEmail(), "client-email");
+ assertEquals(keyFile.getIssuerUrl(), "https://issuer-url/");
+ }
+
+ private static URL keyResource() {
+ return ClientCredentialsFlowTest.class.getResource("/oauth2_key.json");
+ }
+
+ @Test
+ public void testLoadPrivateKeyFromFileUrl() throws Exception {
+ assertKeyFile(ClientCredentialsFlow.loadPrivateKey(keyResource().toString()));
+ }
+
+ @Test
+ public void testLoadPrivateKeyFromPath() throws Exception {
+ assertKeyFile(ClientCredentialsFlow.loadPrivateKey(new File(keyResource().toURI()).getAbsolutePath()));
+ }
+
+ @Test
+ public void testLoadPrivateKeyFromDataUrl() throws Exception {
+ assertKeyFile(ClientCredentialsFlow.loadPrivateKey("data:application/json;base64," + KEY_JSON_BASE64));
+ }
+
+ @Test
+ public void testLoadPrivateKeyRejectsDataUrlWithoutJsonContentType() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClientCredentialsFlow.loadPrivateKey("data:;base64," + KEY_JSON_BASE64));
+ }
+
+ @Test
+ public void testLoadPrivateKeyFromConnectionWithoutContentType() throws Exception {
+ URL resource = keyResource();
+ // Stands in for a connection from a custom URL handler that does not report a content type,
+ // for which URLConnection.getContent() fails with "no content-type"
+ URLConnection connection = new URLConnection(URI.create("http://localhost/oauth2_key.json").toURL()) {
+ @Override
+ public void connect() {
+ }
+
+ @Override
+ public String getContentType() {
+ return null;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return resource.openStream();
+ }
+ };
+ assertNull(connection.getContentType());
+ assertKeyFile(ClientCredentialsFlow.loadPrivateKey(connection));
+ }
+}
diff --git a/pulsar-client/src/test/resources/oauth2_key.json b/pulsar-client/src/test/resources/oauth2_key.json
new file mode 100644
index 000000000000..bf9e0de1c9fb
--- /dev/null
+++ b/pulsar-client/src/test/resources/oauth2_key.json
@@ -0,0 +1,7 @@
+{
+ "type": "type",
+ "client_id": "client-id",
+ "client_secret": "client-secret",
+ "client_email": "client-email",
+ "issuer_url": "https://issuer-url/"
+}