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/04/17 11:22:53 UTC
(pulsar) branch branch-4.1 updated (0be605e7575 -> ff90898b88e)
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a change to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/pulsar.git
from 0be605e7575 [cleanup][ci] Remove documentation label bot (#25469)
new d947b529655 [improve][client] Deduplicate in-progress lookup requests also for HttpLookupService (#25017)
new ff90898b88e [fix][sec] Upgrade to async-http-client 2.14.5 to address CVE-2026-40490 (#25546)
The 2 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:
distribution/server/src/assemble/LICENSE.bin.txt | 6 +-
distribution/shell/src/assemble/LICENSE.bin.txt | 6 +-
pom.xml | 2 +-
.../pulsar/client/api/BrokerServiceLookupTest.java | 7 +-
.../apache/pulsar/client/api/SimpleSchemaTest.java | 6 +-
.../internal/http/AsyncHttpConnectorTest.java | 56 +++++
pulsar-client/pom.xml | 6 +
.../client/impl/BinaryProtoLookupService.java | 205 +++------------
.../org/apache/pulsar/client/impl/HttpClient.java | 89 +++++--
.../pulsar/client/impl/HttpLookupService.java | 14 +-
...rogressDeduplicationDecoratorLookupService.java | 276 +++++++++++++++++++++
.../apache/pulsar/client/impl/LookupService.java | 26 +-
.../pulsar/client/impl/PulsarClientImpl.java | 22 +-
.../client/impl/BinaryProtoLookupServiceTest.java | 21 +-
.../apache/pulsar/client/impl/HttpClientTest.java | 150 +++++++++++
.../pulsar/client/impl/HttpLookupServiceTest.java | 142 +++++++++++
.../proxy/server/ProxyLookupThrottlingTest.java | 3 +-
.../server/ProxyWithExtensibleLoadManagerTest.java | 13 +-
.../pulsar/websocket/LookupProtocolTest.java | 29 +--
19 files changed, 823 insertions(+), 256 deletions(-)
create mode 100644 pulsar-client/src/main/java/org/apache/pulsar/client/impl/InProgressDeduplicationDecoratorLookupService.java
create mode 100644 pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpClientTest.java
create mode 100644 pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpLookupServiceTest.java
(pulsar) 02/02: [fix][sec] Upgrade to async-http-client 2.14.5 to address CVE-2026-40490 (#25546)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit ff90898b88eea16fe1b48207398a05efded355c8
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Apr 17 13:39:15 2026 +0300
[fix][sec] Upgrade to async-http-client 2.14.5 to address CVE-2026-40490 (#25546)
(cherry picked from commit a1613bc2e5fd26cc16fc95b4a3c61bc5e1ae090d)
---
distribution/server/src/assemble/LICENSE.bin.txt | 6 +-
distribution/shell/src/assemble/LICENSE.bin.txt | 6 +-
pom.xml | 2 +-
.../internal/http/AsyncHttpConnectorTest.java | 56 ++++++++
pulsar-client/pom.xml | 6 +
.../org/apache/pulsar/client/impl/HttpClient.java | 89 +++++++++---
.../apache/pulsar/client/impl/HttpClientTest.java | 150 +++++++++++++++++++++
.../pulsar/client/impl/HttpLookupServiceTest.java | 142 +++++++++++++++++++
8 files changed, 435 insertions(+), 22 deletions(-)
diff --git a/distribution/server/src/assemble/LICENSE.bin.txt b/distribution/server/src/assemble/LICENSE.bin.txt
index 8cd3b8c3b6c..d73b2bf7092 100644
--- a/distribution/server/src/assemble/LICENSE.bin.txt
+++ b/distribution/server/src/assemble/LICENSE.bin.txt
@@ -392,8 +392,8 @@ The Apache Software License, Version 2.0
* AirCompressor
- io.airlift-aircompressor-2.0.3.jar
* AsyncHttpClient
- - org.asynchttpclient-async-http-client-2.12.4.jar
- - org.asynchttpclient-async-http-client-netty-utils-2.12.4.jar
+ - org.asynchttpclient-async-http-client-2.14.5.jar
+ - org.asynchttpclient-async-http-client-netty-utils-2.14.5.jar
* Jetty
- org.eclipse.jetty-jetty-client-9.4.58.v20250814.jar
- org.eclipse.jetty-jetty-continuation-9.4.58.v20250814.jar
@@ -611,7 +611,7 @@ Eclipse Public License - v2.0 -- ../licenses/LICENSE-EPL-2.0.txt
* Jakarta Injection -- org.glassfish.hk2.external-jakarta.inject-2.6.1.jar
Public Domain (CC0) -- ../licenses/LICENSE-CC0.txt
- * Reactive Streams -- org.reactivestreams-reactive-streams-1.0.3.jar
+ * Reactive Streams -- org.reactivestreams-reactive-streams-1.0.4.jar
Creative Commons Attribution License
* Jcip -- ../licenses/LICENSE-jcip.txt
diff --git a/distribution/shell/src/assemble/LICENSE.bin.txt b/distribution/shell/src/assemble/LICENSE.bin.txt
index c4bfdf8a3de..e306bdced43 100644
--- a/distribution/shell/src/assemble/LICENSE.bin.txt
+++ b/distribution/shell/src/assemble/LICENSE.bin.txt
@@ -398,8 +398,8 @@ The Apache Software License, Version 2.0
* AirCompressor
- aircompressor-2.0.3.jar
* AsyncHttpClient
- - async-http-client-2.12.4.jar
- - async-http-client-netty-utils-2.12.4.jar
+ - async-http-client-2.14.5.jar
+ - async-http-client-netty-utils-2.14.5.jar
* Jetty
- jetty-client-9.4.58.v20250814.jar
- jetty-http-9.4.58.v20250814.jar
@@ -459,7 +459,7 @@ Eclipse Public License - v2.0 -- ../licenses/LICENSE-EPL-2.0.txt
* Jakarta Injection -- jakarta.inject-2.6.1.jar
Public Domain (CC0) -- ../licenses/LICENSE-CC0.txt
- * Reactive Streams -- reactive-streams-1.0.3.jar
+ * Reactive Streams -- reactive-streams-1.0.4.jar
Creative Commons Attribution License
* Jcip -- ../licenses/LICENSE-jcip.txt
diff --git a/pom.xml b/pom.xml
index 3a14a780d38..8940335744a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -261,7 +261,7 @@ flexible messaging model and an intuitive client API.</description>
<prometheus-jmx.version>0.16.1</prometheus-jmx.version>
<confluent.version>7.9.2</confluent.version>
<aircompressor.version>2.0.3</aircompressor.version>
- <asynchttpclient.version>2.12.4</asynchttpclient.version>
+ <asynchttpclient.version>2.14.5</asynchttpclient.version>
<commons-lang3.version>3.19.0</commons-lang3.version>
<commons-io.version>2.21.0</commons-io.version>
<commons-codec.version>1.20.0</commons-codec.version>
diff --git a/pulsar-client-admin/src/test/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnectorTest.java b/pulsar-client-admin/src/test/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnectorTest.java
index e0b4b13a03d..38243976f56 100644
--- a/pulsar-client-admin/src/test/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnectorTest.java
+++ b/pulsar-client-admin/src/test/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnectorTest.java
@@ -19,7 +19,9 @@
package org.apache.pulsar.client.admin.internal.http;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.testng.Assert.assertEquals;
@@ -282,6 +284,60 @@ public class AsyncHttpConnectorTest {
assertEquals(response.getResponseBody(), "OK");
}
+ /**
+ * Locks in that AsyncHttpConnector forwards the {@code Authorization} header across a cross-origin
+ * HTTP redirect (different host:port — serverA → serverB). The admin connector disables AHC's
+ * built-in follow-redirect and runs its own redirect loop that copies the original request headers,
+ * so it must remain unaffected by the async-http-client >= 2.14.5 {@code Authorization} stripping
+ * on cross-origin redirects (CVE-2026-40490 fix). Regressing {@code setFollowRedirect(true)} would
+ * break this test.
+ */
+ @Test
+ void testAuthorizationHeaderOnCrossOriginRedirect() throws ExecutionException, InterruptedException {
+ WireMockServer serverB = new WireMockServer(WireMockConfiguration.wireMockConfig().port(0));
+ serverB.start();
+ try {
+ server.stubFor(get(urlEqualTo("/admin/v2/clusters"))
+ .willReturn(aResponse()
+ .withStatus(307)
+ .withHeader("Location",
+ "http://127.0.0.1:" + serverB.port() + "/admin/v2/clusters")));
+
+ serverB.stubFor(get(urlEqualTo("/admin/v2/clusters"))
+ .atPriority(2)
+ .willReturn(aResponse().withStatus(401).withBody("missing auth")));
+ serverB.stubFor(get(urlEqualTo("/admin/v2/clusters"))
+ .atPriority(1)
+ .withHeader("Authorization", equalTo("Bearer test-token"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody("[\"test-cluster\"]")));
+
+ ClientConfigurationData conf = new ClientConfigurationData();
+ conf.setServiceUrl("http://127.0.0.1:" + server.port());
+
+ @Cleanup
+ AsyncHttpConnector connector = new AsyncHttpConnector(5000, 5000,
+ 5000, 0, conf, false, null);
+
+ Request request = new RequestBuilder("GET")
+ .setUrl("http://127.0.0.1:" + server.port() + "/admin/v2/clusters")
+ .addHeader("Authorization", "Bearer test-token")
+ .build();
+
+ Response response = connector.executeRequest(request).get();
+
+ assertEquals(response.getStatusCode(), 200,
+ "cross-origin redirect should forward Authorization and return the stubbed body");
+ assertEquals(response.getResponseBody(), "[\"test-cluster\"]");
+ serverB.verify(getRequestedFor(urlEqualTo("/admin/v2/clusters"))
+ .withHeader("Authorization", equalTo("Bearer test-token")));
+ } finally {
+ serverB.stop();
+ }
+ }
+
@Test
void testRedirectWithBody() throws ExecutionException, InterruptedException {
server.stubFor(post(urlEqualTo("/path1"))
diff --git a/pulsar-client/pom.xml b/pulsar-client/pom.xml
index aaab87c6e63..6c60e79d0e0 100644
--- a/pulsar-client/pom.xml
+++ b/pulsar-client/pom.xml
@@ -228,6 +228,12 @@
<artifactId>fastutil</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
+ <version>${wiremock.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpClient.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpClient.java
index 72fcf82b859..6c53c067702 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpClient.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpClient.java
@@ -55,6 +55,7 @@ import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.asynchttpclient.Request;
+import org.asynchttpclient.Response;
import org.asynchttpclient.SslEngineFactory;
import org.asynchttpclient.channel.DefaultKeepAliveStrategy;
@@ -87,7 +88,12 @@ public class HttpClient implements Closeable {
DefaultAsyncHttpClientConfig.Builder confBuilder = new DefaultAsyncHttpClientConfig.Builder();
confBuilder.setCookieStore(null);
confBuilder.setUseProxyProperties(true);
- confBuilder.setFollowRedirect(true);
+ // Follow redirects manually in executeGet(...) so we can re-invoke authentication per hop and
+ // carry the Authorization header across cross-origin redirects. async-http-client >= 2.14.5
+ // (CVE-2026-40490 fix) strips the Authorization header when it follows redirects itself; Pulsar
+ // HTTP lookups routinely redirect to another broker's httpUrl/httpUrlTls which is a different
+ // host/port, i.e. cross-origin.
+ confBuilder.setFollowRedirect(false);
confBuilder.setMaxRedirects(conf.getMaxLookupRedirects());
confBuilder.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_IN_SECONDS * 1000);
confBuilder.setReadTimeout(DEFAULT_READ_TIMEOUT_IN_SECONDS * 1000);
@@ -167,10 +173,28 @@ public class HttpClient implements Closeable {
try {
URI hostUri = serviceNameResolver.resolveHostUri();
String requestUrl = new URL(hostUri.toURL(), path).toString();
- String remoteHostName = hostUri.getHost();
+ InetSocketAddress originalHost = InetSocketAddress.createUnresolved(hostUri.getHost(), hostUri.getPort());
+ executeGet(requestUrl, originalHost, clientConf.getMaxLookupRedirects(), future, clazz);
+ } catch (Exception e) {
+ log.warn("[{}] Failed to initiate HTTP get request: {}", path, e.getMessage());
+ if (e instanceof PulsarClientException) {
+ future.completeExceptionally(e);
+ } else {
+ future.completeExceptionally(new PulsarClientException(e));
+ }
+ }
+
+ return future;
+ }
+
+ private <T> void executeGet(String requestUrl, InetSocketAddress originalHost,
+ int redirectsRemaining, CompletableFuture<T> future, Class<T> clazz) {
+ try {
+ URI currentUri = URI.create(requestUrl);
+ String remoteHostName = currentUri.getHost();
AuthenticationDataProvider authData = authentication.getAuthData(remoteHostName);
- CompletableFuture<Map<String, String>> authFuture = new CompletableFuture<>();
+ CompletableFuture<Map<String, String>> authFuture = new CompletableFuture<>();
// bring a authenticationStage for sasl auth.
if (authData.hasDataForHttp()) {
@@ -179,18 +203,15 @@ public class HttpClient implements Closeable {
authFuture.complete(null);
}
- // auth complete, do real request
authFuture.whenComplete((respHeaders, ex) -> {
if (ex != null) {
- serviceNameResolver.markHostAvailability(
- InetSocketAddress.createUnresolved(hostUri.getHost(), hostUri.getPort()), false);
+ serviceNameResolver.markHostAvailability(originalHost, false);
log.warn("[{}] Failed to perform http request at authentication stage: {}",
requestUrl, ex.getMessage());
future.completeExceptionally(new PulsarClientException(ex));
return;
}
- // auth complete, use a new builder
BoundRequestBuilder builder = httpClient.prepareGet(requestUrl)
// share the DNS resolver and cache with Pulsar client
.setNameResolver(nameResolver)
@@ -217,20 +238,25 @@ public class HttpClient implements Closeable {
builder.execute().toCompletableFuture().whenComplete((response2, t) -> {
if (t != null) {
- serviceNameResolver.markHostAvailability(
- InetSocketAddress.createUnresolved(hostUri.getHost(), hostUri.getPort()), false);
+ serviceNameResolver.markHostAvailability(originalHost, false);
log.warn("[{}] Failed to perform http request: {}", requestUrl, t.getMessage());
future.completeExceptionally(new PulsarClientException(t));
return;
}
- serviceNameResolver.markHostAvailability(
- InetSocketAddress.createUnresolved(hostUri.getHost(), hostUri.getPort()), true);
+ serviceNameResolver.markHostAvailability(originalHost, true);
+
+ int statusCode = response2.getStatusCode();
+ if (isRedirectStatusCode(statusCode)) {
+ handleRedirect(requestUrl, currentUri, response2, originalHost,
+ redirectsRemaining, future, clazz);
+ return;
+ }
// request not success
- if (response2.getStatusCode() != HttpURLConnection.HTTP_OK) {
+ if (statusCode != HttpURLConnection.HTTP_OK) {
log.warn("[{}] HTTP get request failed: {}", requestUrl, response2.getStatusText());
Exception e;
- if (response2.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
+ if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
e = new NotFoundException("Not found: " + response2.getStatusText());
} else {
e = new PulsarClientException("HTTP get request failed: " + response2.getStatusText());
@@ -250,15 +276,48 @@ public class HttpClient implements Closeable {
});
});
} catch (Exception e) {
- log.warn("[{}]PulsarClientImpl: {}", path, e.getMessage());
+ log.warn("[{}] HTTP request setup failed: {}", requestUrl, e.getMessage());
if (e instanceof PulsarClientException) {
future.completeExceptionally(e);
} else {
future.completeExceptionally(new PulsarClientException(e));
}
}
+ }
- return future;
+ private <T> void handleRedirect(String requestUrl, URI currentUri,
+ Response response,
+ InetSocketAddress originalHost, int redirectsRemaining,
+ CompletableFuture<T> future, Class<T> clazz) {
+ String location = response.getHeader("Location");
+ if (location == null || location.isEmpty()) {
+ future.completeExceptionally(new PulsarClientException(
+ "HTTP redirect " + response.getStatusCode() + " without Location header: " + requestUrl));
+ return;
+ }
+ if (redirectsRemaining <= 0) {
+ future.completeExceptionally(new PulsarClientException(
+ "Maximum redirects exceeded (" + clientConf.getMaxLookupRedirects()
+ + ") while following HTTP redirect for " + requestUrl));
+ return;
+ }
+ String newUrl;
+ try {
+ newUrl = currentUri.resolve(location).toString();
+ } catch (Exception e) {
+ future.completeExceptionally(new PulsarClientException(
+ "Invalid redirect Location \"" + location + "\" for " + requestUrl));
+ return;
+ }
+ executeGet(newUrl, originalHost, redirectsRemaining - 1, future, clazz);
+ }
+
+ private static boolean isRedirectStatusCode(int statusCode) {
+ return statusCode == HttpURLConnection.HTTP_MOVED_PERM // 301
+ || statusCode == HttpURLConnection.HTTP_MOVED_TEMP // 302
+ || statusCode == HttpURLConnection.HTTP_SEE_OTHER // 303
+ || statusCode == 307 // Temporary Redirect
+ || statusCode == 308; // Permanent Redirect
}
protected PulsarSslConfiguration buildSslConfiguration(ClientConfigurationData config, String host)
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpClientTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpClientTest.java
new file mode 100644
index 00000000000..ec3c8b0b78e
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpClientTest.java
@@ -0,0 +1,150 @@
+/*
+ * 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 com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import com.github.tomakehurst.wiremock.WireMockServer;
+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.resolver.NameResolver;
+import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.net.InetAddress;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.client.api.AuthenticationFactory;
+import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
+import org.apache.pulsar.common.lookup.data.LookupData;
+import org.apache.pulsar.common.util.netty.DnsResolverUtil;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Verifies that {@link HttpClient} carries the {@code Authorization} header across cross-origin HTTP redirects.
+ *
+ * <p>Pulsar's HTTP lookup endpoint returns {@code 307 Temporary Redirect} to whichever broker owns the bundle for a
+ * topic. The redirect target is that broker's {@code httpUrl}/{@code httpUrlTls}, i.e. typically a different host or
+ * port from the original request. Auth plugins ({@code AuthenticationToken}, {@code AuthenticationBasic},
+ * {@code AuthenticationOAuth2}, {@code AuthenticationAthenz}) inject the {@code Authorization} header — that header
+ * must reach the redirect target for lookup to succeed.
+ *
+ * <p>async-http-client 2.14.5 strips {@code Authorization} on cross-origin redirects when its built-in follow-redirect
+ * is enabled (CVE-2026-40490 fix). This test drives two WireMock servers on different ports to exercise that path.
+ */
+public class HttpClientTest {
+
+ private static final String LOOKUP_PATH = "/lookup/v2/topic/persistent/public/default/test-topic";
+ private static final String EXPECTED_BODY = "{\"brokerUrl\":\"pulsar://broker-b:6650\","
+ + "\"brokerUrlTls\":\"pulsar+ssl://broker-b:6651\","
+ + "\"httpUrl\":\"http://broker-b:8080\","
+ + "\"httpUrlTls\":\"https://broker-b:8443\","
+ + "\"nativeUrl\":\"pulsar://broker-b:6650\"}";
+
+ private WireMockServer serverA;
+ private WireMockServer serverB;
+ private EventLoopGroup eventLoopGroup;
+ private Timer timer;
+ private NameResolver<InetAddress> nameResolver;
+
+ @BeforeClass(alwaysRun = true)
+ void beforeClass() {
+ eventLoopGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("HttpClientTest"));
+ timer = new HashedWheelTimer(new DefaultThreadFactory("HttpClientTest-timer"));
+ // Default JDK-backed resolver is sufficient; we only hit 127.0.0.1.
+ nameResolver = DnsResolverUtil.adaptToNameResolver(null);
+ }
+
+ @AfterClass(alwaysRun = true)
+ void afterClass() {
+ if (eventLoopGroup != null) {
+ eventLoopGroup.shutdownGracefully();
+ }
+ if (timer != null) {
+ timer.stop();
+ }
+ }
+
+ @BeforeMethod(alwaysRun = true)
+ void beforeMethod() {
+ serverA = new WireMockServer(WireMockConfiguration.wireMockConfig().port(0));
+ serverB = new WireMockServer(WireMockConfiguration.wireMockConfig().port(0));
+ serverA.start();
+ serverB.start();
+ }
+
+ @AfterMethod(alwaysRun = true)
+ void afterMethod() {
+ if (serverA != null) {
+ serverA.stop();
+ }
+ if (serverB != null) {
+ serverB.stop();
+ }
+ }
+
+ @Test
+ public void testCrossOriginRedirectCarriesAuthorizationHeader() throws Exception {
+ // serverA (origin host:port) returns 307 Temporary Redirect to serverB (different port -> cross-origin).
+ serverA.stubFor(get(urlPathMatching(LOOKUP_PATH))
+ .willReturn(aResponse()
+ .withStatus(307)
+ .withHeader("Location",
+ "http://127.0.0.1:" + serverB.port() + LOOKUP_PATH)));
+
+ // serverB only responds 200 when the Authorization header is present with the expected token.
+ // Priorities: lower = higher priority; the specific-Authorization stub must be checked first.
+ serverB.stubFor(get(urlPathMatching(LOOKUP_PATH))
+ .atPriority(2)
+ .willReturn(aResponse().withStatus(401).withBody("missing auth")));
+ serverB.stubFor(get(urlPathMatching(LOOKUP_PATH))
+ .atPriority(1)
+ .withHeader("Authorization", equalTo("Bearer test-token"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody(EXPECTED_BODY)));
+
+ ClientConfigurationData conf = new ClientConfigurationData();
+ conf.setServiceUrl("http://127.0.0.1:" + serverA.port());
+ conf.setAuthentication(AuthenticationFactory.token("test-token"));
+
+ try (HttpClient httpClient = new HttpClient(conf, eventLoopGroup, timer, nameResolver)) {
+ LookupData result = httpClient.get(LOOKUP_PATH, LookupData.class)
+ .get(30, TimeUnit.SECONDS);
+
+ assertNotNull(result, "Expected lookup payload after cross-origin redirect");
+ assertEquals(result.getBrokerUrl(), "pulsar://broker-b:6650");
+ assertEquals(result.getHttpUrl(), "http://broker-b:8080");
+
+ // Lock the invariant: the final hop on serverB must carry the Authorization header.
+ serverB.verify(getRequestedFor(urlPathMatching(LOOKUP_PATH))
+ .withHeader("Authorization", equalTo("Bearer test-token")));
+ }
+ }
+}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpLookupServiceTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpLookupServiceTest.java
new file mode 100644
index 00000000000..f2d3751ecb0
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/HttpLookupServiceTest.java
@@ -0,0 +1,142 @@
+/*
+ * 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 com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import com.github.tomakehurst.wiremock.WireMockServer;
+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.client.api.AuthenticationFactory;
+import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
+import org.apache.pulsar.client.impl.metrics.InstrumentProvider;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.util.netty.DnsResolverUtil;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * End-to-end check that {@link HttpLookupService#getBroker} carries the {@code Authorization} header
+ * across a cross-origin redirect — the production scenario where a broker returns
+ * {@code 307 Temporary Redirect} with a {@code Location} pointing at another broker's
+ * {@code httpUrl}/{@code httpUrlTls}.
+ */
+public class HttpLookupServiceTest {
+
+ private static final String TOPIC = "persistent://public/default/cross-origin-lookup-topic";
+ private static final String LOOKUP_PATH_REGEX =
+ "/lookup/v2/topic/persistent/public/default/cross-origin-lookup-topic";
+ private static final String LOOKUP_BODY = "{\"brokerUrl\":\"pulsar://broker-b.example:6650\","
+ + "\"brokerUrlTls\":\"pulsar+ssl://broker-b.example:6651\","
+ + "\"httpUrl\":\"http://broker-b.example:8080\","
+ + "\"httpUrlTls\":\"https://broker-b.example:8443\","
+ + "\"nativeUrl\":\"pulsar://broker-b.example:6650\"}";
+
+ private WireMockServer serverA;
+ private WireMockServer serverB;
+ private EventLoopGroup eventLoopGroup;
+ private Timer timer;
+
+ @BeforeClass(alwaysRun = true)
+ void beforeClass() {
+ eventLoopGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("HttpLookupServiceTest"));
+ timer = new HashedWheelTimer(new DefaultThreadFactory("HttpLookupServiceTest-timer"));
+ }
+
+ @AfterClass(alwaysRun = true)
+ void afterClass() {
+ if (eventLoopGroup != null) {
+ eventLoopGroup.shutdownGracefully();
+ }
+ if (timer != null) {
+ timer.stop();
+ }
+ }
+
+ @BeforeMethod(alwaysRun = true)
+ void beforeMethod() {
+ serverA = new WireMockServer(WireMockConfiguration.wireMockConfig().port(0));
+ serverB = new WireMockServer(WireMockConfiguration.wireMockConfig().port(0));
+ serverA.start();
+ serverB.start();
+ }
+
+ @AfterMethod(alwaysRun = true)
+ void afterMethod() {
+ if (serverA != null) {
+ serverA.stop();
+ }
+ if (serverB != null) {
+ serverB.stop();
+ }
+ }
+
+ @Test
+ public void testGetBrokerFollowsCrossOriginRedirect() throws Exception {
+ serverA.stubFor(get(urlPathMatching(LOOKUP_PATH_REGEX))
+ .willReturn(aResponse()
+ .withStatus(307)
+ .withHeader("Location",
+ "http://127.0.0.1:" + serverB.port() + LOOKUP_PATH_REGEX)));
+
+ serverB.stubFor(get(urlPathMatching(LOOKUP_PATH_REGEX))
+ .atPriority(2)
+ .willReturn(aResponse().withStatus(401).withBody("missing auth")));
+ serverB.stubFor(get(urlPathMatching(LOOKUP_PATH_REGEX))
+ .atPriority(1)
+ .withHeader("Authorization", equalTo("Bearer test-token"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody(LOOKUP_BODY)));
+
+ ClientConfigurationData conf = new ClientConfigurationData();
+ conf.setServiceUrl("http://127.0.0.1:" + serverA.port());
+ conf.setAuthentication(AuthenticationFactory.token("test-token"));
+
+ HttpLookupService lookupService = new HttpLookupService(
+ InstrumentProvider.NOOP, conf, eventLoopGroup, timer, DnsResolverUtil.adaptToNameResolver(null));
+ try {
+ LookupTopicResult result = lookupService.getBroker(TopicName.get(TOPIC))
+ .get(30, TimeUnit.SECONDS);
+
+ assertNotNull(result);
+ assertEquals(result.getLogicalAddress().getHostString(), "broker-b.example");
+ assertEquals(result.getLogicalAddress().getPort(), 6650);
+
+ serverB.verify(getRequestedFor(urlPathMatching(LOOKUP_PATH_REGEX))
+ .withHeader("Authorization", equalTo("Bearer test-token")));
+ } finally {
+ lookupService.close();
+ }
+ }
+}
(pulsar) 01/02: [improve][client] Deduplicate in-progress lookup requests also for HttpLookupService (#25017)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit d947b529655483bb65f148c036b5e719151f87b8
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Tue Dec 2 17:33:44 2025 +0200
[improve][client] Deduplicate in-progress lookup requests also for HttpLookupService (#25017)
(cherry picked from commit b37b5b3fa01494fd6541f4d460f3586443c221b6)
---
.../pulsar/client/api/BrokerServiceLookupTest.java | 7 +-
.../apache/pulsar/client/api/SimpleSchemaTest.java | 6 +-
.../client/impl/BinaryProtoLookupService.java | 205 +++------------
.../pulsar/client/impl/HttpLookupService.java | 14 +-
...rogressDeduplicationDecoratorLookupService.java | 276 +++++++++++++++++++++
.../apache/pulsar/client/impl/LookupService.java | 26 +-
.../pulsar/client/impl/PulsarClientImpl.java | 22 +-
.../client/impl/BinaryProtoLookupServiceTest.java | 21 +-
.../proxy/server/ProxyLookupThrottlingTest.java | 3 +-
.../server/ProxyWithExtensibleLoadManagerTest.java | 13 +-
.../pulsar/websocket/LookupProtocolTest.java | 29 +--
11 files changed, 388 insertions(+), 234 deletions(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java
index ddbe6547213..e00e6d69ce8 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java
@@ -82,7 +82,6 @@ import org.apache.pulsar.broker.namespace.OwnershipCache;
import org.apache.pulsar.broker.namespace.ServiceUnitUtils;
import org.apache.pulsar.broker.service.BrokerService;
import org.apache.pulsar.broker.testcontext.PulsarTestContext;
-import org.apache.pulsar.client.impl.BinaryProtoLookupService;
import org.apache.pulsar.client.impl.ClientCnx;
import org.apache.pulsar.client.impl.LookupService;
import org.apache.pulsar.client.impl.PulsarClientImpl;
@@ -957,7 +956,7 @@ public class BrokerServiceLookupTest extends ProducerConsumerBase implements ITe
// Assert the lookup service is a "BinaryProtoLookupService".
final PulsarClientImpl pulsarClientImpl = (PulsarClientImpl) pulsarClient;
final LookupService lookupService = pulsarClientImpl.getLookup();
- assertTrue(lookupService instanceof BinaryProtoLookupService);
+ assertTrue(lookupService.isBinaryProtoLookupService());
final String tpName = BrokerTestUtil.newUniqueName("persistent://public/default/tp");
final int topicPartitions = 10;
@@ -981,7 +980,7 @@ public class BrokerServiceLookupTest extends ProducerConsumerBase implements ITe
// Assert the lookup service is a "BinaryProtoLookupService".
final PulsarClientImpl pulsarClientImpl = (PulsarClientImpl) pulsarClient;
final LookupService lookupService = pulsarClientImpl.getLookup();
- assertTrue(lookupService instanceof BinaryProtoLookupService);
+ assertTrue(lookupService.isBinaryProtoLookupService());
final String tpName = BrokerTestUtil.newUniqueName("persistent://public/default/tp");
admin.topics().createNonPartitionedTopic(tpName);
@@ -1234,7 +1233,7 @@ public class BrokerServiceLookupTest extends ProducerConsumerBase implements ITe
Consumer<String> consumer = pulsarClientImpl.newConsumer(Schema.STRING).topic(tpName)
.subscriptionName("s1").isAckReceiptEnabled(true).subscribe();
LookupService lookupService = pulsarClientImpl.getLookup();
- assertTrue(lookupService instanceof BinaryProtoLookupService);
+ assertTrue(lookupService.isBinaryProtoLookupService());
ClientCnx lookupConnection = pulsarClientImpl.getCnxPool().getConnection(lookupService.resolveHost()).join();
var metricReader = pulsarTestContext.getOpenTelemetryMetricReader();
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleSchemaTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleSchemaTest.java
index 3a7f65f0b07..d581e0a6b32 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleSchemaTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleSchemaTest.java
@@ -49,10 +49,8 @@ import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.api.PulsarClientException.IncompatibleSchemaException;
import org.apache.pulsar.client.api.PulsarClientException.InvalidMessageException;
import org.apache.pulsar.client.api.schema.GenericRecord;
-import org.apache.pulsar.client.impl.BinaryProtoLookupService;
import org.apache.pulsar.client.impl.ClientBuilderImpl;
import org.apache.pulsar.client.impl.ClientCnx;
-import org.apache.pulsar.client.impl.HttpLookupService;
import org.apache.pulsar.client.impl.LookupService;
import org.apache.pulsar.client.impl.MessageImpl;
import org.apache.pulsar.client.impl.PulsarClientImpl;
@@ -1262,8 +1260,8 @@ public class SimpleSchemaTest extends ProducerConsumerBase {
LookupService httpLookupService = httpProtocolClient.getLookup();
LookupService binaryLookupService = binaryProtocolClient.getLookup();
- Assert.assertTrue(httpLookupService instanceof HttpLookupService);
- Assert.assertTrue(binaryLookupService instanceof BinaryProtoLookupService);
+ Assert.assertTrue(!httpLookupService.isBinaryProtoLookupService());
+ Assert.assertTrue(binaryLookupService.isBinaryProtoLookupService());
Assert.assertEquals(admin.schemas().getAllSchemas(topic).size(), 2);
Assert.assertTrue(httpLookupService.getSchema(TopicName.get(topic),
ByteBuffer.allocate(8).putLong(0).array()).get().isPresent());
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/BinaryProtoLookupService.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/BinaryProtoLookupService.java
index 368d9c3809a..674fb40793f 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/BinaryProtoLookupService.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/BinaryProtoLookupService.java
@@ -26,17 +26,13 @@ import io.opentelemetry.api.common.Attributes;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;
-import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
-import org.apache.commons.lang3.mutable.MutableObject;
-import org.apache.commons.lang3.tuple.Pair;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SchemaSerializationException;
import org.apache.pulsar.client.impl.metrics.LatencyHistogram;
@@ -66,16 +62,6 @@ public class BinaryProtoLookupService implements LookupService {
private final int maxLookupRedirects;
private final ExecutorService lookupPinnedExecutor;
private final boolean createdLookupPinnedExecutor;
-
- private final ConcurrentHashMap<Pair<TopicName, Map<String, String>>, CompletableFuture<LookupTopicResult>>
- lookupInProgress = new ConcurrentHashMap<>();
-
- private final ConcurrentHashMap<PartitionedTopicMetadataKey, CompletableFuture<PartitionedTopicMetadata>>
- partitionedMetadataInProgress = new ConcurrentHashMap<>();
-
- private final ConcurrentHashMap<TopicsUnderNamespaceKey, CompletableFuture<GetTopicsResult>>
- topicsUnderNamespaceInProgress = new ConcurrentHashMap<>();
-
private final LatencyHistogram histoGetBroker;
private final LatencyHistogram histoGetTopicMetadata;
private final LatencyHistogram histoGetSchema;
@@ -156,32 +142,20 @@ public class BinaryProtoLookupService implements LookupService {
* topic-name
* @return broker-socket-address that serves given topic
*/
- public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName) {
- long startTime = System.nanoTime();
- final MutableObject<CompletableFuture> newFutureCreated = new MutableObject<>();
- final Pair<TopicName, Map<String, String>> key = Pair.of(topicName,
- client.getConfiguration().getLookupProperties());
- try {
- return lookupInProgress.computeIfAbsent(key, tpName -> {
- CompletableFuture<LookupTopicResult> newFuture = findBroker(serviceNameResolver.resolveHost(), false,
- topicName, 0, key.getRight());
- newFutureCreated.setValue(newFuture);
-
- newFuture.thenRun(() -> {
- histoGetBroker.recordSuccess(System.nanoTime() - startTime);
- }).exceptionally(x -> {
- histoGetBroker.recordFailure(System.nanoTime() - startTime);
- return null;
- });
- return newFuture;
- });
- } finally {
- if (newFutureCreated.getValue() != null) {
- newFutureCreated.getValue().whenComplete((v, ex) -> {
- lookupInProgress.remove(key, newFutureCreated.getValue());
- });
- }
+ public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName, Map<String, String> lookupProperties) {
+ if (lookupProperties == null) {
+ lookupProperties = client.getConfiguration().getLookupProperties();
}
+ long startTime = System.nanoTime();
+ CompletableFuture<LookupTopicResult> newFuture = findBroker(serviceNameResolver.resolveHost(), false,
+ topicName, 0, lookupProperties);
+ newFuture.thenRun(() -> {
+ histoGetBroker.recordSuccess(System.nanoTime() - startTime);
+ }).exceptionally(x -> {
+ histoGetBroker.recordFailure(System.nanoTime() - startTime);
+ return null;
+ });
+ return newFuture;
}
/**
@@ -191,24 +165,7 @@ public class BinaryProtoLookupService implements LookupService {
@Override
public CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadata(
TopicName topicName, boolean metadataAutoCreationEnabled, boolean useFallbackForNonPIP344Brokers) {
- final MutableObject<CompletableFuture> newFutureCreated = new MutableObject<>();
- final PartitionedTopicMetadataKey key = new PartitionedTopicMetadataKey(
- topicName, metadataAutoCreationEnabled, useFallbackForNonPIP344Brokers);
- try {
- return partitionedMetadataInProgress.computeIfAbsent(key, k -> {
- CompletableFuture<PartitionedTopicMetadata> newFuture = getPartitionedTopicMetadataAsync(
- topicName, metadataAutoCreationEnabled,
- useFallbackForNonPIP344Brokers);
- newFutureCreated.setValue(newFuture);
- return newFuture;
- });
- } finally {
- if (newFutureCreated.getValue() != null) {
- newFutureCreated.getValue().whenComplete((v, ex) -> {
- partitionedMetadataInProgress.remove(key, newFutureCreated.getValue());
- });
- }
- }
+ return getPartitionedTopicMetadataAsync(topicName, metadataAutoCreationEnabled, useFallbackForNonPIP344Brokers);
}
private CompletableFuture<LookupTopicResult> findBroker(InetSocketAddress socketAddress,
@@ -351,12 +308,6 @@ public class BinaryProtoLookupService implements LookupService {
return partitionFuture;
}
- @Override
- public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) {
- return getSchema(topicName, null);
- }
-
-
@Override
public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName, byte[] version) {
long startTime = System.nanoTime();
@@ -403,31 +354,21 @@ public class BinaryProtoLookupService implements LookupService {
Mode mode,
String topicsPattern,
String topicsHash) {
- final MutableObject<CompletableFuture<GetTopicsResult>> newFutureCreated = new MutableObject<>();
- final TopicsUnderNamespaceKey key = new TopicsUnderNamespaceKey(namespace, mode, topicsPattern, topicsHash);
-
- try {
- return topicsUnderNamespaceInProgress.computeIfAbsent(key, k -> {
- CompletableFuture<GetTopicsResult> topicsFuture = new CompletableFuture<>();
- AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs());
- Backoff backoff = new BackoffBuilder()
- .setInitialTime(100, TimeUnit.MILLISECONDS)
- .setMandatoryStop(opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS)
- .setMax(1, TimeUnit.MINUTES)
- .create();
-
- newFutureCreated.setValue(topicsFuture);
- getTopicsUnderNamespace(namespace, backoff, opTimeoutMs, topicsFuture, mode,
- topicsPattern, topicsHash);
- return topicsFuture;
- });
- } finally {
- if (newFutureCreated.getValue() != null) {
- newFutureCreated.getValue().whenComplete((v, ex) -> {
- topicsUnderNamespaceInProgress.remove(key, newFutureCreated.getValue());
- });
- }
- }
+ CompletableFuture<GetTopicsResult> topicsFuture = new CompletableFuture<>();
+ AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs());
+ Backoff backoff = new BackoffBuilder()
+ .setInitialTime(100, TimeUnit.MILLISECONDS)
+ .setMandatoryStop(opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS)
+ .setMax(1, TimeUnit.MINUTES)
+ .create();
+ getTopicsUnderNamespace(namespace, backoff, opTimeoutMs, topicsFuture, mode,
+ topicsPattern, topicsHash);
+ return topicsFuture;
+ }
+
+ @Override
+ public boolean isBinaryProtoLookupService() {
+ return true;
}
private void getTopicsUnderNamespace(
@@ -517,93 +458,5 @@ public class BinaryProtoLookupService implements LookupService {
}
- private static final class TopicsUnderNamespaceKey {
- private final NamespaceName namespace;
- private final Mode mode;
- private final String topicsPattern;
- private final String topicsHash;
-
- TopicsUnderNamespaceKey(NamespaceName namespace, Mode mode,
- String topicsPattern, String topicsHash) {
- this.namespace = namespace;
- this.mode = mode;
- this.topicsPattern = topicsPattern;
- this.topicsHash = topicsHash;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- TopicsUnderNamespaceKey that = (TopicsUnderNamespaceKey) o;
- return Objects.equals(namespace, that.namespace)
- && mode == that.mode
- && Objects.equals(topicsPattern, that.topicsPattern)
- && Objects.equals(topicsHash, that.topicsHash);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(namespace, mode, topicsPattern, topicsHash);
- }
-
- @Override
- public String toString() {
- return "TopicsUnderNamespaceKey{"
- + "namespace=" + namespace
- + ", mode=" + mode
- + ", topicsPattern='" + topicsPattern + '\''
- + ", topicsHash='" + topicsHash + '\''
- + '}';
- }
- }
-
- private static final class PartitionedTopicMetadataKey {
- private final TopicName topicName;
- private final boolean metadataAutoCreationEnabled;
- private final boolean useFallbackForNonPIP344Brokers;
-
- PartitionedTopicMetadataKey(TopicName topicName,
- boolean metadataAutoCreationEnabled,
- boolean useFallbackForNonPIP344Brokers) {
- this.topicName = topicName;
- this.metadataAutoCreationEnabled = metadataAutoCreationEnabled;
- this.useFallbackForNonPIP344Brokers = useFallbackForNonPIP344Brokers;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- PartitionedTopicMetadataKey that = (PartitionedTopicMetadataKey) o;
- return metadataAutoCreationEnabled == that.metadataAutoCreationEnabled
- && useFallbackForNonPIP344Brokers == that.useFallbackForNonPIP344Brokers
- && Objects.equals(topicName, that.topicName);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(topicName, metadataAutoCreationEnabled, useFallbackForNonPIP344Brokers);
- }
-
- @Override
- public String toString() {
- return "PartitionedTopicMetadataKey{"
- + "topicName=" + topicName
- + ", metadataAutoCreationEnabled=" + metadataAutoCreationEnabled
- + ", useFallbackForNonPIP344Brokers=" + useFallbackForNonPIP344Brokers
- + '}';
- }
- }
-
-
private static final Logger log = LoggerFactory.getLogger(BinaryProtoLookupService.class);
}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpLookupService.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpLookupService.java
index 08c9956b5be..9044088f724 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpLookupService.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/HttpLookupService.java
@@ -28,6 +28,7 @@ import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
@@ -105,7 +106,14 @@ public class HttpLookupService implements LookupService {
*/
@Override
@SuppressWarnings("deprecation")
- public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName) {
+ public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName, Map<String, String> lookupProperties) {
+ if (lookupProperties == null) {
+ lookupProperties = httpClient.clientConf.getLookupProperties();
+ }
+ if (lookupProperties != null && !lookupProperties.isEmpty()) {
+ log.warn("Lookup properties aren't supported for http lookup service. lookupProperties: {}",
+ lookupProperties);
+ }
String basePath = topicName.isV2() ? BasePathV2 : BasePathV1;
String path = basePath + topicName.getLookupName();
path = StringUtils.isBlank(listenerName) ? path : path + "?listenerName=" + Codec.encode(listenerName);
@@ -211,8 +219,8 @@ public class HttpLookupService implements LookupService {
}
@Override
- public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) {
- return getSchema(topicName, null);
+ public boolean isBinaryProtoLookupService() {
+ return false;
}
@Override
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/InProgressDeduplicationDecoratorLookupService.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/InProgressDeduplicationDecoratorLookupService.java
new file mode 100644
index 00000000000..8cf95b62634
--- /dev/null
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/InProgressDeduplicationDecoratorLookupService.java
@@ -0,0 +1,276 @@
+/*
+ * 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 java.net.InetSocketAddress;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.mutable.MutableObject;
+import org.apache.pulsar.client.api.PulsarClientException;
+import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace.Mode;
+import org.apache.pulsar.common.lookup.GetTopicsResult;
+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.schema.SchemaInfo;
+
+/**
+ * Decorator for {@link LookupService} that deduplicates in-progress lookups for topics, schemas, partitioned topics
+ * and topic listings for namespace.
+ */
+public class InProgressDeduplicationDecoratorLookupService implements LookupService {
+ private final LookupService delegate;
+ private final Supplier<Map<String, String>> lookupPropertiesSupplier;
+ private final InProgressHolder<LookupBrokerKey, CompletableFuture<LookupTopicResult>> topicLookupsInProgress =
+ new InProgressHolder<>();
+ private final InProgressHolder<PartitionedTopicMetadataKey, CompletableFuture<PartitionedTopicMetadata>>
+ partitionedTopicMetadataInProgress = new InProgressHolder<>();
+ private final InProgressHolder<LookupSchemaKey, CompletableFuture<Optional<SchemaInfo>>> schemasInProgress =
+ new InProgressHolder<>();
+ private final InProgressHolder<TopicsUnderNamespaceKey, CompletableFuture<GetTopicsResult>>
+ topicsUnderNamespaceInProgress = new InProgressHolder<>();
+
+ public InProgressDeduplicationDecoratorLookupService(LookupService delegate,
+ Supplier<Map<String, String>> lookupPropertiesSupplier) {
+ this.delegate = delegate;
+ this.lookupPropertiesSupplier = lookupPropertiesSupplier;
+ }
+
+ @Override
+ public void updateServiceUrl(String serviceUrl) throws PulsarClientException {
+ delegate.updateServiceUrl(serviceUrl);
+ }
+
+ @Override
+ public String getServiceUrl() {
+ return delegate.getServiceUrl();
+ }
+
+ @Override
+ public InetSocketAddress resolveHost() {
+ return delegate.resolveHost();
+ }
+
+ @Override
+ public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName, Map<String, String> lookupProperties) {
+ Map<String, String> lookupPropertiesToUse =
+ lookupProperties != null ? lookupProperties : lookupPropertiesSupplier.get();
+ return topicLookupsInProgress.getOrComputeIfAbsent(
+ new LookupBrokerKey(topicName.toString(), lookupPropertiesToUse),
+ () -> delegate.getBroker(topicName, lookupPropertiesToUse));
+ }
+
+ @Override
+ public CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadata(
+ TopicName topicName,
+ boolean metadataAutoCreationEnabled,
+ boolean useFallbackForNonPIP344Brokers) {
+ return partitionedTopicMetadataInProgress.getOrComputeIfAbsent(
+ new PartitionedTopicMetadataKey(topicName, metadataAutoCreationEnabled, useFallbackForNonPIP344Brokers),
+ () -> delegate.getPartitionedTopicMetadata(topicName, metadataAutoCreationEnabled,
+ useFallbackForNonPIP344Brokers));
+ }
+
+ @Override
+ public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName, byte[] version) {
+ // all partitions of a partitioned topic share the same schema
+ // therefore, perform the lookup with the partitioned topic name
+ String topicForSchemaLookup = topicName.getPartitionedTopicName();
+ return schemasInProgress.getOrComputeIfAbsent(new LookupSchemaKey(topicForSchemaLookup, version),
+ () -> delegate.getSchema(TopicName.get(topicForSchemaLookup), version));
+ }
+
+ @Override
+ public CompletableFuture<GetTopicsResult> getTopicsUnderNamespace(NamespaceName namespace, Mode mode,
+ String topicPattern, String topicsHash) {
+ return topicsUnderNamespaceInProgress.getOrComputeIfAbsent(
+ new TopicsUnderNamespaceKey(namespace, mode, topicPattern, topicsHash),
+ () -> delegate.getTopicsUnderNamespace(namespace, mode, topicPattern, topicsHash));
+ }
+
+ @Override
+ public void close() throws Exception {
+ delegate.close();
+ }
+
+ @Override
+ public boolean isBinaryProtoLookupService() {
+ return delegate.isBinaryProtoLookupService();
+ }
+
+ private static class InProgressHolder<K, V extends CompletableFuture<?>> {
+ private final ConcurrentHashMap<K, V> inProgress = new ConcurrentHashMap<>();
+
+ public V getOrComputeIfAbsent(K key, Supplier<V> supplier) {
+ final MutableObject<V> newFutureCreated = new MutableObject<>();
+ try {
+ return inProgress.computeIfAbsent(key, k -> {
+ V newFuture = supplier.get();
+ newFutureCreated.setValue(newFuture);
+ return newFuture;
+ });
+ } finally {
+ V newFutureCreatedValue = newFutureCreated.getValue();
+ if (newFutureCreatedValue != null) {
+ newFutureCreatedValue.whenComplete((v, ex) -> {
+ inProgress.remove(key, newFutureCreatedValue);
+ });
+ }
+ }
+ }
+ }
+
+ private static final class LookupBrokerKey {
+ private final String topic;
+ private final Map<String, String> properties;
+
+ private LookupBrokerKey(String topic, Map<String, String> properties) {
+ this.topic = topic;
+ this.properties = properties.isEmpty() ? Collections.emptyMap() : new HashMap<>(properties);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ LookupBrokerKey lookupBrokerKey = (LookupBrokerKey) o;
+ return Objects.equals(topic, lookupBrokerKey.topic) && properties.equals(lookupBrokerKey.properties);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hashCode(topic);
+ result = 31 * result + properties.hashCode();
+ return result;
+ }
+ }
+
+ private static final class LookupSchemaKey {
+ private final String topic;
+ private final byte[] version;
+
+ private LookupSchemaKey(String topic, byte[] version) {
+ this.topic = topic;
+ this.version = version != null ? version.clone() : null;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ LookupSchemaKey that = (LookupSchemaKey) o;
+ return Objects.equals(topic, that.topic) && Arrays.equals(version, that.version);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hashCode(topic);
+ result = 31 * result + Arrays.hashCode(version);
+ return result;
+ }
+ }
+
+ private static final class TopicsUnderNamespaceKey {
+ private final NamespaceName namespace;
+ private final Mode mode;
+ private final String topicsPattern;
+ private final String topicsHash;
+
+ TopicsUnderNamespaceKey(NamespaceName namespace, Mode mode, String topicsPattern, String topicsHash) {
+ this.namespace = namespace;
+ this.mode = mode;
+ this.topicsPattern = topicsPattern;
+ this.topicsHash = topicsHash;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ TopicsUnderNamespaceKey that = (TopicsUnderNamespaceKey) o;
+ return Objects.equals(namespace, that.namespace) && mode == that.mode && Objects.equals(topicsPattern,
+ that.topicsPattern) && Objects.equals(topicsHash, that.topicsHash);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(namespace, mode, topicsPattern, topicsHash);
+ }
+
+ @Override
+ public String toString() {
+ return "TopicsUnderNamespaceKey{" + "namespace=" + namespace + ", mode=" + mode + ", topicsPattern='"
+ + topicsPattern + '\'' + ", topicsHash='" + topicsHash + '\'' + '}';
+ }
+ }
+
+ private static final class PartitionedTopicMetadataKey {
+ private final TopicName topicName;
+ private final boolean metadataAutoCreationEnabled;
+ private final boolean useFallbackForNonPIP344Brokers;
+
+ PartitionedTopicMetadataKey(TopicName topicName, boolean metadataAutoCreationEnabled,
+ boolean useFallbackForNonPIP344Brokers) {
+ this.topicName = topicName;
+ this.metadataAutoCreationEnabled = metadataAutoCreationEnabled;
+ this.useFallbackForNonPIP344Brokers = useFallbackForNonPIP344Brokers;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ PartitionedTopicMetadataKey that = (PartitionedTopicMetadataKey) o;
+ return metadataAutoCreationEnabled == that.metadataAutoCreationEnabled
+ && useFallbackForNonPIP344Brokers == that.useFallbackForNonPIP344Brokers && Objects.equals(
+ topicName, that.topicName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(topicName, metadataAutoCreationEnabled, useFallbackForNonPIP344Brokers);
+ }
+
+ @Override
+ public String toString() {
+ return "PartitionedTopicMetadataKey{" + "topicName=" + topicName + ", metadataAutoCreationEnabled="
+ + metadataAutoCreationEnabled + ", useFallbackForNonPIP344Brokers=" + useFallbackForNonPIP344Brokers
+ + '}';
+ }
+ }
+}
\ No newline at end of file
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/LookupService.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/LookupService.java
index 3367ae99cb1..67cfe449ec9 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/LookupService.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/LookupService.java
@@ -19,6 +19,7 @@
package org.apache.pulsar.client.impl;
import java.net.InetSocketAddress;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.apache.pulsar.client.api.PulsarClientException;
@@ -56,7 +57,21 @@ public interface LookupService extends AutoCloseable {
* @return a {@link LookupTopicResult} representing the logical and physical address of the broker that serves the
* given topic, as well as proxying information.
*/
- CompletableFuture<LookupTopicResult> getBroker(TopicName topicName);
+ default CompletableFuture<LookupTopicResult> getBroker(TopicName topicName) {
+ return getBroker(topicName, null);
+ }
+
+ /**
+ * Calls broker lookup-api to get broker {@link InetSocketAddress} which serves namespace bundle that contains given
+ * topic. This lookup is made with the given lookup properties. When null is passed, the
+ * default lookup properties specified in the client configuration are used.
+ *
+ * @param topicName
+ * topic-name
+ * @return a {@link LookupTopicResult} representing the logical and physical address of the broker that serves the
+ * given topic, as well as proxying information.
+ */
+ CompletableFuture<LookupTopicResult> getBroker(TopicName topicName, Map<String, String> lookupProperties);
/**
* Returns {@link PartitionedTopicMetadata} for a given topic.
@@ -104,7 +119,9 @@ public interface LookupService extends AutoCloseable {
* @param topicName topic-name
* @return SchemaInfo
*/
- CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName);
+ default CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) {
+ return getSchema(topicName, null);
+ }
/**
* Returns specific version SchemaInfo {@link SchemaInfo} for a given topic.
@@ -144,4 +161,9 @@ public interface LookupService extends AutoCloseable {
*/
CompletableFuture<GetTopicsResult> getTopicsUnderNamespace(NamespaceName namespace, Mode mode,
String topicPattern, String topicsHash);
+
+ /**
+ * Returns true if the lookup service is a binary protocol lookup service.
+ */
+ boolean isBinaryProtoLookupService();
}
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 d8b27e7264b..27c0010c7df 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
@@ -271,14 +271,7 @@ public class PulsarClientImpl implements PulsarClient {
} else {
this.timer = timer;
}
- if (conf.getServiceUrl().startsWith("http")) {
- lookup = new HttpLookupService(instrumentProvider, conf, this.eventLoopGroup, this.timer,
- getNameResolver());
- } else {
- lookup = new BinaryProtoLookupService(this, conf.getServiceUrl(), conf.getListenerName(),
- conf.isUseTls(), this.scheduledExecutorProvider.getExecutor(),
- this.lookupExecutorProvider.getExecutor());
- }
+ lookup = createLookup(conf.getServiceUrl());
if (conf.getServiceUrlProvider() != null) {
conf.getServiceUrlProvider().initialize(this);
@@ -1154,7 +1147,7 @@ public class PulsarClientImpl implements PulsarClient {
}
public CompletableFuture<ClientCnx> getConnectionToServiceUrl() {
- if (!(lookup instanceof BinaryProtoLookupService)) {
+ if (!lookup.isBinaryProtoLookupService()) {
return FutureUtil.failedFuture(new PulsarClientException.InvalidServiceURL(
"Can't get client connection to HTTP service URL", null));
}
@@ -1164,7 +1157,7 @@ public class PulsarClientImpl implements PulsarClient {
public CompletableFuture<ClientCnx> getProxyConnection(final InetSocketAddress logicalAddress,
final int randomKeyForSelectConnection) {
- if (!(lookup instanceof BinaryProtoLookupService)) {
+ if (!lookup.isBinaryProtoLookupService()) {
return FutureUtil.failedFuture(new PulsarClientException.InvalidServiceURL(
"Cannot proxy connection through HTTP service URL", null));
}
@@ -1233,12 +1226,15 @@ public class PulsarClientImpl implements PulsarClient {
}
public LookupService createLookup(String url) throws PulsarClientException {
+ LookupService lookupService;
if (url.startsWith("http")) {
- return new HttpLookupService(instrumentProvider, conf, eventLoopGroup, timer, getNameResolver());
+ lookupService = new HttpLookupService(instrumentProvider, conf, eventLoopGroup, timer, getNameResolver());
} else {
- return new BinaryProtoLookupService(this, url, conf.getListenerName(), conf.isUseTls(),
- externalExecutorProvider.getExecutor());
+ lookupService = new BinaryProtoLookupService(this, url, conf.getListenerName(), conf.isUseTls(),
+ this.scheduledExecutorProvider.getExecutor(), this.lookupExecutorProvider.getExecutor());
}
+ return new InProgressDeduplicationDecoratorLookupService(lookupService,
+ () -> getConfiguration().getLookupProperties());
}
/**
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BinaryProtoLookupServiceTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BinaryProtoLookupServiceTest.java
index 8bc78264ec7..7b9d7b37e5e 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BinaryProtoLookupServiceTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BinaryProtoLookupServiceTest.java
@@ -37,6 +37,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
+import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -204,6 +205,10 @@ public class BinaryProtoLookupServiceTest {
return lookupResult;
}
+ private LookupService decoratedLookupService(LookupService lookupService) {
+ return new InProgressDeduplicationDecoratorLookupService(lookupService, () -> Collections.emptyMap());
+ }
+
/**
* Verifies that getTopicsUnderNamespace() deduplicates concurrent requests and cleans up after completion.
*
@@ -236,8 +241,8 @@ public class BinaryProtoLookupServiceTest {
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("lookup-test-sched"));
- try (BinaryProtoLookupService lookup = new BinaryProtoLookupService(
- client, "pulsar://broker:6650", null, false, scheduler, /*lookupPinnedExecutor*/ null)) {
+ try (LookupService lookup = decoratedLookupService(new BinaryProtoLookupService(
+ client, "pulsar://broker:6650", null, false, scheduler, /*lookupPinnedExecutor*/ null))) {
NamespaceName ns = NamespaceName.get("public", "default");
Mode mode = Mode.PERSISTENT;
@@ -295,8 +300,8 @@ public class BinaryProtoLookupServiceTest {
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("lookup-test-sched"));
- try (BinaryProtoLookupService lookup = new BinaryProtoLookupService(
- client, "pulsar://broker:6650", null, false, scheduler, null)) {
+ try (LookupService lookup = decoratedLookupService(new BinaryProtoLookupService(
+ client, "pulsar://broker:6650", null, false, scheduler, null))) {
NamespaceName ns = NamespaceName.get("public", "default");
Mode mode = Mode.PERSISTENT;
@@ -366,8 +371,8 @@ public class BinaryProtoLookupServiceTest {
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("lookup-test-sched"));
- try (BinaryProtoLookupService lookup = new BinaryProtoLookupService(
- client, "pulsar://broker:6650", null, false, scheduler, null)) {
+ try (LookupService lookup = decoratedLookupService(new BinaryProtoLookupService(
+ client, "pulsar://broker:6650", null, false, scheduler, null))) {
TopicName topic = TopicName.get("persistent://public/default/t1");
boolean metadataAutoCreationEnabled = true;
@@ -426,8 +431,8 @@ public class BinaryProtoLookupServiceTest {
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("lookup-test-sched"));
- try (BinaryProtoLookupService lookup = new BinaryProtoLookupService(
- client, "pulsar://broker:6650", null, false, scheduler, null)) {
+ try (LookupService lookup = decoratedLookupService(new BinaryProtoLookupService(
+ client, "pulsar://broker:6650", null, false, scheduler, null))) {
TopicName topic = TopicName.get("persistent://public/default/t1");
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyLookupThrottlingTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyLookupThrottlingTest.java
index 00abe6c55c4..83321d0f776 100644
--- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyLookupThrottlingTest.java
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyLookupThrottlingTest.java
@@ -33,7 +33,6 @@ import org.apache.pulsar.client.api.AuthenticationFactory;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;
-import org.apache.pulsar.client.impl.BinaryProtoLookupService;
import org.apache.pulsar.client.impl.ClientCnx;
import org.apache.pulsar.client.impl.LookupService;
import org.apache.pulsar.client.impl.PulsarClientImpl;
@@ -135,7 +134,7 @@ public class ProxyLookupThrottlingTest extends MockedPulsarServiceBaseTest {
.serviceUrl(proxyService.getServiceUrl()).build();
String tpName = BrokerTestUtil.newUniqueName("persistent://public/default/tp");
LookupService lookupService = client.getLookup();
- assertTrue(lookupService instanceof BinaryProtoLookupService);
+ assertTrue(lookupService.isBinaryProtoLookupService());
ClientCnx lookupConnection = client.getCnxPool().getConnection(lookupService.resolveHost()).join();
// Make no permits to lookup.
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyWithExtensibleLoadManagerTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyWithExtensibleLoadManagerTest.java
index f0f8a3bbcae..2529c929a6f 100644
--- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyWithExtensibleLoadManagerTest.java
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyWithExtensibleLoadManagerTest.java
@@ -20,6 +20,7 @@ package org.apache.pulsar.proxy.server;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -190,7 +191,7 @@ public class ProxyWithExtensibleLoadManagerTest extends MultiBrokerBaseTest {
var producerClient = producerClientFuture.get();
@Cleanup
var producer = producerClient.newProducer(Schema.INT32).topic(topicName.toString()).create();
- LookupService producerLookupServiceSpy = spyField(producerClient, "lookup");
+ LookupService producerLookupServiceSpy = spyField(producerClient.getLookup(), "delegate");
@Cleanup
var consumerClient = consumerClientFuture.get();
@@ -200,7 +201,7 @@ public class ProxyWithExtensibleLoadManagerTest extends MultiBrokerBaseTest {
subscriptionName(BrokerTestUtil.newUniqueName("my-sub")).
ackTimeout(1000, TimeUnit.MILLISECONDS).
subscribe();
- LookupService consumerLookupServiceSpy = spyField(consumerClient, "lookup");
+ LookupService consumerLookupServiceSpy = spyField(consumerClient.getLookup(), "delegate");
var bundleRange = admin.lookups().getBundleRange(topicName.toString());
@@ -268,7 +269,7 @@ public class ProxyWithExtensibleLoadManagerTest extends MultiBrokerBaseTest {
@Cleanup
var producer = (ProducerImpl<Integer>) producerClient.newProducer(Schema.INT32).topic(topicName.toString()).
create();
- LookupService producerLookupServiceSpy = spyField(producerClient, "lookup");
+ LookupService producerLookupServiceSpy = spyField(producerClient.getLookup(), "delegate");
when(((ServiceNameResolver) spyField(producerLookupServiceSpy, "serviceNameResolver")).resolveHost()).
thenCallRealMethod().then(invocation -> getSourceBrokerInetAddress(topicName));
@@ -280,7 +281,7 @@ public class ProxyWithExtensibleLoadManagerTest extends MultiBrokerBaseTest {
subscriptionName(BrokerTestUtil.newUniqueName("my-sub")).
ackTimeout(1000, TimeUnit.MILLISECONDS).
subscribe();
- LookupService consumerLookupServiceSpy = spyField(consumerClient, "lookup");
+ LookupService consumerLookupServiceSpy = spyField(consumerClient.getLookup(), "delegate");
when(((ServiceNameResolver) spyField(consumerLookupServiceSpy, "serviceNameResolver")).resolveHost()).
thenCallRealMethod().then(invocation -> getSourceBrokerInetAddress(topicName));
@@ -341,9 +342,9 @@ public class ProxyWithExtensibleLoadManagerTest extends MultiBrokerBaseTest {
assertEquals(FieldUtils.readDeclaredField(consumer.getConnectionHandler(), "useProxy", true), Boolean.FALSE);
verify(producerClient, times(1)).getProxyConnection(any(), anyInt());
- verify(producerLookupServiceSpy, times(1)).getBroker(topicName);
+ verify(producerLookupServiceSpy, times(1)).getBroker(eq(topicName), any());
verify(consumerClient, times(1)).getProxyConnection(any(), anyInt());
- verify(consumerLookupServiceSpy, times(1)).getBroker(topicName);
+ verify(consumerLookupServiceSpy, times(1)).getBroker(eq(topicName), any());
}
}
diff --git a/pulsar-websocket/src/test/java/org/apache/pulsar/websocket/LookupProtocolTest.java b/pulsar-websocket/src/test/java/org/apache/pulsar/websocket/LookupProtocolTest.java
index 67dff01e1cc..da7c2892936 100644
--- a/pulsar-websocket/src/test/java/org/apache/pulsar/websocket/LookupProtocolTest.java
+++ b/pulsar-websocket/src/test/java/org/apache/pulsar/websocket/LookupProtocolTest.java
@@ -19,7 +19,9 @@
package org.apache.pulsar.websocket;
import io.netty.channel.epoll.Epoll;
+import java.io.IOException;
import java.lang.reflect.Field;
+import org.apache.pulsar.client.impl.LookupService;
import org.apache.pulsar.client.impl.PulsarClientImpl;
import org.apache.pulsar.websocket.service.WebSocketProxyConfiguration;
import org.testng.Assert;
@@ -38,12 +40,17 @@ public class LookupProtocolTest {
conf.setServiceUrl("http://localhost:8080");
conf.setServiceUrlTls("https://localhost:8443");
WebSocketService service = new WebSocketService(conf);
+ assertLookupIsBinaryProtoLookup(service, false);
+ service.close();
+ }
+
+ private static void assertLookupIsBinaryProtoLookup(WebSocketService service, boolean expected)
+ throws IOException, NoSuchFieldException, IllegalAccessException {
PulsarClientImpl testClient = (PulsarClientImpl) service.getPulsarClient();
Field lookupField = PulsarClientImpl.class.getDeclaredField("lookup");
lookupField.setAccessible(true);
- Assert.assertEquals(lookupField.get(testClient).getClass().getName(),
- "org.apache.pulsar.client.impl.HttpLookupService");
- service.close();
+ LookupService lookupService = (LookupService) lookupField.get(testClient);
+ Assert.assertEquals(expected, lookupService.isBinaryProtoLookupService());
}
@Test(timeOut = 10000)
@@ -55,10 +62,7 @@ public class LookupProtocolTest {
conf.setBrokerClientTlsEnabled(true);
WebSocketService service = new WebSocketService(conf);
PulsarClientImpl testClient = (PulsarClientImpl) service.getPulsarClient();
- Field lookupField = PulsarClientImpl.class.getDeclaredField("lookup");
- lookupField.setAccessible(true);
- Assert.assertEquals(lookupField.get(testClient).getClass().getName(),
- "org.apache.pulsar.client.impl.HttpLookupService");
+ assertLookupIsBinaryProtoLookup(service, false);
Assert.assertTrue(testClient.getConfiguration().isUseTls());
service.close();
}
@@ -71,11 +75,7 @@ public class LookupProtocolTest {
conf.setBrokerServiceUrl("pulsar://localhost:6650");
conf.setBrokerServiceUrlTls("pulsar+ssl://localhost:6651");
WebSocketService service = new WebSocketService(conf);
- PulsarClientImpl testClient = (PulsarClientImpl) service.getPulsarClient();
- Field lookupField = PulsarClientImpl.class.getDeclaredField("lookup");
- lookupField.setAccessible(true);
- Assert.assertEquals(lookupField.get(testClient).getClass().getName(),
- "org.apache.pulsar.client.impl.BinaryProtoLookupService");
+ assertLookupIsBinaryProtoLookup(service, true);
service.close();
}
@@ -89,10 +89,7 @@ public class LookupProtocolTest {
conf.setBrokerClientTlsEnabled(true);
WebSocketService service = new WebSocketService(conf);
PulsarClientImpl testClient = (PulsarClientImpl) service.getPulsarClient();
- Field lookupField = PulsarClientImpl.class.getDeclaredField("lookup");
- lookupField.setAccessible(true);
- Assert.assertEquals(lookupField.get(testClient).getClass().getName(),
- "org.apache.pulsar.client.impl.BinaryProtoLookupService");
+ assertLookupIsBinaryProtoLookup(service, true);
Assert.assertTrue(testClient.getConfiguration().isUseTls());
service.close();
}