Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* 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.bookkeeper.mledger.util;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.apache.bookkeeper.mledger.AsyncCallbacks;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.bookkeeper.mledger.ManagedCursor;
import org.apache.bookkeeper.mledger.ManagedLedger;
import org.apache.bookkeeper.mledger.ManagedLedgerException;
import org.apache.bookkeeper.mledger.Position;
import org.apache.pulsar.common.classification.InterfaceStability;

/**
* This util class contains some future-based methods to replace callback-based APIs. With a callback-based API, if any
* exception is thrown in the callback, the callback will never have a chance to be called. While with a future-based
* API, if any exception is thrown in future's callback (e.g. `thenApply`), the future will eventually be completed
* exceptionally. In addition, future-based API is easier for users to switch a different executor to execute the
* callback (e.g. `thenApplyAsync`).
*/
@InterfaceStability.Evolving
public class ManagedLedgerAsyncUtils {

public static CompletableFuture<ManagedCursor> openCursor(ManagedLedger ml, String cursorName) {
final var future = new CompletableFuture<ManagedCursor>();
ml.asyncOpenCursor(cursorName, new AsyncCallbacks.OpenCursorCallback() {
@Override
public void openCursorComplete(ManagedCursor cursor, Object ctx) {
future.complete(cursor);
}

@Override
public void openCursorFailed(ManagedLedgerException exception, Object ctx) {
future.completeExceptionally(exception);
}
}, null);
return future;
}

public static CompletableFuture<List<Entry>> readEntries(ManagedCursor cursor, int numberOfEntriesToRead,
Position maxPosition) {
final var future = new CompletableFuture<List<Entry>>();
cursor.asyncReadEntries(numberOfEntriesToRead, new AsyncCallbacks.ReadEntriesCallback() {
@Override
public void readEntriesComplete(List<Entry> entries, Object ctx) {
future.complete(entries);
}

@Override
public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
future.completeExceptionally(exception);
}
}, null, maxPosition);
return future;
}

public static CompletableFuture<Void> markDelete(ManagedCursor cursor, Position position,
Map<String, Long> properties) {
final var future = new CompletableFuture<Void>();
cursor.asyncMarkDelete(position, properties, new AsyncCallbacks.MarkDeleteCallback() {
@Override
public void markDeleteComplete(Object ctx) {
future.complete(null);
}

@Override
public void markDeleteFailed(ManagedLedgerException exception, Object ctx) {
future.completeExceptionally(exception);
}
}, new Object());
return future;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
import org.apache.pulsar.broker.service.persistent.DispatchRateLimiter;
import org.apache.pulsar.broker.service.persistent.DispatchRateLimiterFactory;
import org.apache.pulsar.broker.service.persistent.DispatchRateLimiterFactoryClassic;
import org.apache.pulsar.broker.service.persistent.MessageDeduplication;
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.broker.service.persistent.SystemTopic;
import org.apache.pulsar.broker.service.plugin.EntryFilterProvider;
Expand Down Expand Up @@ -1657,16 +1658,20 @@ public PulsarAdmin getClusterPulsarAdmin(String cluster, Optional<ClusterData> c
* @return CompletableFuture<Topic>
* @throws RuntimeException
*/
protected CompletableFuture<Optional<Topic>> loadOrCreatePersistentTopic(final String topic,
@VisibleForTesting
public CompletableFuture<Optional<Topic>> loadOrCreatePersistentTopic(final String topic,
boolean createIfMissing, Map<String, String> properties) {
final CompletableFuture<Optional<Topic>> topicFuture = FutureUtil.createFutureWithTimeout(
Duration.ofSeconds(pulsar.getConfiguration().getTopicLoadTimeoutSeconds()), executor(),
() -> FAILED_TO_LOAD_TOPIC_TIMEOUT_EXCEPTION);

topicFuture.exceptionally(t -> {
topicFuture.exceptionallyAsync(e -> {
pulsarStats.recordTopicLoadFailed();
Copy link
Contributor

@poorbarcode poorbarcode Jul 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The primary change of #22860 is to remove the failed Future case by case instead of removing a failed topic creation future here.

@shibd @codelipenghui Could you also review the current PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I explained all details in the PR description.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Key point:

But there are still some cases not considered

#24497 is the best example. #23184 is another example before.

The main concern is that if an orphan pending PersistentTopic could affect the new pending PersistentTopic, mainly due to:

  • Managed ledger, which was handled in this PR
  • Replicators, especially the Pulsar producer

Even if it could make the new PersistentTopic fail to load, it will be the same with the existing case, with better exception message (e.g. replicator create failure) rather than the misleading timeout exception (Failed to load topic within timeout).

return null;
});
if (topics.remove(topic, topicFuture)) {
log.info("Removed topic {} for: {}", topic, e.getMessage());
}
return Optional.empty();
}, executor());

checkTopicNsOwnership(topic)
.thenRun(() -> {
Expand Down Expand Up @@ -1781,7 +1786,6 @@ public void createPersistentTopic0(final String topic, boolean createIfMissing,
if (isTransactionInternalName(topicName)) {
String msg = String.format("Can not create transaction system topic %s", topic);
log.warn(msg);
pulsar.getExecutor().execute(() -> topics.remove(topic, topicFuture));
topicFuture.completeExceptionally(new NotAllowedException(msg));
return;
}
Expand Down Expand Up @@ -1842,6 +1846,12 @@ public void createPersistentTopic0(final String topic, boolean createIfMissing,
@Override
public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
try {
if (topicFuture.isCompletedExceptionally()) {
// Don't close the managed ledger because next time the topic is accessed, the
// managed ledger will be created again. The managed ledger will be removed if the
// ownership has been changed.
return;
}
PersistentTopic persistentTopic = isSystemTopic(topic)
? new SystemTopic(topic, ledger, BrokerService.this)
: newTopic(topic, ledger, BrokerService.this, PersistentTopic.class);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can checkDeduplicationStatus first before checkReplication to avoid creating replicator.

Expand Down Expand Up @@ -1870,20 +1880,15 @@ public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
log.error("{} future is already completed by another thread, "
+ "which is not expected. Closing the current one", topic);
}
executor().submit(() -> {
persistentTopic.close().whenComplete((ignore, ex) -> {
topics.remove(topic, topicFuture);
if (ex != null) {
log.warn("[{}] Get an error when closing topic.",
topic, ex);
}
});
});
} else {
addTopicToStatsMaps(topicName, persistentTopic);
}
})
.exceptionally((ex) -> {
if (MessageDeduplication.RECOVERY_FAILURE.equals(ex.getCause())) {
log.info("Deduplication recovery of {} is cancelled", topic);
return null;
}
log.warn("Replication or dedup check failed."
+ " Removing topic from topics list {}, {}", topic, ex);
executor().submit(() -> {
Expand Down
Loading
Loading