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/07/25 17:14:05 UTC

(pulsar) branch branch-4.2 updated: [fix][broker] Fix incorrect listener URLs returned by ModularLoadManager lookups (#26245)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 5993b6f10fc9 [fix][broker] Fix incorrect listener URLs returned by ModularLoadManager lookups (#26245)
5993b6f10fc9 is described below

commit 5993b6f10fc90315bce7de11341bb5237cd18eed
Author: void-ptr974 <vo...@protonmail.com>
AuthorDate: Sun Jul 26 00:52:47 2026 +0800

    [fix][broker] Fix incorrect listener URLs returned by ModularLoadManager lookups (#26245)
    
    (cherry picked from commit 931f9fb0d8aa1fe15446e5ebb1e867868e87fe2c)
---
 .../pulsar/broker/namespace/NamespaceService.java  |  29 +++-
 .../NamespaceServiceLookupOptionsTest.java         | 163 +++++++++++++++++++++
 2 files changed, 186 insertions(+), 6 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java
index 8a14b16f3733..975efc4e57e3 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java
@@ -449,11 +449,27 @@ public class NamespaceService implements AutoCloseable {
         }
     }
 
-    private final Map<NamespaceBundle, CompletableFuture<Optional<LookupResult>>>
+    // The two maps keep authoritative and non-authoritative lookups separate. The key contains every
+    // remaining option that affects the lookup result or its side effects.
+    private final Map<LookupRequestKey, CompletableFuture<Optional<LookupResult>>>
             findingBundlesAuthoritative = new ConcurrentHashMap<>();
-    private final Map<NamespaceBundle, CompletableFuture<Optional<LookupResult>>>
+    private final Map<LookupRequestKey, CompletableFuture<Optional<LookupResult>>>
             findingBundlesNotAuthoritative = new ConcurrentHashMap<>();
 
+    /**
+     * Key for coalescing lookup requests handled by this lookup path.
+     *
+     * <p>Lookup properties and the requestHttps flag are intentionally excluded because this lookup path
+     * does not consume them.
+     */
+    private record LookupRequestKey(NamespaceBundle bundle, boolean readOnly, boolean loadTopicsInBundle,
+                                    String advertisedListenerName) {
+        private static LookupRequestKey from(NamespaceBundle bundle, LookupOptions options) {
+            return new LookupRequestKey(bundle, options.isReadOnly(), options.isLoadTopicsInBundle(),
+                    options.hasAdvertisedListenerName() ? options.getAdvertisedListenerName() : null);
+        }
+    }
+
     /**
      * Main internal method to lookup and setup ownership of service unit to a broker.
      *
@@ -467,18 +483,19 @@ public class NamespaceService implements AutoCloseable {
             LOG.debug("findBrokerServiceUrl: {} - options: {}", bundle, options);
         }
 
-        Map<NamespaceBundle, CompletableFuture<Optional<LookupResult>>> targetMap;
+        Map<LookupRequestKey, CompletableFuture<Optional<LookupResult>>> targetMap;
         if (options.isAuthoritative()) {
             targetMap = findingBundlesAuthoritative;
         } else {
             targetMap = findingBundlesNotAuthoritative;
         }
+        LookupRequestKey lookupRequestKey = LookupRequestKey.from(bundle, options);
 
-        return targetMap.computeIfAbsent(bundle, (k) -> {
+        return targetMap.computeIfAbsent(lookupRequestKey, (k) -> {
             CompletableFuture<Optional<LookupResult>> future = new CompletableFuture<>();
 
             // First check if we or someone else already owns the bundle
-            ownershipCache.getOwnerAsync(bundle).thenAccept(nsData -> {
+            getOwnershipCache().getOwnerAsync(bundle).thenAccept(nsData -> {
                 if (nsData.isEmpty()) {
                     // No one owns this bundle
 
@@ -522,7 +539,7 @@ public class NamespaceService implements AutoCloseable {
             });
 
             future.whenComplete((r, t) -> pulsar.getExecutor().execute(
-                () -> targetMap.remove(bundle)
+                () -> targetMap.remove(lookupRequestKey, future)
             ));
 
             return future;
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceLookupOptionsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceLookupOptionsTest.java
new file mode 100644
index 000000000000..13fe6a4d2061
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceLookupOptionsTest.java
@@ -0,0 +1,163 @@
+/*
+ * 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.namespace;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import java.net.URI;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.pulsar.broker.loadbalance.extensions.manager.RedirectManager;
+import org.apache.pulsar.broker.lookup.LookupResult;
+import org.apache.pulsar.broker.service.BrokerTestBase;
+import org.apache.pulsar.common.naming.NamespaceBundle;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.policies.data.loadbalancer.AdvertisedListener;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class NamespaceServiceLookupOptionsTest extends BrokerTestBase {
+
+    @BeforeMethod
+    @Override
+    protected void setup() throws Exception {
+        super.baseSetup();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    @Override
+    protected void cleanup() throws Exception {
+        super.internalCleanup();
+    }
+
+    @DataProvider(name = "differentLookupOptions")
+    public Object[][] differentLookupOptions() {
+        return new Object[][] {
+            {
+                LookupOptions.builder().advertisedListenerName("listener-a").build(),
+                LookupOptions.builder().advertisedListenerName("listener-b").build()
+            },
+            {
+                LookupOptions.builder().readOnly(true).build(),
+                LookupOptions.builder().readOnly(false).build()
+            },
+            {
+                LookupOptions.builder().loadTopicsInBundle(true).build(),
+                LookupOptions.builder().loadTopicsInBundle(false).build()
+            }
+        };
+    }
+
+    @Test(dataProvider = "differentLookupOptions")
+    public void testLookupRequestsWithDifferentOptionsAreNotCoalesced(
+            LookupOptions firstOptions, LookupOptions secondOptions) throws Exception {
+        TopicName topic = TopicName.get("persistent://public/default/lookup-options-" + UUID.randomUUID());
+        NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(topic);
+        NamespaceService namespaceService = pulsar.getNamespaceService();
+        OwnershipCache ownershipCache = mock(OwnershipCache.class);
+        CompletableFuture<Optional<NamespaceEphemeralData>> ownerFuture = new CompletableFuture<>();
+        doReturn(CompletableFuture.completedFuture(bundle)).when(namespaceService).getBundleAsync(any());
+        doReturn(ownershipCache).when(namespaceService).getOwnershipCache();
+        when(ownershipCache.getOwnerAsync(bundle)).thenReturn(ownerFuture);
+        stubRedirectManager(namespaceService);
+
+        CompletableFuture<Optional<LookupResult>> firstLookup =
+                namespaceService.getBrokerServiceUrlAsync(topic, firstOptions);
+        CompletableFuture<Optional<LookupResult>> secondLookup =
+                namespaceService.getBrokerServiceUrlAsync(topic, secondOptions);
+
+        verify(ownershipCache, times(2)).getOwnerAsync(bundle);
+        ownerFuture.complete(Optional.of(lookupOwnerWithAdvertisedListeners()));
+
+        assertLookupResultUsesOptions(firstLookup.get(5, TimeUnit.SECONDS).orElseThrow(), firstOptions);
+        assertLookupResultUsesOptions(secondLookup.get(5, TimeUnit.SECONDS).orElseThrow(), secondOptions);
+    }
+
+    @Test
+    public void testEquivalentLookupRequestsAreCoalesced() throws Exception {
+        TopicName topic = TopicName.get("persistent://public/default/lookup-options-" + UUID.randomUUID());
+        NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(topic);
+        NamespaceService namespaceService = pulsar.getNamespaceService();
+        OwnershipCache ownershipCache = mock(OwnershipCache.class);
+        CompletableFuture<Optional<NamespaceEphemeralData>> ownerFuture = new CompletableFuture<>();
+        LookupOptions options = LookupOptions.builder().advertisedListenerName("listener-a").build();
+        doReturn(CompletableFuture.completedFuture(bundle)).when(namespaceService).getBundleAsync(any());
+        doReturn(ownershipCache).when(namespaceService).getOwnershipCache();
+        when(ownershipCache.getOwnerAsync(bundle)).thenReturn(ownerFuture);
+        stubRedirectManager(namespaceService);
+
+        CompletableFuture<Optional<LookupResult>> firstLookup =
+                namespaceService.getBrokerServiceUrlAsync(topic, options);
+        CompletableFuture<Optional<LookupResult>> secondLookup = namespaceService.getBrokerServiceUrlAsync(topic,
+                LookupOptions.builder().advertisedListenerName("listener-a").build());
+
+        verify(ownershipCache).getOwnerAsync(bundle);
+        ownerFuture.complete(Optional.of(lookupOwnerWithAdvertisedListeners()));
+
+        assertLookupResultUsesOptions(firstLookup.get(5, TimeUnit.SECONDS).orElseThrow(), options);
+        assertLookupResultUsesOptions(secondLookup.get(5, TimeUnit.SECONDS).orElseThrow(), options);
+    }
+
+    /**
+     * Replaces the redirect manager with one that answers immediately, so that the lookup reaches the
+     * request coalescing logic on the calling thread. Otherwise the redirect check performs a metadata
+     * store read and the lookups would be handled asynchronously.
+     */
+    private static void stubRedirectManager(NamespaceService namespaceService) throws Exception {
+        RedirectManager redirectManager = mock(RedirectManager.class);
+        when(redirectManager.findRedirectLookupResultAsync())
+                .thenReturn(CompletableFuture.completedFuture(Optional.empty()));
+        FieldUtils.writeDeclaredField(namespaceService, "redirectManager", redirectManager, true);
+    }
+
+    private static NamespaceEphemeralData lookupOwnerWithAdvertisedListeners() {
+        Map<String, AdvertisedListener> advertisedListeners = Map.of(
+                "listener-a", AdvertisedListener.builder()
+                        .brokerServiceUrl(URI.create("pulsar://listener-a:6650"))
+                        .brokerHttpUrl(URI.create("http://listener-a:8080"))
+                        .build(),
+                "listener-b", AdvertisedListener.builder()
+                        .brokerServiceUrl(URI.create("pulsar://listener-b:6650"))
+                        .brokerHttpUrl(URI.create("http://listener-b:8080"))
+                        .build());
+        return new NamespaceEphemeralData("pulsar://broker-1:6650", null,
+                "http://broker-1:8080", null, false, advertisedListeners);
+    }
+
+    private static void assertLookupResultUsesOptions(LookupResult lookupResult, LookupOptions options) {
+        if (options.hasAdvertisedListenerName()) {
+            assertEquals(lookupResult.getLookupData().getBrokerUrl(),
+                    "pulsar://" + options.getAdvertisedListenerName() + ":6650");
+        } else {
+            assertEquals(lookupResult.getLookupData().getBrokerUrl(), "pulsar://broker-1:6650");
+        }
+    }
+}