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/01 19:50:29 UTC
(pulsar) 30/32: [fix][broker] Fix lookup permit leak when namespace policy reads fail (#26606)
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch lh-branch-4.0-backports-2026-10-01
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit fc070ab898efaf5b778749b9aa2c1e7c82cd65d6
Author: void-ptr974 <vo...@protonmail.com>
AuthorDate: Thu Oct 1 10:08:45 2026 +0800
[fix][broker] Fix lookup permit leak when namespace policy reads fail (#26606)
(cherry picked from commit 5be997af1bdda57671d5521d0ec3a6945d2a61f3)
---
.../apache/pulsar/broker/service/ServerCnx.java | 220 +++++++-------
.../pulsar/broker/service/ServerCnxTest.java | 336 +++++++++++++++++++++
2 files changed, 455 insertions(+), 101 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 cdac7a738475..d790cadf3010 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
@@ -93,7 +93,6 @@ import org.apache.pulsar.broker.limiter.ConnectionController;
import org.apache.pulsar.broker.loadbalance.extensions.ExtensibleLoadManagerImpl;
import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
import org.apache.pulsar.broker.namespace.LookupOptions;
-import org.apache.pulsar.broker.namespace.NamespaceService;
import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException;
import org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException;
import org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException;
@@ -714,111 +713,41 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
final Semaphore lookupSemaphore = service.getLookupRequestSemaphore();
if (lookupSemaphore.tryAcquire()) {
- isTopicOperationAllowed(topicName, TopicOperation.LOOKUP, authenticationData, originalAuthData).thenApply(
- isAuthorized -> {
- if (isAuthorized) {
- // Get if exists, respond not found error if not exists.
- getBrokerService().isAllowAutoTopicCreationAsync(topicName).thenAccept(brokerAllowAutoCreate -> {
- boolean autoCreateIfNotExist = partitionMetadata.isMetadataAutoCreationEnabled()
- && brokerAllowAutoCreate;
- if (!autoCreateIfNotExist) {
- NamespaceService namespaceService = getBrokerService().getPulsar().getNamespaceService();
- namespaceService.checkTopicExistsAsync(topicName).thenAccept(topicExistsInfo -> {
- lookupSemaphore.release();
- if (!topicExistsInfo.isExists()) {
- writeAndFlush(Commands.newPartitionMetadataResponse(
- ServerError.TopicNotFound, "", requestId));
- } else if (topicExistsInfo.getTopicType().equals(TopicType.PARTITIONED)) {
- commandSender.sendPartitionMetadataResponse(topicExistsInfo.getPartitions(),
- requestId);
- } else {
- commandSender.sendPartitionMetadataResponse(0, requestId);
- }
- // release resources.
- topicExistsInfo.recycle();
- }).exceptionally(ex -> {
- lookupSemaphore.release();
- Throwable actEx = FutureUtil.unwrapCompletionException(ex);
- if (actEx instanceof WebApplicationException restException
- && restException.getResponse().getStatus() == NOT_FOUND.getStatusCode()) {
- log.warn("{} {} Failed to get partition metadata for nonexistent resource: {}",
- topicName, ServerCnx.this, actEx.getMessage());
- } else {
- log.error("{} {} Failed to get partition metadata", topicName,
- ServerCnx.this, ex);
- }
- writeAndFlush(
- Commands.newPartitionMetadataResponse(ServerError.MetadataError,
- "Failed to get partition metadata",
- requestId));
- return null;
- });
- } else {
- // Get if exists, create a new one if not exists.
- unsafeGetPartitionedTopicMetadataAsync(getBrokerService().pulsar(), topicName)
- .whenComplete((metadata, ex) -> {
- lookupSemaphore.release();
- if (ex == null) {
- int partitions = metadata.partitions;
- commandSender.sendPartitionMetadataResponse(partitions, requestId);
- } else {
- if (ex instanceof PulsarClientException) {
- log.warn("Failed to authorize {} at [{}] on topic {} : {}", getRole(),
- remoteAddress, topicName, ex.getMessage());
- commandSender.sendPartitionMetadataResponse(ServerError.AuthorizationError,
- ex.getMessage(), requestId);
- } else {
- ServerError error = ServerError.ServiceNotReady;
- if (ex instanceof MetadataStoreException) {
- error = ServerError.MetadataError;
- } else if (ex instanceof RestException restException){
- int responseCode = restException.getResponse().getStatus();
- if (responseCode == NOT_FOUND.getStatusCode()){
- error = ServerError.TopicNotFound;
- } else if (responseCode < INTERNAL_SERVER_ERROR.getStatusCode()){
- error = ServerError.MetadataError;
- }
- }
- if (error == ServerError.TopicNotFound) {
- log.info("Trying to get Partitioned Metadata for a resource not exist"
- + "[{}] {}: {}", remoteAddress,
- topicName, ex.getMessage());
- } else {
- log.warn("Failed to get Partitioned Metadata [{}] {}: {}",
- remoteAddress, topicName, ex.getMessage(), ex);
- }
- commandSender.sendPartitionMetadataResponse(error, ex.getMessage(),
- requestId);
- }
- }
- });
- }
- });
- } else {
+ FutureUtil.supplySafely(() -> isTopicOperationAllowed(topicName, TopicOperation.LOOKUP,
+ authenticationData, originalAuthData)).handle((isAuthorized, ex) -> {
+ if (ex != null) {
+ logAuthException(remoteAddress, "partition-metadata", getPrincipal(), Optional.of(topicName), ex);
+ Throwable actEx = FutureUtil.unwrapCompletionException(ex);
+ if (actEx instanceof WebApplicationException restException
+ && restException.getResponse().getStatus() == NOT_FOUND.getStatusCode()) {
+ writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.TopicNotFound,
+ "Tenant or namespace or topic does not exist: " + topicName.getNamespace(), requestId));
+ } else {
+ writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.AuthorizationError,
+ "Exception occurred while trying to authorize get Partition Metadata", requestId));
+ }
+ return false;
+ }
+ if (!isAuthorized) {
final String msg = "Client is not authorized to Get Partition Metadata";
log.warn("[{}] {} with role {} on topic {}", remoteAddress, msg, getPrincipal(), topicName);
- writeAndFlush(
- Commands.newPartitionMetadataResponse(ServerError.AuthorizationError, msg, requestId));
- lookupSemaphore.release();
+ writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.AuthorizationError,
+ msg, requestId));
}
- return null;
- }).exceptionally(ex -> {
- logAuthException(remoteAddress, "partition-metadata", getPrincipal(), Optional.of(topicName), ex);
- Throwable actEx = FutureUtil.unwrapCompletionException(ex);
- if (actEx instanceof WebApplicationException restException) {
- if (restException.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
- writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.TopicNotFound,
- "Tenant or namespace or topic does not exist: " + topicName.getNamespace() ,
- requestId));
- lookupSemaphore.release();
- return null;
- }
+ return isAuthorized;
+ }).thenCompose(isAuthorized -> {
+ if (!isAuthorized) {
+ return CompletableFuture.completedFuture(null);
}
- final String msg = "Exception occurred while trying to authorize get Partition Metadata";
- writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.AuthorizationError, msg,
- requestId));
+ return lookupPartitionMetadata(topicName, requestId, partitionMetadata.isMetadataAutoCreationEnabled());
+ }).whenComplete((ignored, ex) -> {
+ // All branches, including their response handling and cleanup, finish before releasing the permit.
lookupSemaphore.release();
- return null;
+ if (ex != null) {
+ // Stage-specific failures have already been handled. Do not attempt another response here.
+ log.error("{} {} Failed to process partition metadata request {}", topicName, ServerCnx.this,
+ requestId, FutureUtil.unwrapCompletionException(ex));
+ }
});
} else {
if (log.isDebugEnabled()) {
@@ -830,6 +759,95 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
}
}
+ private CompletableFuture<Void> lookupPartitionMetadata(TopicName topicName, long requestId,
+ boolean metadataAutoCreationEnabled) {
+ return FutureUtil.supplySafely(() -> getBrokerService().isAllowAutoTopicCreationAsync(topicName))
+ .<CompletableFuture<Void>>handle((brokerAllowAutoCreate, ex) -> {
+ if (ex != null) {
+ sendPartitionMetadataLookupError(topicName, requestId, ex);
+ return CompletableFuture.completedFuture(null);
+ }
+ if (metadataAutoCreationEnabled && brokerAllowAutoCreate) {
+ return lookupOrCreatePartitionMetadata(topicName, requestId);
+ }
+ return lookupExistingTopicMetadata(topicName, requestId);
+ }).thenCompose(future -> future);
+ }
+
+ private CompletableFuture<Void> lookupExistingTopicMetadata(TopicName topicName, long requestId) {
+ return FutureUtil.supplySafely(() -> getBrokerService().getPulsar().getNamespaceService()
+ .checkTopicExistsAsync(topicName)).handle((topicExistsInfo, ex) -> {
+ if (ex != null) {
+ sendPartitionMetadataLookupError(topicName, requestId, ex);
+ return null;
+ }
+ try {
+ if (!topicExistsInfo.isExists()) {
+ writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.TopicNotFound, "", requestId));
+ } else if (topicExistsInfo.getTopicType().equals(TopicType.PARTITIONED)) {
+ commandSender.sendPartitionMetadataResponse(topicExistsInfo.getPartitions(), requestId);
+ } else {
+ commandSender.sendPartitionMetadataResponse(0, requestId);
+ }
+ } finally {
+ topicExistsInfo.recycle();
+ }
+ return null;
+ });
+ }
+
+ private void sendPartitionMetadataLookupError(TopicName topicName, long requestId, Throwable ex) {
+ Throwable actEx = FutureUtil.unwrapCompletionException(ex);
+ if (actEx instanceof WebApplicationException restException
+ && restException.getResponse().getStatus() == NOT_FOUND.getStatusCode()) {
+ log.warn("{} {} Failed to get partition metadata for nonexistent resource: {}",
+ topicName, ServerCnx.this, actEx.getMessage());
+ } else {
+ log.error("{} {} Failed to get partition metadata", topicName, ServerCnx.this, ex);
+ }
+ writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.MetadataError,
+ "Failed to get partition metadata", requestId));
+ }
+
+ private CompletableFuture<Void> lookupOrCreatePartitionMetadata(TopicName topicName, long requestId) {
+ return FutureUtil.supplySafely(() ->
+ unsafeGetPartitionedTopicMetadataAsync(getBrokerService().pulsar(), topicName))
+ .handle((metadata, ex) -> {
+ if (ex == null) {
+ commandSender.sendPartitionMetadataResponse(metadata.partitions, requestId);
+ return null;
+ }
+ Throwable actEx = FutureUtil.unwrapCompletionException(ex);
+ if (actEx instanceof PulsarClientException) {
+ log.warn("Failed to authorize {} at [{}] on topic {} : {}", getRole(),
+ remoteAddress, topicName, actEx.getMessage());
+ commandSender.sendPartitionMetadataResponse(ServerError.AuthorizationError,
+ actEx.getMessage(), requestId);
+ return null;
+ }
+ ServerError error = ServerError.ServiceNotReady;
+ if (actEx instanceof MetadataStoreException) {
+ error = ServerError.MetadataError;
+ } else if (actEx instanceof RestException restException) {
+ int responseCode = restException.getResponse().getStatus();
+ if (responseCode == NOT_FOUND.getStatusCode()) {
+ error = ServerError.TopicNotFound;
+ } else if (responseCode < INTERNAL_SERVER_ERROR.getStatusCode()) {
+ error = ServerError.MetadataError;
+ }
+ }
+ if (error == ServerError.TopicNotFound) {
+ log.info("Trying to get Partitioned Metadata for a resource not exist"
+ + "[{}] {}: {}", remoteAddress, topicName, actEx.getMessage());
+ } else {
+ log.warn("Failed to get Partitioned Metadata [{}] {}: {}",
+ remoteAddress, topicName, actEx.getMessage(), actEx);
+ }
+ commandSender.sendPartitionMetadataResponse(error, actEx.getMessage(), requestId);
+ return null;
+ });
+ }
+
@Override
protected void handleConsumerStats(CommandConsumerStats commandConsumerStats) {
checkArgument(state == State.Connected);
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 3d9117eb3864..963ad4ed58bd 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
@@ -67,6 +67,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -78,6 +79,7 @@ import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.naming.AuthenticationException;
+import javax.ws.rs.core.Response;
import lombok.AllArgsConstructor;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
@@ -120,7 +122,9 @@ import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.broker.service.schema.SchemaRegistryService;
import org.apache.pulsar.broker.service.utils.ClientChannelHelper;
import org.apache.pulsar.broker.testcontext.PulsarTestContext;
+import org.apache.pulsar.broker.web.RestException;
import org.apache.pulsar.client.api.ProducerAccessMode;
+import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.transaction.TxnID;
import org.apache.pulsar.common.api.AuthData;
@@ -160,9 +164,11 @@ import org.apache.pulsar.common.api.proto.TxnAction;
import org.apache.pulsar.common.naming.NamespaceBundle;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.policies.data.AuthAction;
import org.apache.pulsar.common.policies.data.Policies;
import org.apache.pulsar.common.policies.data.TopicOperation;
+import org.apache.pulsar.common.policies.data.TopicType;
import org.apache.pulsar.common.protocol.ByteBufPair;
import org.apache.pulsar.common.protocol.Commands;
import org.apache.pulsar.common.protocol.Commands.ChecksumType;
@@ -171,7 +177,9 @@ import org.apache.pulsar.common.protocol.schema.EmptyVersion;
import org.apache.pulsar.common.topics.TopicList;
import org.apache.pulsar.common.util.FutureUtil;
import org.apache.pulsar.common.util.collections.ConcurrentLongHashMap;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
import org.apache.pulsar.transaction.coordinator.TxnMeta;
+import org.apache.pulsar.utils.TestLogAppender;
import org.awaitility.Awaitility;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
@@ -3677,6 +3685,334 @@ public class ServerCnxTest {
channel.finish();
}
+ @DataProvider
+ public Object[][] partitionMetadataPolicyFailures() {
+ return new Object[][]{{true, true}, {true, false}, {false, true}, {false, false}};
+ }
+
+ @Test(dataProvider = "partitionMetadataPolicyFailures", timeOut = 30000)
+ public void testPartitionMetadataPolicyFailure(boolean metadataAutoCreationEnabled, boolean alreadyFailed)
+ throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ TopicName topicName = TopicName.get(successTopicName);
+ for (long requestId = 1; requestId <= 3; requestId++) {
+ CompletableFuture<Boolean> policyFuture = new CompletableFuture<>();
+ doReturn(policyFuture).when(brokerService).isAllowAutoTopicCreationAsync(topicName);
+ MetadataStoreException failure = new MetadataStoreException("Namespace policy read failed");
+ if (alreadyFailed) {
+ policyFuture.completeExceptionally(failure);
+ }
+
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, requestId,
+ metadataAutoCreationEnabled));
+ if (!alreadyFailed) {
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+ policyFuture.completeExceptionally(failure);
+ }
+
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).as("Immediate and single error response").hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.getRequestId()).isEqualTo(requestId);
+ assertThat(response.getError()).isEqualTo(ServerError.MetadataError);
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ assertThat(channel.outboundMessages()).isEmpty();
+ }
+ verify(namespaceService, never()).checkTopicExistsAsync(topicName);
+ channel.finishAndReleaseAll();
+ }
+
+ @Test(timeOut = 30000)
+ public void testPartitionMetadataResponseCleanupFailure() throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+
+ TopicName topicName = TopicName.get(successTopicName);
+ doReturn(CompletableFuture.completedFuture(false)).when(brokerService)
+ .isAllowAutoTopicCreationAsync(topicName);
+ TopicExistsInfo topicExistsInfo = mock(TopicExistsInfo.class);
+ when(topicExistsInfo.isExists()).thenReturn(true);
+ when(topicExistsInfo.getTopicType()).thenReturn(TopicType.PARTITIONED);
+ when(topicExistsInfo.getPartitions()).thenReturn(3);
+ IllegalStateException cleanupFailure = new IllegalStateException("Recycle failed");
+ Mockito.doThrow(cleanupFailure).when(topicExistsInfo).recycle();
+ doReturn(CompletableFuture.completedFuture(topicExistsInfo)).when(namespaceService)
+ .checkTopicExistsAsync(topicName);
+
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ try (TestLogAppender appender = TestLogAppender.create(ServerCnx.class)) {
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, 1, false));
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).as("Cleanup must not send a second response").hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.hasError()).isFalse();
+ assertThat(response.getPartitions()).isEqualTo(3);
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ verify(topicExistsInfo).recycle();
+ assertThat(channel.outboundMessages()).isEmpty();
+ assertThat(appender.getEvents())
+ .filteredOn(event -> event.getThrown() == cleanupFailure)
+ .as("Unexpected cleanup failures must remain visible")
+ .hasSize(1);
+ } finally {
+ channel.finishAndReleaseAll();
+ }
+ }
+
+ @DataProvider
+ public Object[][] partitionMetadataAuthorizationResults() {
+ return new Object[][]{
+ {CompletableFuture.completedFuture(false), ServerError.AuthorizationError},
+ {CompletableFuture.failedFuture(new IllegalStateException("Authorization failed")),
+ ServerError.AuthorizationError},
+ {CompletableFuture.failedFuture(new RestException(Response.Status.NOT_FOUND, "Namespace not found")),
+ ServerError.TopicNotFound}
+ };
+ }
+
+ @Test(dataProvider = "partitionMetadataAuthorizationResults", timeOut = 30000)
+ public void testPartitionMetadataAuthorizationResult(CompletableFuture<Boolean> authorizationFuture,
+ ServerError expectedError) throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+ svcConfig.setAuthorizationEnabled(true);
+ AuthorizationService authorizationService = mock(AuthorizationService.class);
+ doReturn(authorizationService).when(brokerService).getAuthorizationService();
+ doReturn(authorizationFuture).when(authorizationService)
+ .allowTopicOperationAsync(any(), any(), any(), any(), any(), any());
+
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, 1, true));
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.getError()).isEqualTo(expectedError);
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ verify(authorizationService).allowTopicOperationAsync(any(), any(), any(), any(), any(), any());
+ verify(namespaceService, never()).checkTopicExistsAsync(any());
+ assertThat(channel.outboundMessages()).isEmpty();
+ channel.finishAndReleaseAll();
+ }
+
+ @DataProvider
+ public Object[][] partitionMetadataExistingTopics() {
+ return new Object[][]{{true, 3}, {true, 0}, {false, 0}};
+ }
+
+ @Test(dataProvider = "partitionMetadataExistingTopics", timeOut = 30000)
+ public void testPartitionMetadataExistingTopicResult(boolean exists, int partitions) throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+
+ TopicName topicName = TopicName.get(successTopicName);
+ // The client disables creation even though the broker allows it.
+ doReturn(CompletableFuture.completedFuture(true)).when(brokerService)
+ .isAllowAutoTopicCreationAsync(topicName);
+ CompletableFuture<TopicExistsInfo> lookupFuture = new CompletableFuture<>();
+ doReturn(lookupFuture).when(namespaceService).checkTopicExistsAsync(topicName);
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ try {
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, 1, false));
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+
+ TopicExistsInfo info = mock(TopicExistsInfo.class);
+ when(info.isExists()).thenReturn(exists);
+ when(info.getTopicType()).thenReturn(partitions > 0 ? TopicType.PARTITIONED : TopicType.NON_PARTITIONED);
+ when(info.getPartitions()).thenReturn(partitions);
+ lookupFuture.complete(info);
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.getRequestId()).isEqualTo(1);
+ assertThat(response.hasError()).isEqualTo(!exists);
+ if (exists) {
+ assertThat(response.getPartitions()).isEqualTo(partitions);
+ } else {
+ assertThat(response.getError()).isEqualTo(ServerError.TopicNotFound);
+ }
+ verify(info).recycle();
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ assertThat(channel.outboundMessages()).isEmpty();
+ } finally {
+ channel.finishAndReleaseAll();
+ }
+ }
+
+ @DataProvider
+ public Object[][] partitionMetadataCreationPolicies() {
+ return new Object[][]{{true}, {false}};
+ }
+
+ @Test(dataProvider = "partitionMetadataCreationPolicies", timeOut = 30000)
+ public void testPartitionMetadataDelayedStages(boolean brokerAllowAutoCreate) throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+ svcConfig.setAuthorizationEnabled(true);
+ AuthorizationService authorizationService = mock(AuthorizationService.class);
+ doReturn(authorizationService).when(brokerService).getAuthorizationService();
+ CompletableFuture<Boolean> authorizationFuture = new CompletableFuture<>();
+ doReturn(authorizationFuture).when(authorizationService)
+ .allowTopicOperationAsync(any(), any(), any(), any(), any(), any());
+
+ TopicName topicName = TopicName.get(successTopicName);
+ Policies policies = new Policies();
+ policies.replication_clusters.add(svcConfig.getClusterName());
+ pulsarTestContext.getPulsarResources().getNamespaceResources()
+ .createPolicies(topicName.getNamespaceObject(), policies);
+ CompletableFuture<Boolean> policyFuture = new CompletableFuture<>();
+ AtomicInteger policyReads = new AtomicInteger();
+ doAnswer(invocation -> {
+ policyReads.incrementAndGet();
+ return policyFuture;
+ }).when(brokerService).isAllowAutoTopicCreationAsync(topicName);
+ CompletableFuture<Void> lookupStarted = new CompletableFuture<>();
+ CompletableFuture<TopicExistsInfo> existingTopicFuture = new CompletableFuture<>();
+ CompletableFuture<PartitionedTopicMetadata> metadataFuture = new CompletableFuture<>();
+ doAnswer(invocation -> {
+ lookupStarted.complete(null);
+ return existingTopicFuture;
+ }).when(namespaceService).checkTopicExistsAsync(topicName);
+ doAnswer(invocation -> {
+ lookupStarted.complete(null);
+ return metadataFuture;
+ }).when(brokerService).fetchPartitionedTopicMetadataCheckAllowAutoCreationAsync(topicName);
+
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ try {
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, 1, true));
+ assertThat(policyReads.get()).as("Policy lookup must wait for authorization").isZero();
+ assertThat(lookupStarted.isDone()).isFalse();
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+
+ authorizationFuture.complete(true);
+ assertThat(policyReads.get()).isEqualTo(1);
+ assertThat(lookupStarted.isDone()).as("Metadata lookup must wait for the policy").isFalse();
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+
+ policyFuture.complete(brokerAllowAutoCreate);
+ lookupStarted.get(10, TimeUnit.SECONDS);
+ assertThat(lookupSemaphore.availablePermits()).as("Lookup still owns the permit")
+ .isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+ if (brokerAllowAutoCreate) {
+ verify(namespaceService, never()).checkTopicExistsAsync(topicName);
+ metadataFuture.complete(new PartitionedTopicMetadata(3));
+ } else {
+ verify(namespaceService).checkTopicExistsAsync(topicName);
+ existingTopicFuture.complete(TopicExistsInfo.newPartitionedTopicExists(3));
+ }
+
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.getRequestId()).isEqualTo(1);
+ assertThat(response.hasError()).isFalse();
+ assertThat(response.getPartitions()).isEqualTo(3);
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ assertThat(channel.outboundMessages()).isEmpty();
+ } finally {
+ channel.finishAndReleaseAll();
+ }
+ }
+
+ @DataProvider
+ public Object[][] partitionMetadataLookupFailures() {
+ Object[][] failures = {
+ {new RestException(Response.Status.NOT_FOUND, "Not found"), ServerError.TopicNotFound},
+ {new RestException(Response.Status.BAD_REQUEST, "Invalid metadata"), ServerError.MetadataError},
+ {new RestException(Response.Status.INTERNAL_SERVER_ERROR, "Unavailable"), ServerError.ServiceNotReady},
+ {new MetadataStoreException("Metadata read failed"), ServerError.MetadataError},
+ {new PulsarClientException.AuthorizationException("Denied"), ServerError.AuthorizationError},
+ {new IllegalStateException("Lookup failed"), ServerError.ServiceNotReady}
+ };
+ List<Object[]> cases = new ArrayList<>();
+ for (Object[] failure : failures) {
+ // The same cause maps differently in the existing-topic and auto-creation paths.
+ cases.add(new Object[]{false, new CompletionException((Throwable) failure[0]), ServerError.MetadataError});
+ cases.add(new Object[]{true, new CompletionException((Throwable) failure[0]), failure[1]});
+ }
+ return cases.toArray(new Object[0][]);
+ }
+
+ @Test(dataProvider = "partitionMetadataLookupFailures", timeOut = 30000)
+ public void testPartitionMetadataLookupFailure(boolean brokerAllowAutoCreate, Throwable failure,
+ ServerError expectedError) throws Exception {
+ resetChannel();
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(getResponse()).isInstanceOf(CommandConnected.class);
+
+ TopicName topicName = TopicName.get(successTopicName);
+ doReturn(CompletableFuture.completedFuture(brokerAllowAutoCreate)).when(brokerService)
+ .isAllowAutoTopicCreationAsync(topicName);
+ CompletableFuture<TopicExistsInfo> existingTopicFuture = new CompletableFuture<>();
+ CompletableFuture<PartitionedTopicMetadata> metadataFuture = new CompletableFuture<>();
+ CompletableFuture<Void> lookupStarted = new CompletableFuture<>();
+ if (brokerAllowAutoCreate) {
+ Policies policies = new Policies();
+ policies.replication_clusters.add(svcConfig.getClusterName());
+ pulsarTestContext.getPulsarResources().getNamespaceResources()
+ .createPolicies(topicName.getNamespaceObject(), policies);
+ doAnswer(invocation -> {
+ lookupStarted.complete(null);
+ return metadataFuture;
+ }).when(brokerService).fetchPartitionedTopicMetadataCheckAllowAutoCreationAsync(topicName);
+ } else {
+ doReturn(existingTopicFuture).when(namespaceService).checkTopicExistsAsync(topicName);
+ }
+
+ var lookupSemaphore = brokerService.getLookupRequestSemaphore();
+ int initialPermits = lookupSemaphore.availablePermits();
+ try {
+ // Broker policy chooses the branch while the client allows creation.
+ channel.writeInbound(Commands.newPartitionMetadataRequest(successTopicName, 1, true));
+ if (brokerAllowAutoCreate) {
+ lookupStarted.get(10, TimeUnit.SECONDS);
+ verify(namespaceService, never()).checkTopicExistsAsync(topicName);
+ } else {
+ verify(namespaceService).checkTopicExistsAsync(topicName);
+ }
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits - 1);
+ assertThat(channel.outboundMessages()).isEmpty();
+ if (brokerAllowAutoCreate) {
+ metadataFuture.completeExceptionally(failure);
+ } else {
+ existingTopicFuture.completeExceptionally(failure);
+ }
+ channel.runPendingTasks();
+ assertThat(channel.outboundMessages()).hasSize(1);
+ CommandPartitionedTopicMetadataResponse response =
+ (CommandPartitionedTopicMetadataResponse) getResponse();
+ assertThat(response.getRequestId()).isEqualTo(1);
+ assertThat(response.getError()).isEqualTo(expectedError);
+ assertThat(lookupSemaphore.availablePermits()).isEqualTo(initialPermits);
+ assertThat(channel.outboundMessages()).isEmpty();
+ } finally {
+ channel.finishAndReleaseAll();
+ }
+ }
+
@Test(timeOut = 30000)
public void sendAddPartitionToTxnResponse() throws Exception {
final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class);