You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by pe...@apache.org on 2026/10/19 16:49:42 UTC
(pulsar) branch master updated: [feat][broker] Add scalable-topic session and request metrics (#26980)
This is an automated email from the ASF dual-hosted git repository.
codelipenghui pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar.git
The following commit(s) were added to refs/heads/master by this push:
new 50a71f43e2ac [feat][broker] Add scalable-topic session and request metrics (#26980)
50a71f43e2ac is described below
commit 50a71f43e2acbedea35172437944b006072a8765
Author: Penghui Li <pe...@apache.org>
AuthorDate: Mon Oct 19 09:49:34 2026 -0700
[feat][broker] Add scalable-topic session and request metrics (#26980)
---
.../pulsar/broker/service/BrokerService.java | 7 +
.../broker/service/PulsarCommandSenderImpl.java | 11 +-
.../apache/pulsar/broker/service/ServerCnx.java | 116 ++-
.../broker/service/scalable/DagWatchSession.java | 118 ++-
.../service/scalable/ScalableTopicMetrics.java | 354 +++++++++
.../scalable/ScalableTopicsWatcherSession.java | 51 +-
.../service/ScalableTopicRequestMetricsTest.java | 455 ++++++++++++
.../ScalableTopicRequestWriteMetricsTest.java | 479 +++++++++++++
.../DagWatchSessionLookupCompatibilityTest.java | 220 ++++++
.../scalable/DagWatchSessionMetricsTest.java | 359 ++++++++++
.../service/scalable/DagWatchSessionTest.java | 5 +
.../ScalableTopicMetricsIsolationTest.java | 352 +++++++++
.../service/scalable/ScalableTopicMetricsTest.java | 794 +++++++++++++++++++++
...ScalableTopicsWatcherSessionDeleteRaceTest.java | 5 +-
.../ScalableTopicsWatcherSessionHashTest.java | 22 +-
.../ScalableTopicsWatcherSessionMetricsTest.java | 320 +++++++++
16 files changed, 3633 insertions(+), 35 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
index d7bd9dd1ee37..1ff71f1ed705 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
@@ -141,6 +141,7 @@ import org.apache.pulsar.broker.service.persistent.DispatchRateLimiterFactoryCla
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.broker.service.persistent.SystemTopic;
import org.apache.pulsar.broker.service.plugin.EntryFilterProvider;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics;
import org.apache.pulsar.broker.service.scalable.SegmentLoadReporter;
import org.apache.pulsar.broker.stats.BrokerOperabilityMetrics.TopicLoadFailureReason;
import org.apache.pulsar.broker.stats.ClusterReplicationMetrics;
@@ -346,6 +347,9 @@ public class BrokerService implements Closeable {
@Getter
private volatile org.apache.pulsar.broker.service.scalable.ScalableTopicService scalableTopicService;
+ @Getter
+ private final ScalableTopicMetrics scalableTopicMetrics;
+
private PulsarChannelInitializer.Factory pulsarChannelInitFactory = PulsarChannelInitializer.DEFAULT_FACTORY;
private final List<Channel> listenChannels = new ArrayList<>(2);
@@ -386,6 +390,8 @@ public class BrokerService implements Closeable {
this.keepAliveIntervalSeconds = pulsar.getConfiguration().getKeepAliveIntervalSeconds();
this.pendingTopicLoadingQueue = Queues.newConcurrentLinkedQueue();
this.pulsarStats = new PulsarStats(pulsar);
+ this.scalableTopicMetrics = new ScalableTopicMetrics(pulsar.getOpenTelemetry().getMeter(),
+ pulsar.getConfiguration().getClusterName());
this.topicOrderedExecutor = OrderedExecutor.newBuilder()
.numThreads(pulsar.getConfiguration().getTopicOrderedExecutorThreadNum())
@@ -1065,6 +1071,7 @@ public class BrokerService implements Closeable {
log.warn().exception(e).log("Error in closing authenticationService");
}
pulsarStats.close();
+ scalableTopicMetrics.close();
pendingTopicLoadOperationsCounter.close();
pendingLookupOperationsCounter.close();
try {
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
index dd53191c2ed5..7faa0b58bb94 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/PulsarCommandSenderImpl.java
@@ -32,6 +32,7 @@ import java.util.function.Function;
import lombok.CustomLog;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.pulsar.broker.intercept.BrokerInterceptor;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics.RequestType;
import org.apache.pulsar.client.api.transaction.TxnID;
import org.apache.pulsar.common.api.proto.BaseCommand;
import org.apache.pulsar.common.api.proto.CommandLookupTopicResponse;
@@ -86,7 +87,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
BaseCommand command = Commands.newSuccessCommand(requestId);
safeIntercept(command, cnx);
ByteBuf outBuf = Commands.serializeWithSize(command);
- writeAndFlush(outBuf);
+ cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.UNSUBSCRIBE, requestId, true);
}
@Override
@@ -94,7 +95,7 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
BaseCommand command = Commands.newErrorCommand(requestId, error, message);
safeIntercept(command, cnx);
ByteBuf outBuf = Commands.serializeWithSize(command);
- writeAndFlush(outBuf);
+ cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.UNSUBSCRIBE, requestId, false);
}
@Override
@@ -490,12 +491,14 @@ public class PulsarCommandSenderImpl implements PulsarCommandSender {
@Override
public void sendScalableTopicSubscribeResponse(long requestId,
org.apache.pulsar.common.api.proto.ScalableConsumerAssignment assignment) {
- writeAndFlush(Commands.newScalableTopicSubscribeResponse(requestId, assignment));
+ ByteBuf outBuf = Commands.newScalableTopicSubscribeResponse(requestId, assignment);
+ cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.SUBSCRIBE, requestId, true);
}
@Override
public void sendScalableTopicSubscribeError(long requestId, ServerError error, String message) {
- writeAndFlush(Commands.newScalableTopicSubscribeError(requestId, error, message));
+ ByteBuf outBuf = Commands.newScalableTopicSubscribeError(requestId, error, message);
+ cnx.writeScalableTopicResponse(cnx.ctx(), outBuf, RequestType.SUBSCRIBE, requestId, false);
}
@Override
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 e0ddb1b0669a..23f766feab7a 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
@@ -40,6 +40,7 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundBuffer;
+import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.FastThreadLocal;
@@ -106,6 +107,8 @@ import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.broker.service.scalable.ConsumerAssignment;
import org.apache.pulsar.broker.service.scalable.ConsumerSession;
import org.apache.pulsar.broker.service.scalable.DagWatchSession;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics.RequestType;
import org.apache.pulsar.broker.service.scalable.ScalableTopicService;
import org.apache.pulsar.broker.service.scalable.ScalableTopicsWatcherSession;
import org.apache.pulsar.broker.service.schema.SchemaRegistryService;
@@ -448,6 +451,13 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
super.channelInactive(ctx);
connectionController.decreaseConnection(ctx.channel().remoteAddress());
isActive = false;
+ // Claim only requests that have not handed their first response to the writer. Sent responses remain
+ // owned by their write promises, even if a successful write's listener has not been notified yet.
+ scalableResponseRequests.forEach((key, request) -> {
+ if (scalableResponseRequests.remove(key, request)) {
+ request.failure();
+ }
+ });
log.info("Closed connection");
if (brokerInterceptor != null) {
brokerInterceptor.onConnectionClosed(this);
@@ -828,6 +838,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
protected void handleCommandScalableTopicLookup(
CommandScalableTopicLookup commandScalableTopicLookup) {
checkArgument(state == State.Connected);
+ var request = service.getScalableTopicMetrics().startRequest(RequestType.LOOKUP);
final long sessionId = commandScalableTopicLookup.getSessionId();
final String topicStr = commandScalableTopicLookup.getTopic();
@@ -839,6 +850,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.log("Received ScalableTopicLookup");
if (!scalableTopicsEnabled) {
+ request.failure();
ctx.writeAndFlush(Commands.newScalableTopicError(sessionId, ServerError.NotAllowedError,
"Scalable topics are disabled on this broker"));
return;
@@ -849,6 +861,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
topicName = TopicName.get(topicStr);
} catch (Exception e) {
log.warn().attr("topic", topicStr).log("Invalid topic name in ScalableTopicLookup");
+ request.failure();
ctx.close();
return;
}
@@ -856,6 +869,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
// Scalable topics do not support non-persistent storage. Reject early with a
// clear error rather than failing later in segment infrastructure.
if (topicName.getDomain() == TopicDomain.non_persistent) {
+ request.failure();
ctx.writeAndFlush(Commands.newScalableTopicError(sessionId, ServerError.NotAllowedError,
"Scalable topics do not support non-persistent:// topics"));
return;
@@ -863,6 +877,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
if (!this.service.getPulsar().isRunning()) {
log.warn("ScalableTopicLookup rejected: broker not ready");
+ request.failure();
ctx.close();
return;
}
@@ -871,6 +886,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.getScalableTopicResources();
if (resources == null) {
log.warn("ScalableTopicLookup rejected: scalable topic resources not available");
+ request.failure();
ctx.close();
return;
}
@@ -883,23 +899,36 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.attr("principal", getPrincipal())
.attr("topic", topicName)
.log(msg);
+ request.failure();
ctx.writeAndFlush(Commands.newScalableTopicError(sessionId,
ServerError.AuthorizationError, msg));
return;
}
// Create a DagWatchSession that will send the initial layout and watch for changes
var session = new DagWatchSession(
- sessionId, topicName, this, resources, service, createIfMissing);
- dagWatchSessions.put(sessionId, session);
+ sessionId, topicName, this, resources, service, createIfMissing, request);
+ // Account for the map-owned watch without changing replacement/cleanup behavior.
+ var previous = dagWatchSessions.put(sessionId, session);
+ if (previous != null) {
+ previous.stopMetricsTracking();
+ }
+ if (!isActive) {
+ session.stopMetricsTracking();
+ request.failure();
+ }
session.start()
- .thenAcceptAsync(session::pushUpdate, ctx.executor())
+ .thenAcceptAsync(session::pushInitialResponse, ctx.executor())
.exceptionally(ex -> {
Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
log.warn().attr("topic", topicName).exception(cause)
.log("ScalableTopicLookup failed");
- dagWatchSessions.remove(sessionId);
+ var removed = dagWatchSessions.remove(sessionId);
+ if (removed != null) {
+ removed.stopMetricsTracking();
+ }
session.close();
+ request.failure();
ctx.executor().execute(() ->
ctx.writeAndFlush(Commands.newScalableTopicError(sessionId,
ServerError.TopicNotFound, cause.getMessage()))
@@ -910,6 +939,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.exceptionally(ex -> {
logAuthException(remoteAddress, "scalable-topic-lookup", getPrincipal(),
Optional.of(topicName), ex);
+ request.failure();
ctx.writeAndFlush(Commands.newScalableTopicError(sessionId,
ServerError.AuthorizationError,
"Exception occurred while trying to authorize ScalableTopicLookup"));
@@ -934,6 +964,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
protected void handleCommandWatchScalableTopics(
CommandWatchScalableTopics cmd) {
checkArgument(state == State.Connected);
+ var request = service.getScalableTopicMetrics().startRequest(RequestType.WATCH_TOPICS);
final long watchId = cmd.getWatchId();
final String namespaceStr = cmd.getNamespace();
@@ -941,6 +972,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.log("Received WatchScalableTopics");
if (!scalableTopicsEnabled) {
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.NotAllowedError, "Scalable topics are disabled on this broker"));
return;
@@ -951,6 +983,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
namespaceName = NamespaceName.get(namespaceStr);
} catch (Exception e) {
log.warn().attr("namespace", namespaceStr).log("Invalid namespace in WatchScalableTopics");
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.InvalidTopicName, "Invalid namespace: " + namespaceStr));
return;
@@ -965,6 +998,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
if (!this.service.getPulsar().isRunning()) {
log.warn("WatchScalableTopics rejected: broker not ready");
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.ServiceNotReady, "Broker not ready"));
return;
@@ -974,6 +1008,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
service.getPulsar().getPulsarResources().getScalableTopicResources();
if (resources == null) {
log.warn("WatchScalableTopics rejected: scalable topic resources not available");
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.ServiceNotReady, "Scalable topic resources not available"));
return;
@@ -985,19 +1020,33 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
final String msg = "Client is not authorized to WatchScalableTopics";
log.warn().attr("principal", getPrincipal()).attr("namespace", namespaceName)
.log(msg);
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.AuthorizationError, msg));
return;
}
var session = new ScalableTopicsWatcherSession(watchId, namespaceName, propertyFilters,
- clientHash, this, resources, service.getPulsar().getExecutor());
- scalableTopicsWatchers.put(watchId, session);
+ clientHash, this, resources, service.getPulsar().getExecutor(),
+ service.getScalableTopicMetrics(), request);
+ // Account for the map-owned watch without changing replacement/cleanup behavior.
+ var previous = scalableTopicsWatchers.put(watchId, session);
+ if (previous != null) {
+ previous.stopMetricsTracking();
+ }
+ if (!isActive) {
+ session.stopMetricsTracking();
+ request.failure();
+ }
session.start().exceptionally(ex -> {
Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
log.warn().attr("namespace", namespaceName).exception(cause)
.log("WatchScalableTopics failed");
- scalableTopicsWatchers.remove(watchId);
+ var removed = scalableTopicsWatchers.remove(watchId);
+ if (removed != null) {
+ removed.stopMetricsTracking();
+ }
+ request.failure();
session.close();
ctx.executor().execute(() -> ctx.writeAndFlush(
Commands.newWatchScalableTopicsError(watchId,
@@ -1008,6 +1057,7 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
.exceptionally(ex -> {
logNamespaceNameAuthException(remoteAddress, "watch-scalable-topics",
getPrincipal(), Optional.of(namespaceName), ex);
+ request.failure();
ctx.writeAndFlush(Commands.newWatchScalableTopicsError(watchId,
ServerError.AuthorizationError,
"Exception occurred while authorizing WatchScalableTopics"));
@@ -1174,11 +1224,58 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
long requestId,
AtomicBoolean answered) {}
+ private record ScalableRequestKey(RequestType type, long requestId) {}
+
+ private final ConcurrentHashMap<ScalableRequestKey, ScalableTopicMetrics.Request> scalableResponseRequests =
+ new ConcurrentHashMap<>();
+
+ private void trackScalableResponse(RequestType type, long requestId) {
+ PulsarCommandSender sender = getCommandSender();
+ // Do not invent a write-completion result for custom senders or subclasses that can override the
+ // existing void methods. Their original dispatch stays intact; observation requires the native writer.
+ if (sender == null || sender.getClass() != PulsarCommandSenderImpl.class) {
+ return;
+ }
+ var request = service.getScalableTopicMetrics().startRequest(type);
+ if (!isActive) {
+ request.failure();
+ return;
+ }
+ scalableResponseRequests.put(new ScalableRequestKey(type, requestId), request);
+ }
+
+ /** Observe the first response without changing serialization, interception, ordering or failure forwarding. */
+ void writeScalableTopicResponse(ChannelHandlerContext writeContext, ByteBuf response,
+ RequestType type, long requestId, boolean operationSuccess) {
+ var request = scalableResponseRequests.isEmpty() ? null
+ : scalableResponseRequests.remove(new ScalableRequestKey(type, requestId));
+ if (request == null) {
+ NettyChannelUtil.writeAndFlushWithVoidPromise(writeContext, response);
+ return;
+ }
+ try {
+ // unvoid() retains the original void promise's exception forwarding. A fresh promise would not.
+ ChannelPromise promise = writeContext.voidPromise().unvoid();
+ promise.addListener(future -> {
+ if (operationSuccess && future.isSuccess()) {
+ request.success();
+ } else {
+ request.failure();
+ }
+ });
+ writeContext.writeAndFlush(response, promise);
+ } catch (RuntimeException e) {
+ request.failure();
+ throw e;
+ }
+ }
+
@Override
protected void handleCommandScalableTopicSubscribe(
CommandScalableTopicSubscribe
commandScalableTopicSubscribe) {
checkArgument(state == State.Connected);
+ trackScalableResponse(RequestType.SUBSCRIBE, commandScalableTopicSubscribe.getRequestId());
final long requestId = commandScalableTopicSubscribe.getRequestId();
final String topicStr = commandScalableTopicSubscribe.getTopic();
@@ -1332,11 +1429,12 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
protected void handleCommandScalableTopicUnsubscribe(
CommandScalableTopicUnsubscribe commandScalableTopicUnsubscribe) {
checkArgument(state == State.Connected);
+ trackScalableResponse(RequestType.UNSUBSCRIBE, commandScalableTopicUnsubscribe.getRequestId());
final long requestId = commandScalableTopicUnsubscribe.getRequestId();
final long consumerId = commandScalableTopicUnsubscribe.getConsumerId();
if (!scalableTopicsEnabled) {
- writeAndFlush(Commands.newError(requestId, ServerError.NotAllowedError,
- "Scalable topics are disabled on this broker"));
+ writeScalableTopicResponse(ctx, Commands.newError(requestId, ServerError.NotAllowedError,
+ "Scalable topics are disabled on this broker"), RequestType.UNSUBSCRIBE, requestId, false);
return;
}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/DagWatchSession.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/DagWatchSession.java
index a1644fb606eb..93ce378a2c82 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/DagWatchSession.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/DagWatchSession.java
@@ -19,10 +19,12 @@
package org.apache.pulsar.broker.service.scalable;
import io.github.merlimat.slog.Logger;
+import io.netty.channel.ChannelFuture;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
import lombok.Getter;
import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
import org.apache.pulsar.broker.resources.ScalableTopicResources;
@@ -79,6 +81,11 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
* it (set by namespace consumers so a deleted topic isn't resurrected on a per-topic reconnect). */
private final boolean createIfMissing;
private volatile boolean closed = false;
+ private final AtomicBoolean metricsTrackingStopped = new AtomicBoolean();
+ private final AtomicBoolean initialResponseCompleted = new AtomicBoolean();
+ private final AtomicBoolean layoutWritten = new AtomicBoolean();
+ private final ScalableTopicMetrics metrics;
+ private final ScalableTopicMetrics.Request request;
public DagWatchSession(long sessionId,
TopicName topicName,
@@ -86,6 +93,16 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
ScalableTopicResources resources,
BrokerService brokerService,
boolean createIfMissing) {
+ this(sessionId, topicName, cnx, resources, brokerService, createIfMissing, null);
+ }
+
+ public DagWatchSession(long sessionId,
+ TopicName topicName,
+ ServerCnx cnx,
+ ScalableTopicResources resources,
+ BrokerService brokerService,
+ boolean createIfMissing,
+ ScalableTopicMetrics.Request request) {
this.sessionId = sessionId;
this.topicName = topicName;
this.cnx = cnx;
@@ -96,6 +113,11 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
this.scalableTopicName = topicName.toScalableTopic();
this.resolvedTopicName = scalableTopicName.toString();
this.log = LOG.with().attr("topic", topicName).attr("sessionId", sessionId).build();
+ this.metrics = brokerService.getScalableTopicMetrics();
+ this.request = request;
+ if (metrics != null) {
+ metrics.sessionOpened(ScalableTopicMetrics.WatchType.TOPIC);
+ }
}
@Override
@@ -283,8 +305,19 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
return;
}
// Metadata changed — reload and push update
- resources.getScalableTopicMetadataAsync(topicName, true)
- .thenAccept(optMd -> optMd.ifPresent(this::onMetadataChanged));
+ CompletableFuture<Optional<ScalableTopicMetadata>> metadata;
+ try {
+ metadata = resources.getScalableTopicMetadataAsync(topicName, true);
+ } catch (RuntimeException e) {
+ recordWatchUpdate(false);
+ throw e;
+ }
+ metadata.whenComplete((ignored, error) -> {
+ if (error != null) {
+ recordWatchUpdate(false);
+ }
+ });
+ metadata.thenAccept(optMd -> optMd.ifPresent(this::onMetadataChanged));
}
/**
@@ -294,22 +327,78 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
if (closed) {
return;
}
- buildResponse(newMetadata).thenAccept(this::pushUpdate);
+ CompletableFuture<ScalableTopicLayoutResponse> response;
+ try {
+ response = buildResponse(newMetadata);
+ } catch (RuntimeException e) {
+ recordWatchUpdate(false);
+ throw e;
+ }
+ response.whenComplete((ignored, error) -> {
+ if (error != null) {
+ recordWatchUpdate(false);
+ }
+ });
+ response.thenAccept(this::pushUpdate);
+ }
+
+ /**
+ * Push the initial snapshot, completing the lookup request only when its write completes.
+ * Initial snapshots are not watch updates.
+ */
+ public void pushInitialResponse(ScalableTopicLayoutResponse response) {
+ pushResponse(response, true);
}
/**
- * Push an update to the connected client.
+ * Push a subsequent layout update to the connected client.
*/
public void pushUpdate(ScalableTopicLayoutResponse response) {
+ pushResponse(response, false);
+ }
+
+ private void pushResponse(ScalableTopicLayoutResponse response, boolean initial) {
if (closed) {
return;
}
- ScalableTopicDAG dag = buildDagProto(response);
- log.info().attr("epoch", response.epoch()).log("Pushing DAG update");
- // Always report the canonical topic://... identity so clients that looked up
- // via persistent://... or short-form know the resolved name.
- cnx.ctx().writeAndFlush(Commands.newScalableTopicUpdate(
- sessionId, resolvedTopicName, dag));
+ try {
+ ScalableTopicDAG dag = buildDagProto(response);
+ log.info().attr("epoch", response.epoch()).log("Pushing DAG update");
+ // Always report the canonical topic://... identity so clients that looked up
+ // via persistent://... or short-form know the resolved name.
+ ChannelFuture write = cnx.ctx().writeAndFlush(Commands.newScalableTopicUpdate(
+ sessionId, resolvedTopicName, dag));
+ write.addListener(future -> responseWritten(initial, future.isSuccess()));
+ } catch (RuntimeException e) {
+ responseWritten(initial, false);
+ throw e;
+ }
+ }
+
+ private void responseWritten(boolean initial, boolean success) {
+ // A notification may overtake start()'s metadata read. Complete the request
+ // on the first layout actually written, regardless of which read built it.
+ boolean firstResponse = layoutWritten.compareAndSet(false, true) && request != null;
+ completeInitialRequest(success);
+ if (!initial && !firstResponse) {
+ recordWatchUpdate(success);
+ }
+ }
+
+ private void recordWatchUpdate(boolean success) {
+ if (metrics != null && !metricsTrackingStopped.get()) {
+ metrics.recordWatchUpdate(success);
+ }
+ }
+
+ private void completeInitialRequest(boolean success) {
+ if (request != null && initialResponseCompleted.compareAndSet(false, true)) {
+ if (success) {
+ request.success();
+ } else {
+ request.failure();
+ }
+ }
}
private ScalableTopicDAG buildDagProto(ScalableTopicLayoutResponse response) {
@@ -372,12 +461,21 @@ public class DagWatchSession implements ScalableTopicResources.MetadataPathListe
public void close() {
closed = true;
+ completeInitialRequest(false);
+ stopMetricsTracking();
// Drop ourselves from the resources' fan-out so the per-event dispatch skips
// us — no listener leak, no per-notification dispatch tax across the broker's
// lifetime.
resources.deregisterPathListener(this);
}
+ /** Stops counting this session without changing its lifecycle or request completion. */
+ public void stopMetricsTracking() {
+ if (metricsTrackingStopped.compareAndSet(false, true) && metrics != null) {
+ metrics.sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ }
+ }
+
/**
* Build a full layout response with broker addresses resolved.
*/
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetrics.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetrics.java
new file mode 100644
index 000000000000..261edb4b8735
--- /dev/null
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetrics.java
@@ -0,0 +1,354 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import com.google.common.annotations.VisibleForTesting;
+import io.opentelemetry.api.common.Attributes;
+import io.opentelemetry.api.metrics.DoubleHistogram;
+import io.opentelemetry.api.metrics.Meter;
+import io.opentelemetry.api.metrics.ObservableLongCounter;
+import io.opentelemetry.api.metrics.ObservableLongUpDownCounter;
+import io.prometheus.client.Collector;
+import io.prometheus.client.CollectorRegistry;
+import io.prometheus.client.Histogram;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+
+/** Broker-level scalable-topic session and control-plane request metrics, exported on both metrics paths. */
+public final class ScalableTopicMetrics implements AutoCloseable {
+ public static final String REQUEST_DURATION_METRIC_NAME = "pulsar.broker.scalable_topic.request.duration";
+ public static final String WATCH_SESSION_COUNT_METRIC_NAME = "pulsar.broker.scalable_topic.watch.session.count";
+ public static final String WATCH_UPDATE_COUNT_METRIC_NAME = "pulsar.broker.scalable_topic.watch.update.count";
+
+ private static final String REQUEST_DURATION = "pulsar_scalable_topic_request_duration_seconds";
+ private static final String WATCH_SESSION_COUNT = "pulsar_scalable_topic_watch_session_count";
+ private static final String WATCH_UPDATE = "pulsar_scalable_topic_watch_update";
+ private static final String ATTRIBUTE_PREFIX = "pulsar.scalable_topic.";
+ private static final String REQUEST_HELP = "Scalable-topic request duration from arrival to the first response.";
+ private static final String SESSION_HELP = "Open scalable-topic watch sessions.";
+ private static final String UPDATE_HELP = "Scalable-topic layout update pushes, excluding initial snapshots.";
+ private static final List<Double> DURATION_BUCKETS =
+ List.of(0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 5.0, 30.0);
+
+ // One collector per registry aggregates brokers with the same cluster label. A broker must not unregister
+ // another broker's metrics, or publish duplicate samples when several brokers run in the same JVM.
+ private static final Map<CollectorRegistry, SharedCollector> COLLECTORS = new IdentityHashMap<>();
+
+ public enum RequestType {
+ LOOKUP("lookup"),
+ WATCH_TOPICS("watch_topics"),
+ SUBSCRIBE("subscribe"),
+ UNSUBSCRIBE("unsubscribe");
+
+ private final String label;
+ private final Attributes successAttributes;
+ private final Attributes failureAttributes;
+
+ RequestType(String label) {
+ this.label = label;
+ successAttributes = Attributes.builder()
+ .put(ATTRIBUTE_PREFIX + "request.type", label)
+ .put(ATTRIBUTE_PREFIX + "operation.status", "success").build();
+ failureAttributes = Attributes.builder()
+ .put(ATTRIBUTE_PREFIX + "request.type", label)
+ .put(ATTRIBUTE_PREFIX + "operation.status", "failure").build();
+ }
+ }
+
+ public enum WatchType {
+ TOPIC("topic"),
+ NAMESPACE("namespace");
+
+ private final String label;
+ private final Attributes attributes;
+
+ WatchType(String label) {
+ this.label = label;
+ attributes = Attributes.builder().put(ATTRIBUTE_PREFIX + "watch.type", label).build();
+ }
+ }
+
+ private static final Attributes SUCCESS_ATTRIBUTES =
+ Attributes.builder().put(ATTRIBUTE_PREFIX + "operation.status", "success").build();
+ private static final Attributes FAILURE_ATTRIBUTES =
+ Attributes.builder().put(ATTRIBUTE_PREFIX + "operation.status", "failure").build();
+
+ private final String cluster;
+ private final CollectorRegistry registry;
+ private final LongSupplier nanoTime;
+ private final AtomicBoolean closed = new AtomicBoolean();
+ private final Object cumulativeLock = new Object();
+ private final AtomicLong[] watchSessions = {new AtomicLong(), new AtomicLong()};
+ private final AtomicLong successfulUpdates = new AtomicLong();
+ private final AtomicLong failedUpdates = new AtomicLong();
+ private final Histogram prometheusRequestDuration;
+ private final DoubleHistogram requestDuration;
+ private final ObservableLongUpDownCounter sessionCount;
+ private final ObservableLongCounter updateCount;
+
+ public ScalableTopicMetrics(Meter meter, String cluster) {
+ this(meter, cluster, CollectorRegistry.defaultRegistry);
+ }
+
+ public ScalableTopicMetrics(Meter meter, String cluster, CollectorRegistry registry) {
+ this(meter, cluster, registry, System::nanoTime);
+ }
+
+ @VisibleForTesting
+ ScalableTopicMetrics(Meter meter, String cluster, CollectorRegistry registry, LongSupplier nanoTime) {
+ this.cluster = Objects.requireNonNull(cluster);
+ this.registry = Objects.requireNonNull(registry);
+ this.nanoTime = Objects.requireNonNull(nanoTime);
+ Objects.requireNonNull(meter);
+ // The shared collector exports no exemplars. Disable sampling here so recording under the freeze lock
+ // cannot invoke a globally configured exemplar sampler.
+ prometheusRequestDuration = Histogram.build(REQUEST_DURATION, REQUEST_HELP)
+ .labelNames("cluster", "request_type", "operation_status")
+ .withoutExemplars()
+ .buckets(DURATION_BUCKETS.stream().mapToDouble(Double::doubleValue).toArray()).create();
+ requestDuration = meter.histogramBuilder(REQUEST_DURATION_METRIC_NAME)
+ .setDescription(REQUEST_HELP).setUnit("s")
+ .setExplicitBucketBoundariesAdvice(DURATION_BUCKETS).build();
+ sessionCount = meter.upDownCounterBuilder(WATCH_SESSION_COUNT_METRIC_NAME)
+ .setDescription(SESSION_HELP).setUnit("{session}")
+ .buildWithCallback(measurement -> {
+ for (WatchType type : WatchType.values()) {
+ measurement.record(watchSessions[type.ordinal()].get(), type.attributes);
+ }
+ });
+ updateCount = meter.counterBuilder(WATCH_UPDATE_COUNT_METRIC_NAME)
+ .setDescription(UPDATE_HELP).setUnit("{update}")
+ .buildWithCallback(measurement -> {
+ measurement.record(successfulUpdates.get(), SUCCESS_ATTRIBUTES);
+ measurement.record(failedUpdates.get(), FAILURE_ATTRIBUTES);
+ });
+ try {
+ synchronized (COLLECTORS) {
+ SharedCollector collector = COLLECTORS.get(registry);
+ if (collector == null) {
+ collector = new SharedCollector();
+ registry.register(collector);
+ COLLECTORS.put(registry, collector);
+ }
+ collector.add(this);
+ }
+ } catch (RuntimeException e) {
+ sessionCount.close();
+ updateCount.close();
+ throw e;
+ }
+ }
+
+ /** Starts timing at request arrival; only the first response records an outcome. */
+ public Request startRequest(RequestType type) {
+ return new Request(Objects.requireNonNull(type));
+ }
+
+ public void sessionOpened(WatchType type) {
+ if (!closed.get()) {
+ watchSessions[type.ordinal()].incrementAndGet();
+ }
+ }
+
+ public void sessionClosed(WatchType type) {
+ if (!closed.get()) {
+ watchSessions[type.ordinal()].decrementAndGet();
+ }
+ }
+
+ public void recordWatchUpdate(boolean success) {
+ synchronized (cumulativeLock) {
+ if (!closed.get()) {
+ (success ? successfulUpdates : failedUpdates).incrementAndGet();
+ }
+ }
+ }
+
+ public final class Request {
+ private final RequestType type;
+ private final long startedAt;
+ private final AtomicBoolean completed = new AtomicBoolean();
+
+ private Request(RequestType type) {
+ this.type = type;
+ startedAt = nanoTime.getAsLong();
+ }
+
+ public void success() {
+ complete(true);
+ }
+
+ public void failure() {
+ complete(false);
+ }
+
+ private void complete(boolean success) {
+ if (!completed.compareAndSet(false, true) || closed.get()) {
+ return;
+ }
+ double seconds = (nanoTime.getAsLong() - startedAt) / 1_000_000_000.0;
+ synchronized (cumulativeLock) {
+ if (closed.get()) {
+ return;
+ }
+ prometheusRequestDuration.labels(cluster, type.label, success ? "success" : "failure").observe(seconds);
+ }
+ // An accepted observation must reach both paths even if close() runs here. Keep SDK calls outside the lock.
+ requestDuration.record(seconds, success ? type.successAttributes : type.failureAttributes);
+ }
+ }
+
+ @Override
+ public void close() {
+ List<Collector.MetricFamilySamples> cumulative;
+ synchronized (cumulativeLock) {
+ if (!closed.compareAndSet(false, true)) {
+ return;
+ }
+ // Freeze cumulative state before transferring it; an in-flight recording cannot be lost at retirement.
+ cumulative = collectCumulative();
+ }
+ sessionCount.close();
+ updateCount.close();
+ synchronized (COLLECTORS) {
+ SharedCollector collector = COLLECTORS.get(registry);
+ collector.retire(this, cumulative);
+ if (collector.isEmpty()) {
+ registry.unregister(collector);
+ COLLECTORS.remove(registry);
+ }
+ }
+ }
+
+ private List<Collector.MetricFamilySamples> collect() {
+ List<Collector.MetricFamilySamples.Sample> sessions = new ArrayList<>();
+ for (WatchType type : WatchType.values()) {
+ sessions.add(new Collector.MetricFamilySamples.Sample(WATCH_SESSION_COUNT,
+ List.of("cluster", "watch_type"), List.of(cluster, type.label),
+ watchSessions[type.ordinal()].get()));
+ }
+ List<Collector.MetricFamilySamples> families = collectCumulative();
+ families.add(new Collector.MetricFamilySamples(
+ WATCH_SESSION_COUNT, Collector.Type.GAUGE, SESSION_HELP, sessions));
+ return families;
+ }
+
+ private List<Collector.MetricFamilySamples> collectCumulative() {
+ List<Collector.MetricFamilySamples.Sample> updates = List.of(
+ new Collector.MetricFamilySamples.Sample(WATCH_UPDATE + "_total",
+ List.of("cluster", "operation_status"), List.of(cluster, "success"), successfulUpdates.get()),
+ new Collector.MetricFamilySamples.Sample(WATCH_UPDATE + "_total",
+ List.of("cluster", "operation_status"), List.of(cluster, "failure"), failedUpdates.get()));
+ List<Collector.MetricFamilySamples> families = new ArrayList<>(prometheusRequestDuration.collect());
+ families.add(new Collector.MetricFamilySamples(WATCH_UPDATE, Collector.Type.COUNTER, UPDATE_HELP, updates));
+ return families;
+ }
+
+ private record SampleKey(String family, String name, List<String> labelNames, List<String> labelValues) {
+ private SampleKey(Collector.MetricFamilySamples family, Collector.MetricFamilySamples.Sample sample) {
+ this(family.name, sample.name, List.copyOf(sample.labelNames), List.copyOf(sample.labelValues));
+ }
+
+ private String cluster() {
+ return labelValues.get(labelNames.indexOf("cluster"));
+ }
+ }
+
+ private static final class SharedCollector extends Collector implements Collector.Describable {
+ // Publish membership and retired totals together, so a scrape sees each broker's contribution exactly once.
+ // Writers hold COLLECTORS; scrapes read one immutable snapshot without taking that lock.
+ private record State(List<ScalableTopicMetrics> brokers, Map<SampleKey, BigDecimal> retired) {}
+ private volatile State state = new State(List.of(), Map.of());
+
+ private void add(ScalableTopicMetrics broker) {
+ State current = state;
+ List<ScalableTopicMetrics> brokers = new ArrayList<>(current.brokers);
+ brokers.add(broker);
+ state = new State(List.copyOf(brokers), current.retired);
+ }
+
+ private void retire(ScalableTopicMetrics broker, List<MetricFamilySamples> cumulative) {
+ State current = state;
+ List<ScalableTopicMetrics> brokers = new ArrayList<>(current.brokers);
+ brokers.remove(broker);
+ Map<SampleKey, BigDecimal> retired = new LinkedHashMap<>(current.retired);
+ if (brokers.stream().anyMatch(active -> active.cluster.equals(broker.cluster))) {
+ merge(retired, cumulative);
+ } else {
+ // The last broker ends this cluster's series lifetime. Retain no history for inactive clusters.
+ retired.keySet().removeIf(key -> key.cluster().equals(broker.cluster));
+ }
+ // Only fixed-label sample totals are retained, never retired brokers or their SDK callbacks.
+ state = new State(List.copyOf(brokers), Map.copyOf(retired));
+ }
+
+ private boolean isEmpty() {
+ return state.brokers.isEmpty();
+ }
+
+ @Override
+ public List<MetricFamilySamples> describe() {
+ return List.of(new MetricFamilySamples(REQUEST_DURATION, Type.HISTOGRAM, REQUEST_HELP, List.of()),
+ new MetricFamilySamples(WATCH_SESSION_COUNT, Type.GAUGE, SESSION_HELP, List.of()),
+ new MetricFamilySamples(WATCH_UPDATE, Type.COUNTER, UPDATE_HELP, List.of()));
+ }
+
+ private static void merge(Map<SampleKey, BigDecimal> samples, List<MetricFamilySamples> families) {
+ for (MetricFamilySamples family : families) {
+ for (MetricFamilySamples.Sample sample : family.samples) {
+ // Creation timestamps cannot be summed, and are not part of these metric families.
+ if (!sample.name.endsWith("_created")) {
+ samples.merge(new SampleKey(family, sample), BigDecimal.valueOf(sample.value), BigDecimal::add);
+ }
+ }
+ }
+ }
+
+ @Override
+ public List<MetricFamilySamples> collect() {
+ State current = state;
+ // Exact aggregation avoids a floating-point _sum decrease when retirement changes the grouping.
+ Map<SampleKey, BigDecimal> totals = new LinkedHashMap<>(current.retired);
+ for (ScalableTopicMetrics broker : current.brokers) {
+ // Frozen brokers remain readable by scrapes that captured the pre-retirement snapshot.
+ merge(totals, broker.collect());
+ }
+ List<MetricFamilySamples> result = new ArrayList<>();
+ for (MetricFamilySamples description : describe()) {
+ List<MetricFamilySamples.Sample> samples = new ArrayList<>();
+ totals.forEach((key, value) -> {
+ if (key.family.equals(description.name)) {
+ samples.add(new MetricFamilySamples.Sample(
+ key.name, key.labelNames, key.labelValues, value.doubleValue()));
+ }
+ });
+ result.add(new MetricFamilySamples(description.name, description.type, description.help, samples));
+ }
+ return result;
+ }
+ }
+}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSession.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSession.java
index 055be5adc6df..2fc5925c19fb 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSession.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSession.java
@@ -19,6 +19,7 @@
package org.apache.pulsar.broker.service.scalable;
import io.github.merlimat.slog.Logger;
+import io.netty.channel.ChannelFuture;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
@@ -121,6 +122,10 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
private final AtomicBoolean closed = new AtomicBoolean();
private final AtomicBoolean snapshotEmitted = new AtomicBoolean();
+ private final AtomicBoolean initialResponseCompleted = new AtomicBoolean();
+ private final AtomicBoolean metricsTrackingStopped = new AtomicBoolean();
+ private final ScalableTopicMetrics metrics;
+ private final ScalableTopicMetrics.Request request;
// --- Coalescing state. All three fields guarded by `coalesceLock`. ---
private final Object coalesceLock = new Object();
@@ -135,6 +140,19 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
ServerCnx cnx,
ScalableTopicResources resources,
ScheduledExecutorService scheduler) {
+ this(watchId, namespace, propertyFilters, clientHash, cnx, resources, scheduler,
+ cnx.getBrokerService() == null ? null : cnx.getBrokerService().getScalableTopicMetrics(), null);
+ }
+
+ public ScalableTopicsWatcherSession(long watchId,
+ NamespaceName namespace,
+ Map<String, String> propertyFilters,
+ String clientHash,
+ ServerCnx cnx,
+ ScalableTopicResources resources,
+ ScheduledExecutorService scheduler,
+ ScalableTopicMetrics metrics,
+ ScalableTopicMetrics.Request request) {
this.watchId = watchId;
this.namespace = namespace;
this.propertyFilters = propertyFilters == null ? Map.of() : propertyFilters;
@@ -148,6 +166,11 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
.attr("watchId", watchId)
.attr("filters", this.propertyFilters)
.build();
+ this.metrics = metrics;
+ this.request = request;
+ if (metrics != null) {
+ metrics.sessionOpened(ScalableTopicMetrics.WatchType.NAMESPACE);
+ }
}
@Override
@@ -194,10 +217,10 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
if (clientHash != null && clientHash.equals(TopicList.calculateHash(initialTopics))) {
log.info().attr("topics", initialTopics.size())
.log("Reconnect hash matched; skipping snapshot");
+ completeInitialRequest(true);
} else {
log.info().attr("topics", initialTopics.size()).log("Initial snapshot");
- cnx.ctx().writeAndFlush(
- Commands.newWatchScalableTopicsSnapshot(watchId, initialTopics));
+ pushSnapshot(initialTopics);
}
// Diffs are computed against the snapshot's set: let them out only after it.
snapshotEmitted.set(true);
@@ -205,6 +228,21 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
});
}
+ private void pushSnapshot(List<String> topics) {
+ ChannelFuture write = cnx.ctx().writeAndFlush(Commands.newWatchScalableTopicsSnapshot(watchId, topics));
+ write.addListener(future -> completeInitialRequest(future.isSuccess()));
+ }
+
+ private void completeInitialRequest(boolean success) {
+ if (request != null && initialResponseCompleted.compareAndSet(false, true)) {
+ if (success) {
+ request.success();
+ } else {
+ request.failure();
+ }
+ }
+ }
+
/**
* Invoked by {@link ScalableTopicResources} for every metadata event whose path
* is a direct child of this watcher's namespace base path. The resources-level
@@ -361,6 +399,15 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
if (!closed.compareAndSet(false, true)) {
return;
}
+ completeInitialRequest(false);
+ stopMetricsTracking();
resources.deregisterNamespaceListener(this);
}
+
+ /** Stops counting this session without changing its lifecycle or request completion. */
+ public void stopMetricsTracking() {
+ if (metricsTrackingStopped.compareAndSet(false, true) && metrics != null) {
+ metrics.sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ }
+ }
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestMetricsTest.java
new file mode 100644
index 000000000000..09dc0eea5bba
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestMetricsTest.java
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.EventLoop;
+import io.netty.channel.VoidChannelPromise;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+import io.opentelemetry.api.OpenTelemetry;
+import io.prometheus.client.CollectorRegistry;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.authorization.AuthorizationService;
+import org.apache.pulsar.broker.resources.PulsarResources;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
+import org.apache.pulsar.broker.service.scalable.ConsumerAssignment;
+import org.apache.pulsar.broker.service.scalable.ConsumerSession;
+import org.apache.pulsar.broker.service.scalable.DagWatchSession;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicService;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicsWatcherSession;
+import org.apache.pulsar.broker.testcontext.PulsarTestContext;
+import org.apache.pulsar.common.api.proto.BaseCommand;
+import org.apache.pulsar.common.api.proto.ScalableConsumerAssignment;
+import org.apache.pulsar.common.api.proto.ScalableConsumerType;
+import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
+import org.apache.pulsar.common.protocol.Commands;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker", timeOut = 30000)
+public class ScalableTopicRequestMetricsTest {
+ private PulsarTestContext context;
+ private BrokerService brokerService;
+ private ServerCnx cnx;
+ private EmbeddedChannel channel;
+ private CollectorRegistry registry;
+ private ScalableTopicMetrics metrics;
+ private ServiceConfiguration config;
+ private final List<DagWatchSession> dagSessions = new ArrayList<>();
+ private final List<ScalableTopicsWatcherSession> namespaceSessions = new ArrayList<>();
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ dagSessions.clear();
+ namespaceSessions.clear();
+ config = new ServiceConfiguration();
+ config.setClusterName("test");
+ config.setBrokerShutdownTimeoutMs(0L);
+ config.setLoadBalancerOverrideBrokerNicSpeedGbps(Optional.of(1.0));
+ config.setBacklogQuotaCheckEnabled(false);
+ context = PulsarTestContext.builderForNonStartableContext().config(config).spyByDefault().build();
+ brokerService = context.getBrokerService();
+ registry = new CollectorRegistry();
+ metrics = new ScalableTopicMetrics(OpenTelemetry.noop().getMeter("test"), "test", registry);
+ when(brokerService.getScalableTopicMetrics()).thenReturn(metrics);
+ }
+
+ private void connect() {
+ connect(new ServerCnx(context.getPulsarService()));
+ }
+
+ private void connect(ServerCnx connection) {
+ cnx = connection;
+ channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(5 * 1024 * 1024, 0, 4, 0, 4), cnx);
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(readResponse().getType()).isEqualTo(BaseCommand.Type.CONNECTED);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void cleanup() throws Exception {
+ if (channel != null) {
+ channel.finishAndReleaseAll();
+ }
+ dagSessions.forEach(DagWatchSession::close);
+ namespaceSessions.forEach(ScalableTopicsWatcherSession::close);
+ if (metrics != null) {
+ metrics.close();
+ }
+ if (context != null) {
+ context.close();
+ }
+ }
+
+ @Test
+ public void disabledRequestsAreFailures() {
+ config.setScalableTopicsEnabled(false);
+ connect();
+ channel.writeInbound(Commands.newScalableTopicLookup(1, "topic://public/default/t"));
+ readResponse();
+ channel.writeInbound(Commands.newWatchScalableTopics(2, "public/default", null, null));
+ readResponse();
+ channel.writeInbound(Commands.newScalableTopicSubscribe(3, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ readResponse();
+ channel.writeInbound(Commands.newScalableTopicUnsubscribe(4, 1));
+ readResponse();
+ for (String type : List.of("lookup", "watch_topics", "subscribe", "unsubscribe")) {
+ assertRequestCount(type, "failure", 1);
+ assertRequestCount(type, "success", 0);
+ }
+ assertSessions("topic", 0);
+ assertSessions("namespace", 0);
+ }
+
+ @Test
+ public void authorizationFailureIsMeasuredWithoutOpeningWatch() {
+ var authorization = mock(AuthorizationService.class);
+ when(brokerService.isAuthorizationEnabled()).thenReturn(true);
+ when(brokerService.getAuthorizationService()).thenReturn(authorization);
+ var allowed = new CompletableFuture<Boolean>();
+ when(authorization.allowTopicOperationAsync(any(), any(), any(), any(), any(), any()))
+ .thenReturn(allowed);
+ connect();
+ channel.writeInbound(Commands.newScalableTopicLookup(1, "topic://public/default/t"));
+ channel.runPendingTasks();
+ assertRequestCount("lookup", "failure", 0);
+ assertSessions("topic", 0);
+ allowed.complete(false);
+ assertThat(readResponse().getScalableTopicUpdate().hasError()).isTrue();
+ assertRequestCount("lookup", "failure", 1);
+ assertSessions("topic", 0);
+ }
+
+ @Test
+ public void metricsPreserveLookupStartAfterLateAuthorization() {
+ var resources = spyScalableResources();
+ doReturn(CompletableFuture.completedFuture(new PartitionedTopicMetadata(0)))
+ .when(brokerService).fetchPartitionedTopicMetadataAsync(any());
+ var authorization = mock(AuthorizationService.class);
+ when(brokerService.isAuthorizationEnabled()).thenReturn(true);
+ when(brokerService.getAuthorizationService()).thenReturn(authorization);
+ var allowed = new CompletableFuture<Boolean>();
+ when(authorization.allowTopicOperationAsync(any(), any(), any(), any(), any(), any()))
+ .thenReturn(allowed);
+ connect();
+ channel.writeInbound(Commands.newScalableTopicLookup(1, "persistent://public/default/t"));
+ channel.close();
+ allowed.complete(true);
+ // Authorization still runs its original continuation, even after disconnect.
+ verify(resources).registerPathListener(any());
+ verify(resources, never()).deregisterPathListener(any());
+ channel.runPendingTasks();
+ assertRequestCount("lookup", "failure", 1);
+ assertSessions("topic", 0);
+ }
+
+ @Test
+ public void metricsPreserveSubscribeRegistrationAfterLateAuthorization() {
+ var authorization = mock(AuthorizationService.class);
+ when(brokerService.isAuthorizationEnabled()).thenReturn(true);
+ when(brokerService.getAuthorizationService()).thenReturn(authorization);
+ var allowed = new CompletableFuture<Boolean>();
+ when(authorization.allowTopicOperationAsync(any(), any(), any(), any(), any(), any()))
+ .thenReturn(allowed);
+ var service = mock(ScalableTopicService.class);
+ when(brokerService.getScalableTopicService()).thenReturn(service);
+ when(service.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.completedFuture(new ConsumerAssignment(1, List.of())));
+ connect();
+ channel.writeInbound(Commands.newScalableTopicSubscribe(1, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ channel.close();
+ allowed.complete(true);
+ // The metrics observer must not introduce an authorization executor hop or skip registration.
+ verify(service).registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any());
+ channel.runPendingTasks();
+ assertRequestCount("subscribe", "failure", 1);
+ assertRequestCount("subscribe", "success", 0);
+ }
+
+ @Test
+ public void lookupReplacementCloseAndDisconnect() {
+ var resources = spyScalableResources();
+ doReturn(CompletableFuture.completedFuture(new PartitionedTopicMetadata(0)))
+ .when(brokerService).fetchPartitionedTopicMetadataAsync(any());
+ connect();
+ for (int i = 0; i < 2; i++) {
+ channel.writeInbound(Commands.newScalableTopicLookup(1, "persistent://public/default/t"));
+ assertThat(readResponse().getScalableTopicUpdate().hasError()).isFalse();
+ assertSessions("topic", 1);
+ }
+ verify(resources, times(2)).registerPathListener(any());
+ verify(resources, never()).deregisterPathListener(any());
+ assertRequestCount("lookup", "success", 2);
+ assertThat(sample("pulsar_scalable_topic_watch_update_total",
+ new String[]{"cluster", "operation_status"}, new String[]{"test", "success"})).isZero();
+ channel.writeInbound(Commands.newScalableTopicClose(1));
+ channel.writeInbound(Commands.newScalableTopicClose(1));
+ assertSessions("topic", 0);
+ verify(resources, times(1)).deregisterPathListener(any());
+ channel.writeInbound(Commands.newScalableTopicLookup(2, "persistent://public/default/t"));
+ readResponse();
+ assertSessions("topic", 1);
+ channel.close();
+ assertSessions("topic", 0);
+ }
+
+ @Test
+ public void namespaceReplacementAndDisconnect() {
+ var resources = spyScalableResources();
+ connect();
+ for (int i = 0; i < 2; i++) {
+ channel.writeInbound(Commands.newWatchScalableTopics(1, "public/default", null, null));
+ assertThat(readResponse().getWatchScalableTopicsUpdate().hasError()).isFalse();
+ assertSessions("namespace", 1);
+ }
+ verify(resources, times(2)).registerNamespaceListener(any());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ assertRequestCount("watch_topics", "success", 2);
+ channel.writeInbound(Commands.newWatchScalableTopicsClose(1));
+ channel.writeInbound(Commands.newWatchScalableTopicsClose(1));
+ assertSessions("namespace", 0);
+ verify(resources, times(1)).deregisterNamespaceListener(any());
+ channel.writeInbound(Commands.newWatchScalableTopics(2, "public/default", null, null));
+ readResponse();
+ channel.close();
+ assertSessions("namespace", 0);
+ }
+
+ @Test
+ public void subscribeMeasuresFirstResponseNotRegistrationCompletion() {
+ var service = mock(ScalableTopicService.class);
+ when(brokerService.getScalableTopicService()).thenReturn(service);
+ var registration = new CompletableFuture<ConsumerAssignment>();
+ when(service.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenAnswer(invocation -> {
+ ServerCnx connection = invocation.getArgument(5);
+ connection.sendScalableConsumerAssignment(1,
+ ConsumerSession.toProto(new ConsumerAssignment(1, List.of())));
+ return registration;
+ });
+ connect();
+ channel.writeInbound(Commands.newScalableTopicSubscribe(1, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ assertThat(readResponse().getScalableTopicSubscribeResponse().hasError()).isFalse();
+ assertThat(registration).isNotDone();
+ assertRequestCount("subscribe", "success", 1);
+ cnx.sendScalableConsumerAssignment(1, ConsumerSession.toProto(new ConsumerAssignment(2, List.of())));
+ readResponse();
+ registration.completeExceptionally(new IllegalStateException("failure after response"));
+ channel.runPendingTasks();
+ assertRequestCount("subscribe", "success", 1);
+ assertRequestCount("subscribe", "failure", 0);
+ }
+
+ @Test
+ public void subscribeFailureAndUnsubscribeRetry() {
+ var service = mock(ScalableTopicService.class);
+ when(brokerService.getScalableTopicService()).thenReturn(service);
+ when(service.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.failedFuture(new IllegalStateException("failed")))
+ .thenReturn(CompletableFuture.completedFuture(new ConsumerAssignment(1, List.of())));
+ connect();
+ for (int i = 0; i < 2; i++) {
+ channel.writeInbound(Commands.newScalableTopicSubscribe(i, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ readResponse();
+ }
+ assertRequestCount("subscribe", "failure", 1);
+ assertRequestCount("subscribe", "success", 1);
+ when(service.unregisterConsumer(any(), anyString(), anyString(), anyLong()))
+ .thenReturn(CompletableFuture.failedFuture(new IllegalStateException("failed")))
+ .thenReturn(CompletableFuture.completedFuture(null));
+ for (int i = 0; i < 3; i++) {
+ channel.writeInbound(Commands.newScalableTopicUnsubscribe(10 + i, 1));
+ readResponse();
+ }
+ assertRequestCount("unsubscribe", "failure", 1);
+ assertRequestCount("unsubscribe", "success", 2);
+ }
+
+ @Test
+ public void successfulWriteKeepsItsOutcomeWhenDisconnectPrecedesListenerNotification() {
+ class DeferredWriteCnx extends ServerCnx {
+ private ChannelHandlerContext output;
+
+ DeferredWriteCnx() {
+ super(ScalableTopicRequestMetricsTest.this.context.getPulsarService());
+ }
+
+ @Override
+ public ChannelHandlerContext ctx() {
+ return output == null ? super.ctx() : output;
+ }
+ }
+ var service = mock(ScalableTopicService.class);
+ when(brokerService.getScalableTopicService()).thenReturn(service);
+ when(service.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.completedFuture(new ConsumerAssignment(1, List.of())));
+ var connection = new DeferredWriteCnx();
+ connect(connection);
+ Deque<Runnable> notifications = new ArrayDeque<>();
+ EventLoop notifier = mock(EventLoop.class);
+ doAnswer(invocation -> {
+ notifications.addLast(invocation.getArgument(0));
+ return null;
+ }).when(notifier).execute(any(Runnable.class));
+ Channel promiseChannel = mock(Channel.class);
+ when(promiseChannel.eventLoop()).thenReturn(notifier);
+ ChannelHandlerContext output = mock(ChannelHandlerContext.class);
+ when(output.channel()).thenReturn(channel);
+ when(output.voidPromise()).thenReturn(new VoidChannelPromise(promiseChannel, true));
+ doAnswer(invocation -> {
+ ByteBuf response = invocation.getArgument(0);
+ response.release();
+ ChannelPromise promise = invocation.getArgument(1);
+ promise.setSuccess();
+ return promise;
+ }).when(output).writeAndFlush(any(), any(ChannelPromise.class));
+ connection.output = output;
+ channel.writeInbound(Commands.newScalableTopicSubscribe(1, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ channel.runPendingTasks();
+ assertThat(notifications).as("the write succeeded but its listeners are queued").hasSize(1);
+ assertRequestCount("subscribe", "success", 0);
+ assertRequestCount("subscribe", "failure", 0);
+ channel.close();
+ assertRequestCount("subscribe", "failure", 0);
+ notifications.removeFirst().run();
+ assertRequestCount("subscribe", "success", 1);
+ assertRequestCount("subscribe", "failure", 0);
+ }
+
+ @Test
+ public void customSenderOverridesKeepOriginalDispatchWithoutInventedWriteMetrics() {
+ class CustomSenderCnx extends ServerCnx {
+ private PulsarCommandSender alternate;
+
+ CustomSenderCnx() {
+ super(ScalableTopicRequestMetricsTest.this.context.getPulsarService());
+ }
+
+ @Override
+ public PulsarCommandSender getCommandSender() {
+ return alternate == null ? super.getCommandSender() : alternate;
+ }
+ }
+ var service = mock(ScalableTopicService.class);
+ when(brokerService.getScalableTopicService()).thenReturn(service);
+ when(service.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.completedFuture(new ConsumerAssignment(1, List.of())));
+ var connection = new CustomSenderCnx();
+ connect(connection);
+ AtomicInteger responses = new AtomicInteger();
+ connection.alternate = new PulsarCommandSenderImpl(null, connection,
+ brokerService.getMaxTopicListInFlightLimiter()) {
+ @Override
+ public void sendScalableTopicSubscribeResponse(long requestId, ScalableConsumerAssignment assignment) {
+ assertThat(requestId).isEqualTo(1);
+ assertThat(assignment.getLayoutEpoch()).isEqualTo(1);
+ responses.incrementAndGet();
+ }
+ };
+ channel.writeInbound(Commands.newScalableTopicSubscribe(1, "topic://public/default/t", "sub", "c", 1,
+ ScalableConsumerType.STREAM));
+ channel.runPendingTasks();
+ assertThat(responses.get()).as("the old virtual sender override still receives the response").isEqualTo(1);
+ assertThat(channel.outboundMessages()).isEmpty();
+ assertRequestCount("subscribe", "success", 0);
+ assertRequestCount("subscribe", "failure", 0);
+ channel.close();
+ assertRequestCount("subscribe", "failure", 0);
+ }
+
+ private ScalableTopicResources spyScalableResources() {
+ var resources = spy(context.getPulsarService().getPulsarResources().getScalableTopicResources());
+ var pulsarResources = mock(PulsarResources.class);
+ when(pulsarResources.getScalableTopicResources()).thenReturn(resources);
+ doReturn(pulsarResources).when(context.getPulsarService()).getPulsarResources();
+ doAnswer(invocation -> {
+ dagSessions.add(invocation.getArgument(0));
+ return invocation.callRealMethod();
+ }).when(resources).registerPathListener(any());
+ doAnswer(invocation -> {
+ namespaceSessions.add(invocation.getArgument(0));
+ return invocation.callRealMethod();
+ }).when(resources).registerNamespaceListener(any());
+ return resources;
+ }
+
+ private void assertRequestCount(String type, String status, double expected) {
+ assertThat(sample("pulsar_scalable_topic_request_duration_seconds_count",
+ new String[]{"cluster", "request_type", "operation_status"}, new String[]{"test", type, status}))
+ .as("%s %s requests", type, status).isEqualTo(expected);
+ }
+
+ private void assertSessions(String type, double expected) {
+ assertThat(sample("pulsar_scalable_topic_watch_session_count",
+ new String[]{"cluster", "watch_type"}, new String[]{"test", type}))
+ .as("open %s watches", type).isEqualTo(expected);
+ }
+
+ private double sample(String name, String[] labels, String[] values) {
+ Double value = registry.getSampleValue(name, labels, values);
+ return value == null ? 0 : value;
+ }
+
+ private BaseCommand readResponse() {
+ await().until(() -> {
+ channel.runPendingTasks();
+ return !channel.outboundMessages().isEmpty();
+ });
+ ByteBuf frame = channel.readOutbound();
+ try {
+ frame.readInt();
+ int commandSize = frame.readInt();
+ var command = new BaseCommand();
+ command.parseFrom(frame, commandSize);
+ return command;
+ } finally {
+ frame.release();
+ }
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestWriteMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestWriteMetricsTest.java
new file mode 100644
index 000000000000..5e32b447f295
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ScalableTopicRequestWriteMetricsTest.java
@@ -0,0 +1,479 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+import io.opentelemetry.api.OpenTelemetry;
+import io.prometheus.client.CollectorRegistry;
+import java.io.IOException;
+import java.nio.channels.ClosedChannelException;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.intercept.BrokerInterceptor;
+import org.apache.pulsar.broker.service.scalable.ConsumerAssignment;
+import org.apache.pulsar.broker.service.scalable.ConsumerSession;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicService;
+import org.apache.pulsar.broker.testcontext.PulsarTestContext;
+import org.apache.pulsar.common.api.proto.BaseCommand;
+import org.apache.pulsar.common.api.proto.BaseCommand.Type;
+import org.apache.pulsar.common.api.proto.ScalableConsumerType;
+import org.apache.pulsar.common.api.proto.ServerError;
+import org.apache.pulsar.common.protocol.Commands;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+/** The request observation must follow the first response write, not command construction or registration. */
+@Test(groups = "broker", timeOut = 30000)
+public class ScalableTopicRequestWriteMetricsTest {
+ private static final String TOPIC = "topic://public/default/request-write-metrics";
+ private static final long CONSUMER_ID = 7;
+ private static final long REQUEST_ID = 42;
+
+ private PulsarTestContext context;
+ private ServiceConfiguration config;
+ private BrokerService broker;
+ private ScalableTopicService scalableService;
+ private ScalableTopicMetrics metrics;
+ private CollectorRegistry registry;
+ private EmbeddedChannel channel;
+ private ServerCnx cnx;
+ private ResponseWriteGate gate;
+ private final List<Type> interceptedTypes = new ArrayList<>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setup() throws Exception {
+ channel = null;
+ config = new ServiceConfiguration();
+ config.setClusterName("test");
+ config.setBrokerShutdownTimeoutMs(0L);
+ config.setLoadBalancerOverrideBrokerNicSpeedGbps(Optional.of(1.0));
+ config.setBacklogQuotaCheckEnabled(false);
+ context = PulsarTestContext.builderForNonStartableContext().config(config).spyByDefault().build();
+ broker = context.getBrokerService();
+ interceptedTypes.clear();
+ var interceptor = mock(BrokerInterceptor.class);
+ when(broker.getInterceptor()).thenReturn(interceptor);
+ doAnswer(invocation -> {
+ BaseCommand command = invocation.getArgument(0);
+ // Commands may be recycled immediately after interception; retain only the immutable type.
+ interceptedTypes.add(command.getType());
+ return null;
+ }).when(interceptor).onPulsarCommand(any(), any());
+ registry = new CollectorRegistry();
+ metrics = new ScalableTopicMetrics(OpenTelemetry.noop().getMeter("write-test"), "test", registry);
+ when(broker.getScalableTopicMetrics()).thenReturn(metrics);
+ scalableService = mock(ScalableTopicService.class);
+ when(broker.getScalableTopicService()).thenReturn(scalableService);
+ when(scalableService.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.completedFuture(assignment(1)));
+ gate = new ResponseWriteGate();
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void cleanup() throws Exception {
+ if (channel != null) {
+ gate.discardPending();
+ channel.finishAndReleaseAll();
+ }
+ if (metrics != null) {
+ metrics.close();
+ }
+ if (context != null) {
+ context.close();
+ }
+ }
+
+ @DataProvider
+ public Object[][] writeOutcomes() {
+ return new Object[][]{{true}, {false}};
+ }
+
+ @Test(dataProvider = "writeOutcomes")
+ public void coordinatorResponseWaitsForWriteWithoutChangingAssignmentOrder(boolean writeSucceeds) {
+ var registration = new CompletableFuture<ConsumerAssignment>();
+ when(scalableService.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenAnswer(invocation -> {
+ ServerCnx connection = invocation.getArgument(5);
+ connection.sendScalableConsumerAssignment(CONSUMER_ID, ConsumerSession.toProto(assignment(1)));
+ return registration;
+ });
+ connect();
+ gate.hold(Type.SCALABLE_TOPIC_SUBSCRIBE_RESPONSE, REQUEST_ID);
+ subscribe(REQUEST_ID);
+ waitForHeldResponse();
+ assertThat(registration).isNotDone();
+ assertUnobserved("subscribe");
+
+ // A rebalance while the subscribe write is pending must remain an update, not answer the request again.
+ cnx.sendScalableConsumerAssignment(CONSUMER_ID, ConsumerSession.toProto(assignment(2)));
+ channel.runPendingTasks();
+ assertThat(gate.commands()).extracting(BaseCommand::getType)
+ .containsExactly(Type.SCALABLE_TOPIC_SUBSCRIBE_RESPONSE, Type.SCALABLE_TOPIC_ASSIGNMENT_UPDATE);
+ assertUnobserved("subscribe");
+
+ completeResponseWrite(writeSucceeds);
+ assertOnlyOutcome("subscribe", writeSucceeds);
+ if (writeSucceeds) {
+ assertThat(readResponse().getScalableTopicSubscribeResponse().getAssignment().getLayoutEpoch())
+ .isEqualTo(1);
+ gate.succeedNext();
+ assertThat(readResponse().getScalableTopicAssignmentUpdate().getAssignment().getLayoutEpoch()).isEqualTo(2);
+ }
+ registration.completeExceptionally(new IllegalStateException("registration failed after its response"));
+ channel.runPendingTasks();
+ assertOnlyOutcome("subscribe", writeSucceeds);
+ if (writeSucceeds) {
+ assertThat(gate.commands()).isEmpty();
+ assertThat(channel.outboundMessages()).isEmpty();
+ }
+ }
+
+ @Test(dataProvider = "writeOutcomes")
+ public void fallbackSubscribeResponseWaitsForWrite(boolean writeSucceeds) {
+ var registration = new CompletableFuture<ConsumerAssignment>();
+ when(scalableService.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(registration);
+ connect();
+ gate.hold(Type.SCALABLE_TOPIC_SUBSCRIBE_RESPONSE, REQUEST_ID);
+ subscribe(REQUEST_ID);
+ channel.runPendingTasks();
+ assertThat(gate.commands()).isEmpty();
+ assertUnobserved("subscribe");
+
+ registration.complete(assignment(1));
+ waitForHeldResponse();
+ assertUnobserved("subscribe");
+ completeResponseWrite(writeSucceeds);
+ assertOnlyOutcome("subscribe", writeSucceeds);
+ if (writeSucceeds) {
+ assertThat(readResponse().getScalableTopicSubscribeResponse().hasError()).isFalse();
+ }
+ channel.runPendingTasks();
+ assertOnlyOutcome("subscribe", writeSucceeds);
+ }
+
+ @Test(dataProvider = "writeOutcomes")
+ public void unknownUnsubscribeResponseWaitsForWrite(boolean writeSucceeds) {
+ connect();
+ gate.hold(Type.SUCCESS, REQUEST_ID);
+ channel.writeInbound(Commands.newScalableTopicUnsubscribe(REQUEST_ID, CONSUMER_ID));
+ waitForHeldResponse();
+ assertUnobserved("unsubscribe");
+ completeResponseWrite(writeSucceeds);
+ assertOnlyOutcome("unsubscribe", writeSucceeds);
+ if (writeSucceeds) {
+ assertThat(readResponse().getSuccess().getRequestId()).isEqualTo(REQUEST_ID);
+ }
+ }
+
+ @DataProvider
+ public Object[][] unregisterAndWriteOutcomes() {
+ return new Object[][]{{true, true}, {true, false}, {false, true}, {false, false}};
+ }
+
+ @Test(dataProvider = "unregisterAndWriteOutcomes")
+ public void registeredUnsubscribeResponseWaitsForWrite(boolean unregisterSucceeds, boolean writeSucceeds) {
+ var unregistration = new CompletableFuture<Void>();
+ when(scalableService.unregisterConsumer(any(), anyString(), anyString(), anyLong()))
+ .thenReturn(unregistration);
+ connect();
+ subscribe(1);
+ assertThat(readResponse().getScalableTopicSubscribeResponse().hasError()).isFalse();
+ gate.hold(unregisterSucceeds ? Type.SUCCESS : Type.ERROR, REQUEST_ID);
+ channel.writeInbound(Commands.newScalableTopicUnsubscribe(REQUEST_ID, CONSUMER_ID));
+ channel.runPendingTasks();
+ assertThat(gate.commands()).isEmpty();
+ assertUnobserved("unsubscribe");
+
+ if (unregisterSucceeds) {
+ unregistration.complete(null);
+ } else {
+ unregistration.completeExceptionally(new IllegalStateException("unregister failed"));
+ }
+ waitForHeldResponse();
+ assertUnobserved("unsubscribe");
+ completeResponseWrite(writeSucceeds);
+ assertOnlyOutcome("unsubscribe", unregisterSucceeds && writeSucceeds);
+ verify(scalableService).unregisterConsumer(any(), anyString(), anyString(), anyLong());
+ if (writeSucceeds) {
+ BaseCommand response = readResponse();
+ assertThat(response.getType()).isEqualTo(unregisterSucceeds ? Type.SUCCESS : Type.ERROR);
+ if (!unregisterSucceeds) {
+ assertThat(response.getError().getError()).isEqualTo(ServerError.UnknownError);
+ }
+ }
+ }
+
+ @DataProvider
+ public Object[][] subscribeErrors() {
+ return new Object[][]{{"disabled", ServerError.NotAllowedError}, {"invalid", ServerError.InvalidTopicName},
+ {"unavailable", ServerError.ServiceNotReady}, {"registration", ServerError.UnknownError}};
+ }
+
+ @Test(dataProvider = "subscribeErrors")
+ public void subscribeErrorsWaitForTheirErrorResponseWrite(String error, ServerError expectedError) {
+ if (error.equals("disabled")) {
+ config.setScalableTopicsEnabled(false);
+ } else if (error.equals("unavailable")) {
+ when(broker.getScalableTopicService()).thenReturn(null);
+ } else if (error.equals("registration")) {
+ when(scalableService.registerConsumer(any(), anyString(), anyString(), anyLong(), any(), any()))
+ .thenReturn(CompletableFuture.failedFuture(new IllegalStateException("register failed")));
+ }
+ connect();
+ gate.hold(Type.SCALABLE_TOPIC_SUBSCRIBE_RESPONSE, REQUEST_ID);
+ channel.writeInbound(Commands.newScalableTopicSubscribe(REQUEST_ID,
+ error.equals("invalid") ? "bad-domain://public/default/topic" : TOPIC,
+ "subscription", "consumer", CONSUMER_ID, ScalableConsumerType.STREAM));
+ waitForHeldResponse();
+ assertThat(gate.commands().getFirst().getScalableTopicSubscribeResponse().getError()).isEqualTo(expectedError);
+ assertUnobserved("subscribe");
+ gate.succeedNext();
+ readResponse();
+ assertOnlyOutcome("subscribe", false);
+ }
+
+ @DataProvider
+ public Object[][] classicResponseTypes() {
+ return new Object[][]{{Type.SUCCESS}, {Type.ERROR}};
+ }
+
+ @Test(dataProvider = "classicResponseTypes")
+ public void untrackedClassicResponsesKeepVoidPromiseAndSingleInterception(Type type) {
+ connect();
+ gate.hold(type, REQUEST_ID);
+ if (type == Type.SUCCESS) {
+ cnx.getCommandSender().sendSuccessResponse(REQUEST_ID);
+ } else {
+ cnx.getCommandSender().sendErrorResponse(REQUEST_ID, ServerError.UnknownError, "classic error");
+ }
+ waitForHeldResponse();
+ assertThat(gate.pending.getFirst().promise().isVoid()).as("untracked writes retain the original void promise")
+ .isTrue();
+ assertThat(interceptedTypes).containsExactly(type);
+ assertUnobserved("subscribe");
+ assertUnobserved("unsubscribe");
+ gate.succeedNext();
+ assertThat(readResponse().getType()).isEqualTo(type);
+ assertThat(channel.isActive()).isTrue();
+ assertThat(interceptedTypes).as("completion must not intercept the same command a second time")
+ .containsExactly(type);
+ assertUnobserved("subscribe");
+ assertUnobserved("unsubscribe");
+ }
+
+ @Test
+ public void disabledUnsubscribeErrorWaitsForWriteWithoutAddingInterception() {
+ config.setScalableTopicsEnabled(false);
+ connect();
+ gate.hold(Type.ERROR, REQUEST_ID);
+ channel.writeInbound(Commands.newScalableTopicUnsubscribe(REQUEST_ID, CONSUMER_ID));
+ waitForHeldResponse();
+ assertThat(gate.commands().getFirst().getError().getError()).isEqualTo(ServerError.NotAllowedError);
+ assertThat(interceptedTypes).as("disabled unsubscribe retains its original direct-write path").isEmpty();
+ assertUnobserved("unsubscribe");
+ gate.succeedNext();
+ assertThat(readResponse().getError().getError()).isEqualTo(ServerError.NotAllowedError);
+ assertOnlyOutcome("unsubscribe", false);
+ assertThat(channel.isActive()).isTrue();
+ assertThat(interceptedTypes).isEmpty();
+ }
+
+ private void connect() {
+ cnx = new ServerCnx(context.getPulsarService());
+ channel = new EmbeddedChannel(gate,
+ new LengthFieldBasedFrameDecoder(5 * 1024 * 1024, 0, 4, 0, 4), cnx);
+ channel.writeInbound(Commands.newConnect("none", "", null));
+ assertThat(readResponse().getType()).isEqualTo(Type.CONNECTED);
+ interceptedTypes.clear();
+ }
+
+ private void subscribe(long requestId) {
+ channel.writeInbound(Commands.newScalableTopicSubscribe(requestId, TOPIC, "subscription", "consumer",
+ CONSUMER_ID, ScalableConsumerType.STREAM));
+ }
+
+ private static ConsumerAssignment assignment(long epoch) {
+ return new ConsumerAssignment(epoch, List.of());
+ }
+
+ private void waitForHeldResponse() {
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ channel.runPendingTasks();
+ return !gate.commands().isEmpty();
+ });
+ assertThat(channel.outboundMessages()).as("response has not reached the outbound transport").isEmpty();
+ }
+
+ private void completeResponseWrite(boolean success) {
+ if (success) {
+ gate.succeedNext();
+ } else {
+ var failure = new IOException("injected response write failure");
+ gate.failNext(failure);
+ channel.runPendingTasks();
+ assertThat(gate.failures).as("the original void-promise failure still reaches the pipeline")
+ .containsExactly(failure);
+ assertThat(channel.isActive()).as("retain the original transport failure behavior").isFalse();
+ }
+ channel.runPendingTasks();
+ }
+
+ private void assertUnobserved(String type) {
+ assertThat(count(type, "success")).as("%s success before response completion", type).isZero();
+ assertThat(count(type, "failure")).as("%s failure before response completion", type).isZero();
+ }
+
+ private void assertOnlyOutcome(String type, boolean success) {
+ assertThat(count(type, "success")).isEqualTo(success ? 1 : 0);
+ assertThat(count(type, "failure")).isEqualTo(success ? 0 : 1);
+ }
+
+ private double count(String type, String status) {
+ Double result = registry.getSampleValue("pulsar_scalable_topic_request_duration_seconds_count",
+ new String[]{"cluster", "request_type", "operation_status"}, new String[]{"test", type, status});
+ return result == null ? 0 : result;
+ }
+
+ private BaseCommand readResponse() {
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ channel.runPendingTasks();
+ return !channel.outboundMessages().isEmpty();
+ });
+ ByteBuf frame = channel.readOutbound();
+ try {
+ return decode(frame);
+ } finally {
+ frame.release();
+ }
+ }
+
+ private static BaseCommand decode(ByteBuf frame) {
+ // A non-retained duplicate has independent indices; decoding must not consume or release the held frame.
+ ByteBuf copy = frame.duplicate();
+ copy.readInt();
+ int commandSize = copy.readInt();
+ BaseCommand command = new BaseCommand();
+ command.parseFrom(copy, commandSize);
+ return new BaseCommand().copyFrom(command);
+ }
+
+ private record PendingWrite(ByteBuf frame, ChannelPromise promise, BaseCommand command) {}
+
+ private static final class ResponseWriteGate extends ChannelDuplexHandler {
+ private final Deque<PendingWrite> pending = new ArrayDeque<>();
+ private final List<Throwable> failures = new ArrayList<>();
+ private ChannelHandlerContext ctx;
+ private Type heldType;
+ private long heldRequestId;
+
+ @Override
+ public void handlerAdded(ChannelHandlerContext context) {
+ ctx = context;
+ }
+
+ private void hold(Type type, long requestId) {
+ heldType = type;
+ heldRequestId = requestId;
+ }
+
+ @Override
+ public void write(ChannelHandlerContext context, Object message, ChannelPromise promise) {
+ if (message instanceof ByteBuf frame) {
+ BaseCommand command = decode(frame);
+ if (!pending.isEmpty() || matches(command)) {
+ pending.addLast(new PendingWrite(frame, promise, command));
+ heldType = null;
+ return;
+ }
+ }
+ context.write(message, promise);
+ }
+
+ @Override
+ public void flush(ChannelHandlerContext context) {
+ if (pending.isEmpty()) {
+ context.flush();
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
+ failures.add(cause);
+ context.fireExceptionCaught(cause);
+ }
+
+ private boolean matches(BaseCommand command) {
+ if (command.getType() != heldType) {
+ return false;
+ }
+ return switch (command.getType()) {
+ case SCALABLE_TOPIC_SUBSCRIBE_RESPONSE ->
+ command.getScalableTopicSubscribeResponse().getRequestId() == heldRequestId;
+ case SUCCESS -> command.getSuccess().getRequestId() == heldRequestId;
+ case ERROR -> command.getError().getRequestId() == heldRequestId;
+ default -> false;
+ };
+ }
+
+ private List<BaseCommand> commands() {
+ return pending.stream().map(PendingWrite::command).toList();
+ }
+
+ private void succeedNext() {
+ PendingWrite write = pending.removeFirst();
+ ctx.writeAndFlush(write.frame(), write.promise());
+ }
+
+ private void failNext(Throwable cause) {
+ PendingWrite write = pending.removeFirst();
+ write.frame().release();
+ write.promise().tryFailure(cause);
+ }
+
+ private void discardPending() {
+ while (!pending.isEmpty()) {
+ failNext(new ClosedChannelException());
+ }
+ }
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionLookupCompatibilityTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionLookupCompatibilityTest.java
new file mode 100644
index 000000000000..87210cea2775
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionLookupCompatibilityTest.java
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.DefaultChannelPromise;
+import io.netty.util.concurrent.ImmediateEventExecutor;
+import io.opentelemetry.sdk.metrics.SdkMeterProvider;
+import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
+import io.prometheus.client.CollectorRegistry;
+import java.util.ArrayDeque;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.lookup.LookupResult;
+import org.apache.pulsar.broker.namespace.NamespaceService;
+import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
+import org.apache.pulsar.broker.service.BrokerService;
+import org.apache.pulsar.broker.service.ServerCnx;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.scalable.HashRange;
+import org.apache.pulsar.common.scalable.SegmentInfo;
+import org.apache.pulsar.common.scalable.SegmentTopicName;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.testng.annotations.Test;
+
+/** New observability must not change the internal classic lookups that feed existing broker metrics. */
+@Test(groups = "broker")
+public class DagWatchSessionLookupCompatibilityTest {
+ private static final TopicName TOPIC = TopicName.get("topic://tenant/ns/topic");
+ private static final String PATH = "/topics/tenant/ns/topic";
+ private static final HashRange LEFT = HashRange.of(0, 0x7fff);
+ private static final HashRange RIGHT = HashRange.of(0x8000, 0xffff);
+ private static final ScalableTopicMetadata METADATA = ScalableTopicMetadata.builder()
+ .epoch(1).nextSegmentId(3).segments(Map.of(
+ 0L, SegmentInfo.active(0, HashRange.of(0, 0xffff), 0, 1).sealed(1, 2, List.of(1L, 2L)),
+ 1L, SegmentInfo.active(1, LEFT, List.of(0L), 1, 2),
+ 2L, SegmentInfo.active(2, RIGHT, List.of(0L), 1, 2))).build();
+
+ @Test
+ public void collectionAndStoppingMetricsDoNotAddOrSuppressClassicLookups() throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ fixture.session.pushInitialResponse(fixture.session.start().get(10, TimeUnit.SECONDS));
+ fixture.writes.remove().setSuccess();
+ fixture.assertBuilds(1);
+ fixture.collect();
+ fixture.session.stopMetricsTracking();
+ fixture.collect();
+ fixture.assertBuilds(1);
+ verify(fixture.resources, never()).deregisterPathListener(any());
+
+ fixture.notifyChange();
+ fixture.writes.remove().setSuccess();
+ fixture.collect();
+ fixture.assertBuilds(2);
+ verify(fixture.ctx, times(2)).writeAndFlush(any());
+ verify(fixture.resources, times(2)).getScalableTopicMetadataAsync(TOPIC, true);
+ }
+ }
+
+ @Test
+ public void failedInitialWriteDoesNotStopOriginalNotificationWorkload() throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ fixture.session.pushInitialResponse(fixture.session.start().get(10, TimeUnit.SECONDS));
+ fixture.writes.remove().setFailure(new IllegalStateException("write failed"));
+ fixture.assertBuilds(1);
+ verify(fixture.resources, never()).deregisterPathListener(any());
+
+ fixture.notifyChange();
+ fixture.writes.remove().setSuccess();
+ fixture.assertBuilds(2);
+ verify(fixture.ctx, times(2)).writeAndFlush(any());
+ verify(fixture.resources, never()).deregisterPathListener(any());
+ }
+ }
+
+ @Test
+ public void asynchronousLookupFailureDoesNotRetryOrSuppressLaterUpdates() {
+ try (Fixture fixture = new Fixture()) {
+ when(fixture.namespace.getBrokerServiceUrlAsync(eq(SegmentTopicName.fromParent(TOPIC, LEFT, 1)), any()))
+ .thenReturn(CompletableFuture.failedFuture(new IllegalStateException("lookup failed")));
+ fixture.notifyChange();
+ fixture.assertBuilds(1);
+ assertThat(fixture.writes).isEmpty();
+ fixture.collect();
+ fixture.assertBuilds(1);
+ verify(fixture.resources, never()).deregisterPathListener(any());
+
+ when(fixture.namespace.getBrokerServiceUrlAsync(eq(SegmentTopicName.fromParent(TOPIC, LEFT, 1)), any()))
+ .thenReturn(CompletableFuture.completedFuture(Optional.of(fixture.lookup)));
+ fixture.notifyChange();
+ fixture.writes.remove().setSuccess();
+ fixture.assertBuilds(2);
+ verify(fixture.ctx).writeAndFlush(any());
+ verify(fixture.resources, never()).deregisterPathListener(any());
+ }
+ }
+
+ @Test
+ public void synchronousBuildFailureStillEscapesWithoutAdditionalWork() {
+ try (Fixture fixture = new Fixture()) {
+ var failure = new IllegalStateException("synchronous lookup failure");
+ when(fixture.namespace.getBrokerServiceUrlAsync(any(), any())).thenThrow(failure);
+ assertThatThrownBy(() -> fixture.session.onMetadataChanged(METADATA)).isSameAs(failure);
+ verify(fixture.namespace).getBrokerServiceUrlAsync(any(), any());
+ verify(fixture.store, never()).get(any());
+ verify(fixture.ctx, never()).writeAndFlush(any());
+ verify(fixture.resources, never()).deregisterPathListener(any());
+ fixture.collect();
+ verify(fixture.namespace).getBrokerServiceUrlAsync(any(), any());
+ }
+ }
+
+ private static final class Fixture implements AutoCloseable {
+ private final NamespaceService namespace = mock(NamespaceService.class);
+ private final ScalableTopicResources resources = mock(ScalableTopicResources.class);
+ private final MetadataStore store = mock(MetadataStore.class);
+ private final ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
+ private final Queue<ChannelPromise> writes = new ArrayDeque<>();
+ private final CollectorRegistry registry = new CollectorRegistry();
+ private final InMemoryMetricReader reader = InMemoryMetricReader.create();
+ private final SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build();
+ private final ScalableTopicMetrics metrics = new ScalableTopicMetrics(provider.get("test"), "test", registry);
+ private final LookupResult lookup = LookupResult.builder().type(LookupResult.Type.BrokerUrl)
+ .brokerServiceUrl("pulsar://broker:6650").build();
+ private final DagWatchSession session;
+
+ private Fixture() {
+ PulsarService pulsar = mock(PulsarService.class);
+ BrokerService broker = mock(BrokerService.class);
+ ServerCnx cnx = mock(ServerCnx.class);
+ when(broker.getPulsar()).thenReturn(pulsar);
+ when(pulsar.getNamespaceService()).thenReturn(namespace);
+ when(broker.getScalableTopicMetrics()).thenReturn(metrics);
+ when(cnx.ctx()).thenReturn(ctx);
+ when(resources.topicPath(TOPIC)).thenReturn(PATH);
+ when(resources.controllerLockPath(TOPIC)).thenReturn(PATH + "/controller");
+ when(resources.getStore()).thenReturn(store);
+ when(resources.getScalableTopicMetadataAsync(TOPIC, true))
+ .thenReturn(CompletableFuture.completedFuture(Optional.of(METADATA)));
+ when(store.get(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
+ when(namespace.getBrokerServiceUrlAsync(any(), any()))
+ .thenReturn(CompletableFuture.completedFuture(Optional.of(lookup)));
+ when(ctx.writeAndFlush(any())).thenAnswer(invocation -> {
+ ByteBuf command = invocation.getArgument(0);
+ command.release();
+ ChannelPromise write = new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE);
+ writes.add(write);
+ return write;
+ });
+ session = new DagWatchSession(1, TOPIC, cnx, resources, broker, false,
+ metrics.startRequest(ScalableTopicMetrics.RequestType.LOOKUP));
+ }
+
+ private void notifyChange() {
+ session.onNotification(new Notification(NotificationType.Modified, PATH));
+ }
+
+ private void collect() {
+ assertThat(Collections.list(registry.metricFamilySamples())).isNotEmpty();
+ assertThat(reader.collectAllMetrics()).isNotEmpty();
+ }
+
+ private void assertBuilds(int count) {
+ // This is the existing NamespaceService entrypoint that measures classic lookup metrics.
+ verify(namespace, times(count * 2)).getBrokerServiceUrlAsync(any(), any());
+ verify(namespace, times(count)).getBrokerServiceUrlAsync(eq(SegmentTopicName.fromParent(TOPIC, LEFT, 1)),
+ any());
+ verify(namespace, times(count)).getBrokerServiceUrlAsync(eq(SegmentTopicName.fromParent(TOPIC, RIGHT, 2)),
+ any());
+ verify(namespace, never()).getBrokerServiceUrlAsync(
+ eq(SegmentTopicName.fromParent(TOPIC, HashRange.of(0, 0xffff), 0)), any());
+ verify(store, times(count)).get(PATH + "/controller");
+ }
+
+ @Override
+ public void close() {
+ session.close();
+ writes.forEach(write -> write.tryFailure(new IllegalStateException("test finished")));
+ metrics.close();
+ provider.close();
+ }
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionMetricsTest.java
new file mode 100644
index 000000000000..1a6eadd753c0
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionMetricsTest.java
@@ -0,0 +1,359 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.DefaultChannelPromise;
+import io.netty.util.concurrent.ImmediateEventExecutor;
+import java.util.ArrayDeque;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
+import org.apache.pulsar.broker.service.BrokerService;
+import org.apache.pulsar.broker.service.ServerCnx;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.GetResult;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class DagWatchSessionMetricsTest {
+ private static final TopicName TOPIC = TopicName.get("topic://tenant/ns/topic");
+ private static final ScalableTopicLayoutResponse RESPONSE =
+ new ScalableTopicLayoutResponse(1L, Map.of(), null, null, null, null);
+
+ private ScalableTopicResources resources;
+ private ScalableTopicMetrics metrics;
+ private ScalableTopicMetrics.Request request;
+ private ChannelHandlerContext ctx;
+ private MetadataStore store;
+ private DagWatchSession session;
+ private CompletableFuture<Optional<ScalableTopicMetadata>> initialRead;
+ private final Queue<ChannelPromise> writes = new ArrayDeque<>();
+
+ @BeforeMethod
+ public void setUp() {
+ writes.clear();
+ resources = mock(ScalableTopicResources.class);
+ metrics = mock(ScalableTopicMetrics.class);
+ request = mock(ScalableTopicMetrics.Request.class);
+ ctx = mock(ChannelHandlerContext.class);
+ store = mock(MetadataStore.class);
+ BrokerService brokerService = mock(BrokerService.class);
+ ServerCnx cnx = mock(ServerCnx.class);
+ when(brokerService.getScalableTopicMetrics()).thenReturn(metrics);
+ when(cnx.ctx()).thenReturn(ctx);
+ when(resources.topicPath(TOPIC)).thenReturn("/topics/tenant/ns/topic");
+ when(resources.controllerLockPath(TOPIC)).thenReturn("/topics/tenant/ns/topic/controller");
+ when(resources.getStore()).thenReturn(store);
+ when(store.get(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
+ initialRead = new CompletableFuture<>();
+ when(resources.getScalableTopicMetadataAsync(TOPIC, true)).thenReturn(initialRead);
+ when(ctx.writeAndFlush(any())).thenAnswer(invocation -> {
+ ByteBuf frame = invocation.getArgument(0);
+ frame.release();
+ ChannelPromise promise = new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE);
+ writes.add(promise);
+ return promise;
+ });
+ session = new DagWatchSession(1L, TOPIC, cnx, resources, brokerService, false, request);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() {
+ session.close();
+ writes.forEach(promise -> promise.tryFailure(new IllegalStateException("Test finished")));
+ }
+
+ @Test
+ public void initializationIsCountedAndConcurrentCloseCountsOnce() throws Exception {
+ verify(metrics).sessionOpened(ScalableTopicMetrics.WatchType.TOPIC);
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ assertThat(started).as("initial metadata is still in flight").isNotDone();
+ verify(metrics, never()).sessionClosed(any());
+
+ CompletableFuture.allOf(CompletableFuture.runAsync(session::close),
+ CompletableFuture.runAsync(session::close)).get(10, TimeUnit.SECONDS);
+ initialRead.complete(Optional.of(ScalableTopicMetadata.builder().build()));
+ session.pushInitialResponse(started.get(10, TimeUnit.SECONDS));
+
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(resources, times(2)).deregisterPathListener(session);
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(ctx, never()).writeAndFlush(any());
+ }
+
+ @Test
+ public void closeBeforeStartRetainsOriginalRegistrationBehavior() {
+ session.close();
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ initialRead.complete(Optional.of(ScalableTopicMetadata.builder().build()));
+ assertThat(started).isCompleted();
+ verify(resources).registerPathListener(session);
+ verify(resources).deregisterPathListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(request).failure();
+ }
+
+ @Test
+ public void closeRacingRegistrationRetainsOriginalLateListenerBehavior() {
+ Set<ScalableTopicResources.MetadataPathListener> listeners = new HashSet<>();
+ doAnswer(invocation -> {
+ session.close(); // The close wins before the registration becomes visible.
+ listeners.add(session);
+ return null;
+ }).when(resources).registerPathListener(session);
+ doAnswer(invocation -> {
+ listeners.remove(session);
+ return null;
+ }).when(resources).deregisterPathListener(session);
+
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ assertThat(started).isNotDone();
+ assertThat(listeners).as("metrics must not repair the pre-existing late-registration leak")
+ .containsExactly(session);
+ verify(resources).deregisterPathListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(request).failure();
+ }
+
+ @Test
+ public void failedStartDoesNotCloseSessionOrCompleteRequest() {
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ initialRead.completeExceptionally(new IllegalStateException("Metadata unavailable"));
+ assertThat(started).isCompletedExceptionally();
+ verify(resources, never()).deregisterPathListener(any());
+ verify(metrics, never()).sessionClosed(any());
+ verifyNoInteractions(request);
+ session.close();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(resources).deregisterPathListener(session);
+ verify(request).failure();
+ verify(metrics, never()).recordWatchUpdate(true);
+ verify(metrics, never()).recordWatchUpdate(false);
+ }
+
+ @Test
+ public void initialRequestWaitsForWriteAndSnapshotIsNotAnUpdate() {
+ session.pushInitialResponse(RESPONSE);
+ verifyNoInteractions(request);
+ verify(metrics, never()).recordWatchUpdate(true);
+ verify(metrics, never()).recordWatchUpdate(false);
+
+ writes.remove().setSuccess();
+ session.close();
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(metrics, never()).recordWatchUpdate(true);
+ verify(metrics, never()).recordWatchUpdate(false);
+ }
+
+ @Test
+ public void failedInitialWriteFailsRequestWithoutClosingSession() {
+ session.pushInitialResponse(RESPONSE);
+ writes.remove().setFailure(new IllegalStateException("Write failed"));
+ verify(resources, never()).deregisterPathListener(any());
+ verify(metrics, never()).sessionClosed(any());
+ session.pushUpdate(RESPONSE);
+ writes.remove().setSuccess();
+ verify(ctx, times(2)).writeAndFlush(any());
+ session.close();
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(metrics, never()).recordWatchUpdate(false);
+ }
+
+ @Test
+ public void closeBeforeInitialWriteCompletesDoesNotCompleteRequestTwice() {
+ session.pushInitialResponse(RESPONSE);
+ session.close();
+ writes.remove().setSuccess();
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ }
+
+ @Test
+ public void eachSubsequentWriteRecordsItsCompletionStatus() {
+ session.pushInitialResponse(RESPONSE);
+ writes.remove().setSuccess();
+ session.pushUpdate(RESPONSE);
+ session.pushUpdate(RESPONSE);
+ verify(metrics, never()).recordWatchUpdate(true);
+ verify(metrics, never()).recordWatchUpdate(false);
+
+ writes.remove().setSuccess();
+ writes.remove().setFailure(new IllegalStateException("Write failed"));
+ verify(metrics).recordWatchUpdate(true);
+ verify(metrics).recordWatchUpdate(false);
+ verify(request).success();
+ session.close();
+ session.pushUpdate(RESPONSE);
+ verify(ctx, times(3)).writeAndFlush(any());
+ }
+
+ @Test
+ public void notificationOvertakingInitialReadCompletesFirstResponseRequest() {
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ session.onMetadataChanged(ScalableTopicMetadata.builder().build());
+ verifyNoInteractions(request);
+ writes.remove().setSuccess();
+ verify(request).success();
+ verify(metrics, never()).recordWatchUpdate(true);
+
+ initialRead.complete(Optional.of(ScalableTopicMetadata.builder().build()));
+ session.pushInitialResponse(started.getNow(null));
+ writes.remove().setSuccess();
+ verify(request).success();
+ verify(metrics, never()).recordWatchUpdate(true);
+
+ session.pushUpdate(RESPONSE);
+ writes.remove().setSuccess();
+ verify(metrics).recordWatchUpdate(true);
+ }
+
+ @Test
+ public void failedNotificationReadCountsAsFailedUpdate() {
+ session.onNotification(new Notification(NotificationType.Modified, "/topics/tenant/ns/topic"));
+ initialRead.completeExceptionally(new IllegalStateException("Metadata read failed"));
+ verify(metrics).recordWatchUpdate(false);
+ verify(ctx, never()).writeAndFlush(any());
+ verifyNoInteractions(request);
+ }
+
+ @Test
+ public void asynchronousLayoutBuildFailureCountsAsFailedUpdate() {
+ CompletableFuture<Optional<GetResult>> controllerRead =
+ new CompletableFuture<>();
+ when(store.get(any())).thenReturn(controllerRead);
+ session.onMetadataChanged(ScalableTopicMetadata.builder().build());
+ verify(metrics, never()).recordWatchUpdate(false);
+ controllerRead.completeExceptionally(new IllegalStateException("Controller read failed"));
+ verify(metrics).recordWatchUpdate(false);
+ verify(ctx, never()).writeAndFlush(any());
+ verifyNoInteractions(request);
+ }
+
+ @Test
+ public void synchronousLayoutBuildFailureCountsAsFailedUpdate() {
+ ScalableTopicMetadata invalid = mock(ScalableTopicMetadata.class);
+ when(invalid.getSegments()).thenThrow(new IllegalStateException("Invalid layout"));
+ assertThatThrownBy(() -> session.onMetadataChanged(invalid))
+ .isInstanceOf(IllegalStateException.class).hasMessage("Invalid layout");
+ verify(metrics).recordWatchUpdate(false);
+ verify(ctx, never()).writeAndFlush(any());
+ }
+
+ @Test
+ public void metricOnlyStopDoesNotCloseSessionOrStopItsWork() {
+ session.stopMetricsTracking();
+ session.stopMetricsTracking();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ verify(resources, never()).deregisterPathListener(any());
+ verifyNoInteractions(request);
+
+ CompletableFuture<ScalableTopicLayoutResponse> started = session.start();
+ initialRead.complete(Optional.of(ScalableTopicMetadata.builder().build()));
+ session.pushInitialResponse(started.getNow(null));
+ writes.remove().setSuccess();
+ session.onMetadataChanged(ScalableTopicMetadata.builder().build());
+ writes.remove().setSuccess();
+ session.onNotification(new Notification(NotificationType.Modified, "/topics/tenant/ns/topic"));
+ writes.remove().setSuccess();
+ verify(ctx, times(3)).writeAndFlush(any());
+ verify(store, times(3)).get(any());
+ verify(resources, times(2)).getScalableTopicMetadataAsync(TOPIC, true);
+ verify(resources, never()).deregisterPathListener(any());
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(metrics, never()).recordWatchUpdate(true);
+ verify(metrics, never()).recordWatchUpdate(false);
+
+ session.close();
+ session.close();
+ verify(resources, times(2)).deregisterPathListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.TOPIC);
+ }
+
+ @Test
+ public void synchronousStartFailurePropagatesWithoutLifecycleChanges() {
+ IllegalStateException failure = new IllegalStateException("Registration failed");
+ doThrow(failure).when(resources).registerPathListener(session);
+ assertThatThrownBy(session::start).isSameAs(failure);
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterPathListener(any());
+ verifyNoInteractions(request);
+ }
+
+ @Test
+ public void synchronousNotificationReadFailurePropagatesAfterRecording() {
+ IllegalStateException failure = new IllegalStateException("Read failed");
+ when(resources.getScalableTopicMetadataAsync(TOPIC, true)).thenThrow(failure);
+ assertThatThrownBy(() -> session.onNotification(
+ new Notification(NotificationType.Modified, "/topics/tenant/ns/topic"))).isSameAs(failure);
+ verify(metrics).recordWatchUpdate(false);
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterPathListener(any());
+ verifyNoInteractions(request);
+ }
+
+ @Test
+ public void synchronousPushFailurePropagatesWithoutClosingSession() {
+ IllegalStateException failure = new IllegalStateException("Write failed");
+ doAnswer(invocation -> {
+ ByteBuf frame = invocation.getArgument(0);
+ frame.release();
+ throw failure;
+ }).when(ctx).writeAndFlush(any());
+ assertThatThrownBy(() -> session.pushInitialResponse(RESPONSE)).isSameAs(failure);
+ verify(request).failure();
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterPathListener(any());
+ assertThatThrownBy(() -> session.pushUpdate(RESPONSE)).isSameAs(failure);
+ verify(ctx, times(2)).writeAndFlush(any());
+ verify(metrics).recordWatchUpdate(false);
+ }
+
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionTest.java
index f513f7ae45dd..4e0dec4185e2 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/DagWatchSessionTest.java
@@ -30,7 +30,10 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.DefaultChannelPromise;
+import io.netty.util.concurrent.ImmediateEventExecutor;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -82,6 +85,8 @@ public class DagWatchSessionTest {
when(resources.topicPath(TOPIC)).thenReturn(TOPIC_PATH);
when(cnx.ctx()).thenReturn(ctx);
+ when(ctx.writeAndFlush(any())).thenReturn(
+ new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE).setSuccess());
// Default: metadata store has a valid registerListener hook.
var store = mock(org.apache.pulsar.metadata.api.MetadataStore.class);
when(resources.getStore()).thenReturn(store);
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsIsolationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsIsolationTest.java
new file mode 100644
index 000000000000..9145c98600da
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsIsolationTest.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.opentelemetry.api.common.Attributes;
+import io.opentelemetry.api.metrics.Meter;
+import io.opentelemetry.api.metrics.ObservableLongCounter;
+import io.opentelemetry.api.metrics.ObservableLongUpDownCounter;
+import io.opentelemetry.sdk.metrics.SdkMeterProvider;
+import io.opentelemetry.sdk.metrics.data.MetricData;
+import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
+import io.prometheus.client.CollectorRegistry;
+import io.prometheus.client.Counter;
+import io.prometheus.client.Gauge;
+import io.prometheus.client.Histogram;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.pulsar.broker.stats.OpenTelemetryMessageFinderStats;
+import org.apache.pulsar.broker.stats.OpenTelemetryMessageFinderStats.EntryStorage;
+import org.apache.pulsar.broker.stats.OpenTelemetryMessageFinderStats.FindReason;
+import org.apache.pulsar.broker.stats.OpenTelemetryMessageFinderStats.FindResult;
+import org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsGeneratorUtils;
+import org.apache.pulsar.common.util.SimpleTextOutputStream;
+import org.testng.annotations.Test;
+
+/** Compatibility checks for unrelated metrics sharing the registry and meter with scalable-topic metrics. */
+@Test(groups = "broker")
+public class ScalableTopicMetricsIsolationTest {
+ private static final String CLUSTER = "isolation-cluster";
+ private static final String PROM_SESSION = "pulsar_scalable_topic_watch_session_count";
+ private static final String OLD_CALLBACK = "pulsar.broker.non.recoverable.entries.skipped.count";
+ private static final String OLD_LOOKUPS = "pulsar.broker.request.topic.lookup.concurrent.usage";
+
+ @Test
+ public void existingMetricsSurviveCreateUpdateCollectCloseAndRestart() {
+ try (ExistingMetrics existing = new ExistingMetrics(new CollectorRegistry(), "")) {
+ List<MetricSnapshot> before = existing.snapshot();
+ try (ScalableTopicMetrics metrics = new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry)) {
+ existing.assertUnchanged(before);
+ exercise(metrics);
+ existing.assertUnchanged(before);
+ existing.assertUnchanged(before); // Repeated collection must not change unrelated instruments.
+ ScalableTopicMetrics.Request pending = metrics.startRequest(ScalableTopicMetrics.RequestType.SUBSCRIBE);
+ metrics.close();
+ metrics.close();
+ pending.failure();
+ exercise(metrics); // Late completions after close cannot affect existing metrics either.
+ existing.assertUnchanged(before);
+ }
+ try (ScalableTopicMetrics restarted =
+ new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry)) {
+ exercise(restarted);
+ existing.assertUnchanged(before);
+ }
+ existing.assertUnchanged(before);
+ existing.assertStillUpdates(before);
+ }
+ }
+
+ @Test
+ public void closingOneOfSeveralBrokersDoesNotDisposeExistingInstruments() {
+ try (ExistingMetrics existing = new ExistingMetrics(new CollectorRegistry(), "");
+ ScalableTopicMetrics first = new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry);
+ ScalableTopicMetrics second = new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry)) {
+ List<MetricSnapshot> before = existing.snapshot();
+ exercise(first);
+ exercise(second);
+ existing.assertUnchanged(before);
+ assertThat(existing.registry.getSampleValue(PROM_SESSION,
+ new String[]{"cluster", "watch_type"}, new String[]{CLUSTER, "topic"})).isEqualTo(2);
+ first.close();
+ existing.assertUnchanged(before);
+ assertThat(existing.registry.getSampleValue(PROM_SESSION,
+ new String[]{"cluster", "watch_type"}, new String[]{CLUSTER, "topic"})).isEqualTo(1);
+ second.recordWatchUpdate(false);
+ second.close();
+ existing.assertUnchanged(before);
+ existing.assertStillUpdates(before);
+ }
+ }
+
+ @Test
+ public void failedRegistrationDoesNotUnregisterExistingCollectorsOrCallbacks() {
+ try (ExistingMetrics existing = new ExistingMetrics(new CollectorRegistry(), "")) {
+ Gauge conflict = Gauge.build(PROM_SESSION, "Pre-existing conflicting collector")
+ .register(existing.registry);
+ conflict.set(17);
+ try {
+ List<MetricSnapshot> before = existing.snapshot();
+ List<MetricSnapshot> conflictBefore = prometheusSnapshot(existing.registry, Set.of(PROM_SESSION));
+ assertThatThrownBy(() -> new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry))
+ .isInstanceOf(IllegalArgumentException.class);
+ existing.assertUnchanged(before);
+ assertThat(prometheusSnapshot(existing.registry, Set.of(PROM_SESSION))).isEqualTo(conflictBefore);
+ assertThat(existing.reader.collectAllMetrics()).extracting(MetricData::getName)
+ .doesNotContain(ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME,
+ ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME);
+ } finally {
+ existing.registry.unregister(conflict);
+ }
+ List<MetricSnapshot> beforeRetry = existing.snapshot();
+ try (ScalableTopicMetrics retry = new ScalableTopicMetrics(existing.meter, CLUSTER, existing.registry)) {
+ exercise(retry);
+ existing.assertUnchanged(beforeRetry);
+ }
+ existing.assertUnchanged(beforeRetry);
+ existing.assertStillUpdates(beforeRetry);
+ }
+ }
+
+ @Test
+ public void defaultRegistryRendererPreservesExistingSamplesAndAddsClusterOnlyOnce() {
+ // DefaultRegistry may already contain real broker collectors. Use exclusively owned, uniquely suffixed
+ // replicas here; the isolated-registry tests above use the unmodified existing production names.
+ String suffix = "_isolation_" + UUID.randomUUID().toString().replace("-", "");
+ String cluster = "isolation-" + UUID.randomUUID();
+ try (ExistingMetrics existing = new ExistingMetrics(CollectorRegistry.defaultRegistry, suffix)) {
+ List<String> before = existingRenderedLines(existing, cluster);
+ try (ScalableTopicMetrics metrics = new ScalableTopicMetrics(existing.meter, cluster)) {
+ exercise(metrics);
+ assertThat(existingRenderedLines(existing, cluster)).isEqualTo(before);
+ List<String> scalable = render(cluster).lines()
+ .filter(line -> line.startsWith("pulsar_scalable_topic_")
+ && line.contains("cluster=\"" + cluster + "\""))
+ .toList();
+ assertThat(scalable).isNotEmpty();
+ assertThat(scalable).allSatisfy(line ->
+ assertThat(line.split("cluster=", -1)).as("single cluster label: %s", line).hasSize(2));
+ assertThat(scalable.stream().map(line -> line.substring(0, line.indexOf('}') + 1)).toList())
+ .doesNotHaveDuplicates();
+ assertThat(render(cluster).lines()
+ .filter(line -> line.equals("# TYPE " + PROM_SESSION + " gauge")).count()).isEqualTo(1);
+ metrics.close();
+ assertThat(existingRenderedLines(existing, cluster)).isEqualTo(before);
+ }
+ try (ScalableTopicMetrics restarted = new ScalableTopicMetrics(existing.meter, cluster)) {
+ exercise(restarted);
+ assertThat(existingRenderedLines(existing, cluster)).isEqualTo(before);
+ }
+ assertThat(existingRenderedLines(existing, cluster)).isEqualTo(before);
+ }
+ }
+
+ private static void exercise(ScalableTopicMetrics metrics) {
+ metrics.sessionOpened(ScalableTopicMetrics.WatchType.TOPIC);
+ metrics.sessionOpened(ScalableTopicMetrics.WatchType.NAMESPACE);
+ metrics.sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ metrics.recordWatchUpdate(true);
+ metrics.recordWatchUpdate(false);
+ metrics.startRequest(ScalableTopicMetrics.RequestType.LOOKUP).success();
+ metrics.startRequest(ScalableTopicMetrics.RequestType.UNSUBSCRIBE).failure();
+ }
+
+ private static List<String> existingRenderedLines(ExistingMetrics existing, String cluster) {
+ List<String> lines = render(cluster).lines().filter(line -> existing.promNames.stream()
+ .anyMatch(name -> line.startsWith(name + "{") || line.startsWith(name + "_")
+ || line.startsWith("# TYPE " + name + " "))).sorted().toList();
+ assertThat(lines).contains("# TYPE " + existing.counterName + " counter",
+ "# TYPE " + existing.gaugeName + " gauge", "# TYPE " + existing.histogramName + " histogram");
+ assertThat(lines).filteredOn(line -> !line.startsWith("#")).allSatisfy(line -> {
+ assertThat(line).contains("cluster=\"" + cluster + "\"");
+ assertThat(line.split("cluster=", -1)).hasSize(2);
+ });
+ return lines;
+ }
+
+ private static String render(String cluster) {
+ ByteBuf buffer = Unpooled.buffer();
+ try {
+ PrometheusMetricsGeneratorUtils.generateSystemMetrics(new SimpleTextOutputStream(buffer), cluster);
+ return buffer.toString(StandardCharsets.UTF_8);
+ } finally {
+ buffer.release();
+ }
+ }
+
+ private record MetricSnapshot(String name, String type, String help, String unit, List<?> points) {}
+ private record PrometheusPoint(String name, List<String> labels, List<String> values, double value) {}
+ private record LongPoint(Attributes attributes, long value) {}
+ private record HistogramPoint(Attributes attributes, long count, double sum, List<Double> boundaries,
+ List<Long> counts, double min, double max) {}
+
+ private static List<MetricSnapshot> prometheusSnapshot(CollectorRegistry registry, Set<String> names) {
+ return Collections.list(registry.metricFamilySamples()).stream().filter(family -> names.contains(family.name))
+ .map(family -> new MetricSnapshot(family.name, family.type.name(), family.help, "",
+ family.samples.stream()
+ .map(sample -> new PrometheusPoint(sample.name, List.copyOf(sample.labelNames),
+ List.copyOf(sample.labelValues), sample.value))
+ .sorted(Comparator.comparing(PrometheusPoint::name)
+ .thenComparing(point -> point.values().toString())).toList()))
+ .sorted(Comparator.comparing(MetricSnapshot::name)).toList();
+ }
+
+ // Omit only collection timestamps: all exposed metadata, labels, values and bucket boundaries are preserved.
+ private static MetricSnapshot otelSnapshot(MetricData metric) {
+ String type = metric.getType().name();
+ List<?> points;
+ switch (metric.getType()) {
+ case LONG_SUM -> {
+ type += ":" + metric.getLongSumData().isMonotonic() + ":"
+ + metric.getLongSumData().getAggregationTemporality();
+ points = metric.getLongSumData().getPoints().stream()
+ .map(point -> new LongPoint(point.getAttributes(), point.getValue())).toList();
+ }
+ case HISTOGRAM -> {
+ type += ":" + metric.getHistogramData().getAggregationTemporality();
+ points = metric.getHistogramData().getPoints().stream()
+ .map(point -> new HistogramPoint(point.getAttributes(), point.getCount(), point.getSum(),
+ List.copyOf(point.getBoundaries()), List.copyOf(point.getCounts()),
+ point.getMin(), point.getMax())).toList();
+ }
+ default -> throw new AssertionError("Unexpected existing instrument: " + metric.getType());
+ }
+ return new MetricSnapshot(metric.getName(), type, metric.getDescription(), metric.getUnit(), points);
+ }
+
+ private static final class ExistingMetrics implements AutoCloseable {
+ private final CollectorRegistry registry;
+ private final InMemoryMetricReader reader = InMemoryMetricReader.create();
+ private final SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build();
+ private final Meter meter = provider.get("isolation-test");
+ private final AtomicLong callbackValue = new AtomicLong();
+ private final AtomicLong lookupValue = new AtomicLong(9);
+ private final String counterName;
+ private final String gaugeName;
+ private final String histogramName;
+ private final Set<String> promNames;
+ private final Counter counter;
+ private final Gauge gauge;
+ private final Histogram histogram;
+ private final OpenTelemetryMessageFinderStats finder = new OpenTelemetryMessageFinderStats(meter);
+ private final ObservableLongCounter callback;
+ private final ObservableLongUpDownCounter lookups;
+ private final Set<String> otelNames = Set.of(OLD_CALLBACK, OLD_LOOKUPS,
+ OpenTelemetryMessageFinderStats.FIND_DURATION_METRIC_NAME,
+ OpenTelemetryMessageFinderStats.FIND_ENTRY_READ_COUNT_METRIC_NAME,
+ OpenTelemetryMessageFinderStats.FIND_ENTRY_READ_SIZE_METRIC_NAME);
+
+ private ExistingMetrics(CollectorRegistry registry, String suffix) {
+ this.registry = registry;
+ // Existing Prometheus names, help, labels and histogram buckets from SchemaRegistryStats/BrokerService.
+ counterName = "pulsar_schema_get_ops_failed" + suffix;
+ gaugeName = "pulsar_broker_lookup_pending_requests" + suffix;
+ histogramName = "pulsar_storage_backlog_quota_check_duration_seconds" + suffix;
+ promNames = Set.of(counterName, gaugeName, histogramName);
+ counter = Counter.build(counterName + "_total", "-").labelNames("namespace").register(registry);
+ gauge = Gauge.build(gaugeName, "-").register(registry);
+ histogram = Histogram.build(histogramName, "The duration of the backlog quota check process.")
+ .buckets(5, 10, 30, 60, 300).register(registry);
+ callback = meter.counterBuilder(OLD_CALLBACK)
+ .setDescription("The number of non-recoverable entries skipped.")
+ .setUnit("{entry}").buildWithCallback(measurement -> measurement.record(callbackValue.get()));
+ lookups = meter.upDownCounterBuilder(OLD_LOOKUPS)
+ .setDescription("The number of pending lookup operations in the broker. "
+ + "When it reaches threshold \"maxConcurrentLookupRequest\" defined in broker.conf, "
+ + "new requests are rejected.")
+ .setUnit("{operation}").buildWithCallback(measurement -> measurement.record(lookupValue.get()));
+ advance();
+ }
+
+ private void advance() {
+ counter.labels("tenant/namespace").inc(2);
+ gauge.set(lookupValue.addAndGet(2));
+ histogram.observe(8);
+ callbackValue.addAndGet(2);
+ finder.recordEntryRead(FindReason.SEEK, EntryStorage.BOOKKEEPER, 1024);
+ finder.recordFindCompleted(FindReason.SEEK, FindResult.FOUND, TimeUnit.MILLISECONDS.toNanos(125));
+ }
+
+ private List<MetricSnapshot> snapshot() {
+ List<MetricSnapshot> result = new ArrayList<>(prometheusSnapshot(registry, promNames));
+ result.addAll(reader.collectAllMetrics().stream().filter(metric -> otelNames.contains(metric.getName()))
+ .map(ScalableTopicMetricsIsolationTest::otelSnapshot).toList());
+ assertThat(result).as("all three Prometheus and five existing OTel instruments remain exported").hasSize(8);
+ return result.stream().sorted(Comparator.comparing(MetricSnapshot::name)).toList();
+ }
+
+ private void assertUnchanged(List<MetricSnapshot> before) {
+ assertThat(snapshot()).as("existing metric metadata, labels, buckets and values").isEqualTo(before);
+ }
+
+ private void assertStillUpdates(List<MetricSnapshot> before) {
+ advance();
+ List<MetricSnapshot> after = snapshot();
+ assertThat(after).extracting(metric -> List.of(metric.name(), metric.type(), metric.help(), metric.unit()))
+ .isEqualTo(before.stream().map(metric ->
+ List.of(metric.name(), metric.type(), metric.help(), metric.unit())).toList());
+ assertThat(registry.getSampleValue(counterName + "_total",
+ new String[]{"namespace"}, new String[]{"tenant/namespace"})).isEqualTo(4);
+ assertThat(registry.getSampleValue(gaugeName)).isEqualTo(13);
+ assertThat(registry.getSampleValue(histogramName + "_count")).isEqualTo(2);
+ assertThat(after).filteredOn(metric -> metric.name().equals(OLD_CALLBACK)).singleElement()
+ .satisfies(metric -> assertThat(metric.points())
+ .isEqualTo(List.of(new LongPoint(Attributes.empty(), 4))));
+ assertThat(after).filteredOn(metric -> metric.name().equals(OLD_LOOKUPS)).singleElement()
+ .satisfies(metric -> assertThat(metric.points())
+ .isEqualTo(List.of(new LongPoint(Attributes.empty(), 13))));
+ assertThat(after).filteredOn(metric ->
+ metric.name().equals(OpenTelemetryMessageFinderStats.FIND_ENTRY_READ_COUNT_METRIC_NAME))
+ .singleElement().satisfies(metric -> assertThat(((LongPoint) metric.points().getFirst()).value())
+ .isEqualTo(2));
+ assertThat(after).filteredOn(metric ->
+ metric.name().equals(OpenTelemetryMessageFinderStats.FIND_ENTRY_READ_SIZE_METRIC_NAME))
+ .singleElement().satisfies(metric -> assertThat(((LongPoint) metric.points().getFirst()).value())
+ .isEqualTo(2048));
+ assertThat(after).filteredOn(metric ->
+ metric.name().equals(OpenTelemetryMessageFinderStats.FIND_DURATION_METRIC_NAME)).singleElement()
+ .satisfies(metric -> assertThat(metric.points()).singleElement().satisfies(point -> {
+ HistogramPoint histogramPoint = (HistogramPoint) point;
+ assertThat(histogramPoint.count()).isEqualTo(2);
+ assertThat(histogramPoint.sum()).isEqualTo(0.25);
+ }));
+ }
+
+ @Override
+ public void close() {
+ callback.close();
+ lookups.close();
+ registry.unregister(counter);
+ registry.unregister(gauge);
+ registry.unregister(histogram);
+ provider.close();
+ }
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsTest.java
new file mode 100644
index 000000000000..5c6b2eec30c2
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicMetricsTest.java
@@ -0,0 +1,794 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyDouble;
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+import io.opentelemetry.api.common.Attributes;
+import io.opentelemetry.api.metrics.DoubleHistogram;
+import io.opentelemetry.api.metrics.DoubleHistogramBuilder;
+import io.opentelemetry.api.metrics.Meter;
+import io.opentelemetry.sdk.metrics.SdkMeterProvider;
+import io.opentelemetry.sdk.metrics.data.HistogramPointData;
+import io.opentelemetry.sdk.metrics.data.MetricData;
+import io.opentelemetry.sdk.metrics.data.MetricDataType;
+import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
+import io.prometheus.client.Collector;
+import io.prometheus.client.CollectorRegistry;
+import io.prometheus.client.Gauge;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics.RequestType;
+import org.apache.pulsar.broker.service.scalable.ScalableTopicMetrics.WatchType;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class ScalableTopicMetricsTest {
+ private static final String CLUSTER = "test-cluster";
+ private static final String PROM_DURATION = "pulsar_scalable_topic_request_duration_seconds";
+ private static final String PROM_SESSIONS = "pulsar_scalable_topic_watch_session_count";
+ private static final String PROM_UPDATES = "pulsar_scalable_topic_watch_update_total";
+ private static final List<Double> BUCKETS =
+ List.of(0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 5.0, 30.0);
+
+ @Test
+ public void testSessionAndUpdateExporterParity() {
+ CollectorRegistry registry = new CollectorRegistry();
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics metrics = new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry)) {
+ assertSessionsAndUpdates(telemetry, registry, 0, 0, 0, 0);
+ metrics.sessionOpened(WatchType.TOPIC);
+ metrics.sessionOpened(WatchType.TOPIC);
+ metrics.sessionOpened(WatchType.NAMESPACE);
+ metrics.sessionClosed(WatchType.TOPIC);
+ metrics.recordWatchUpdate(true);
+ metrics.recordWatchUpdate(false);
+ metrics.recordWatchUpdate(true);
+ assertSessionsAndUpdates(telemetry, registry, 1, 1, 2, 1);
+
+ metrics.sessionClosed(WatchType.TOPIC);
+ metrics.sessionClosed(WatchType.NAMESPACE);
+ assertSessionsAndUpdates(telemetry, registry, 0, 0, 2, 1);
+ MetricData sessions = telemetry.metric(ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME);
+ assertThat(sessions.getType()).isEqualTo(MetricDataType.LONG_SUM);
+ assertThat(sessions.getLongSumData().isMonotonic()).isFalse();
+ assertThat(sessions.getUnit()).isEqualTo("{session}");
+ MetricData updates = telemetry.metric(ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME);
+ assertThat(updates.getLongSumData().isMonotonic()).isTrue();
+ assertThat(updates.getUnit()).isEqualTo("{update}");
+ assertThat(family(registry, PROM_SESSIONS).type).isEqualTo(Collector.Type.GAUGE);
+ assertThat(family(registry, "pulsar_scalable_topic_watch_update").type)
+ .isEqualTo(Collector.Type.COUNTER);
+ }
+ }
+
+ @Test
+ public void testRequestHistogramExporterParityLabelsAndBuckets() {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong nanoTime = new AtomicLong();
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics metrics =
+ new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry, nanoTime::get)) {
+ List<Double> durations = new ArrayList<>(BUCKETS);
+ durations.add(0.0005);
+ durations.add(31.0);
+ for (RequestType type : RequestType.values()) {
+ for (boolean success : new boolean[]{true, false}) {
+ for (double seconds : durations) {
+ ScalableTopicMetrics.Request request = metrics.startRequest(type);
+ nanoTime.addAndGet((long) (seconds * 1_000_000_000));
+ complete(request, success);
+ }
+ }
+ }
+ MetricData metric = telemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME);
+ assertThat(metric.getType()).isEqualTo(MetricDataType.HISTOGRAM);
+ assertThat(metric.getUnit()).isEqualTo("s");
+ assertThat(metric.getHistogramData().getPoints()).hasSize(8);
+ for (RequestType type : RequestType.values()) {
+ String requestType = type.name().toLowerCase(Locale.ROOT);
+ for (String status : List.of("success", "failure")) {
+ Attributes attributes = requestAttributes(requestType, status);
+ HistogramPointData point = histogramPoint(metric, attributes);
+ assertThat(point.getCount()).isEqualTo(durations.size());
+ assertThat(point.getBoundaries()).containsExactlyElementsOf(BUCKETS);
+ assertThat(point.getSum()).isEqualTo(durationSample(registry, "_sum", requestType, status));
+ assertThat((double) point.getCount())
+ .isEqualTo(durationSample(registry, "_count", requestType, status));
+ long cumulative = 0;
+ for (int i = 0; i < point.getCounts().size(); i++) {
+ cumulative += point.getCounts().get(i);
+ String boundary = i < BUCKETS.size()
+ ? Collector.doubleToGoString(BUCKETS.get(i)) : "+Inf";
+ assertThat(registry.getSampleValue(PROM_DURATION + "_bucket",
+ new String[]{"cluster", "request_type", "operation_status", "le"},
+ new String[]{CLUSTER, requestType, status, boundary}))
+ .as("cumulative bucket %s for %s/%s", boundary, requestType, status)
+ .isEqualTo((double) cumulative);
+ if (i < BUCKETS.size()) {
+ double upperBound = BUCKETS.get(i);
+ assertThat(cumulative).isEqualTo(durations.stream().filter(d -> d <= upperBound).count());
+ }
+ }
+ assertThat(cumulative).isEqualTo(durations.size());
+ }
+ }
+ Collector.MetricFamilySamples histogram = family(registry, PROM_DURATION);
+ assertThat(histogram.type).isEqualTo(Collector.Type.HISTOGRAM);
+ assertThat(histogram.samples).allSatisfy(sample -> {
+ assertThat(sample.labelNames).contains("cluster", "request_type", "operation_status");
+ assertThat(sample.labelNames).isSubsetOf("cluster", "request_type", "operation_status", "le");
+ assertThat(sample.labelValues.get(sample.labelNames.indexOf("cluster"))).isEqualTo(CLUSTER);
+ });
+ }
+ }
+
+ @DataProvider
+ public Object[][] outcomes() {
+ return new Object[][]{{true}, {false}};
+ }
+
+ @Test(dataProvider = "outcomes")
+ public void testOnlyFirstResponseRecordsDuration(boolean success) {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong nanoTime = new AtomicLong(TimeUnit.SECONDS.toNanos(3));
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics metrics =
+ new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry, nanoTime::get)) {
+ ScalableTopicMetrics.Request request = metrics.startRequest(RequestType.LOOKUP);
+ nanoTime.addAndGet(TimeUnit.MILLISECONDS.toNanos(20));
+ complete(request, success);
+ nanoTime.addAndGet(TimeUnit.SECONDS.toNanos(9));
+ complete(request, !success);
+ complete(request, success);
+
+ MetricData metric = telemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME);
+ assertThat(metric.getHistogramData().getPoints()).hasSize(1);
+ String status = success ? "success" : "failure";
+ HistogramPointData point = histogramPoint(metric, requestAttributes("lookup", status));
+ assertThat(point.getCount()).isEqualTo(1);
+ assertThat(point.getSum()).isEqualTo(0.02);
+ assertThat(durationSample(registry, "_count", "lookup", status)).isEqualTo(1);
+ assertThat(durationSample(registry, "_sum", "lookup", status)).isEqualTo(0.02);
+ assertThat(durationSample(registry, "_count", "lookup", success ? "failure" : "success")).isNull();
+ }
+ }
+
+ @Test
+ public void testConcurrentResponsesRecordExactlyOnce() throws Exception {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong nanoTime = new AtomicLong();
+ ExecutorService executor = Executors.newFixedThreadPool(4);
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics metrics =
+ new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry, nanoTime::get)) {
+ ScalableTopicMetrics.Request request = metrics.startRequest(RequestType.SUBSCRIBE);
+ nanoTime.set(TimeUnit.MILLISECONDS.toNanos(50));
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<?>> responses = new ArrayList<>();
+ for (int i = 0; i < 32; i++) {
+ boolean success = i % 2 == 0;
+ responses.add(executor.submit(() -> {
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ complete(request, success);
+ return null;
+ }));
+ }
+ start.countDown();
+ for (Future<?> response : responses) {
+ response.get(10, TimeUnit.SECONDS);
+ }
+ MetricData metric = telemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME);
+ assertThat(metric.getHistogramData().getPoints()).singleElement().satisfies(point -> {
+ assertThat(point.getCount()).isEqualTo(1);
+ assertThat(point.getSum()).isEqualTo(0.05);
+ String status = point.getAttributes().asMap().values().contains("success") ? "success" : "failure";
+ assertThat(durationSample(registry, "_count", "subscribe", status)).isEqualTo(1);
+ assertThat(durationSample(registry, "_sum", "subscribe", status)).isEqualTo(0.05);
+ });
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ public void testCloseUnregistersCollectorAndObservableCallbacks() {
+ CollectorRegistry registry = new CollectorRegistry();
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics metrics = new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry)) {
+ metrics.sessionOpened(WatchType.TOPIC);
+ metrics.recordWatchUpdate(true);
+ metrics.startRequest(RequestType.LOOKUP).success();
+ ScalableTopicMetrics.Request pending = metrics.startRequest(RequestType.SUBSCRIBE);
+ assertSessionsAndUpdates(telemetry, registry, 1, 0, 1, 0);
+ metrics.close();
+ metrics.close();
+ pending.failure();
+ metrics.sessionOpened(WatchType.TOPIC);
+ metrics.sessionClosed(WatchType.TOPIC);
+ metrics.recordWatchUpdate(false);
+ assertThat(Collections.list(registry.metricFamilySamples())).isEmpty();
+ assertThat(telemetry.reader.collectAllMetrics()).extracting(MetricData::getName)
+ .doesNotContain(ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME,
+ ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME);
+ // Synchronous OTel histograms have no close method and retain their already recorded values.
+ assertThat(telemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).singleElement().satisfies(point ->
+ assertThat(point.getCount()).isEqualTo(1));
+ }
+ }
+
+ @Test
+ public void testDefaultRegistrySharedBrokerLifecycle() {
+ String cluster = "scalable-metrics-" + UUID.randomUUID();
+ CollectorRegistry registry = CollectorRegistry.defaultRegistry;
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry secondTelemetry = new Telemetry();
+ Telemetry thirdTelemetry = new Telemetry();
+ ScalableTopicMetrics first = new ScalableTopicMetrics(firstTelemetry.meter, cluster);
+ ScalableTopicMetrics second = new ScalableTopicMetrics(secondTelemetry.meter, cluster)) {
+ first.sessionOpened(WatchType.TOPIC);
+ second.sessionOpened(WatchType.TOPIC);
+ second.sessionOpened(WatchType.NAMESPACE);
+ first.recordWatchUpdate(true);
+ second.recordWatchUpdate(true);
+ first.startRequest(RequestType.LOOKUP).success();
+ second.startRequest(RequestType.LOOKUP).success();
+ assertThat(sessionSample(registry, cluster, "topic")).isEqualTo(2);
+ assertThat(sessionSample(registry, cluster, "namespace")).isEqualTo(1);
+ assertThat(updateSample(registry, cluster, "success")).isEqualTo(2);
+ assertThat(registry.getSampleValue(PROM_DURATION + "_count",
+ new String[]{"cluster", "request_type", "operation_status"},
+ new String[]{cluster, "lookup", "success"})).isEqualTo(2);
+ assertThat(family(registry, PROM_SESSIONS).samples)
+ .filteredOn(sample -> sample.labelValues.contains(cluster)).hasSize(2);
+
+ first.close();
+ first.close();
+ assertThat(sessionSample(registry, cluster, "topic")).isEqualTo(1);
+ assertThat(updateSample(registry, cluster, "success")).isEqualTo(2);
+ assertThat(registry.getSampleValue(PROM_DURATION + "_count",
+ new String[]{"cluster", "request_type", "operation_status"},
+ new String[]{cluster, "lookup", "success"})).isEqualTo(2);
+ assertThat(longPoint(secondTelemetry, ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME,
+ watchAttributes("topic"))).isEqualTo(1);
+
+ // Distinct clusters share registration, but never share state or labels.
+ String otherCluster = cluster + "-other";
+ try (ScalableTopicMetrics third = new ScalableTopicMetrics(thirdTelemetry.meter, otherCluster)) {
+ third.sessionOpened(WatchType.NAMESPACE);
+ second.close();
+ assertThat(sessionSample(registry, cluster, "topic")).isNull();
+ assertThat(sessionSample(registry, otherCluster, "namespace")).isEqualTo(1);
+ assertThat(longPoint(thirdTelemetry, ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME,
+ watchAttributes("namespace"))).isEqualTo(1);
+ }
+ assertThat(sessionSample(registry, otherCluster, "namespace")).isNull();
+ assertThat(sessionSample(registry, cluster, "topic")).isNull();
+
+ // Last close releases registration, and a new broker starts with fresh state.
+ try (ScalableTopicMetrics restarted = new ScalableTopicMetrics(thirdTelemetry.meter, cluster)) {
+ first.close();
+ second.close();
+ assertThat(sessionSample(registry, cluster, "topic")).isEqualTo(0);
+ assertThat(updateSample(registry, cluster, "success")).isEqualTo(0);
+ restarted.sessionOpened(WatchType.TOPIC);
+ assertThat(sessionSample(registry, cluster, "topic")).isEqualTo(1);
+ }
+ }
+ assertThat(sessionSample(registry, cluster, "topic")).isNull();
+ }
+
+ @Test
+ public void testSharedClusterRetainsCumulativeSamplesUntilLastBrokerCloses() {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong firstClock = new AtomicLong();
+ AtomicLong secondClock = new AtomicLong();
+ AtomicLong replacementClock = new AtomicLong();
+ AtomicLong restartedClock = new AtomicLong();
+ String otherCluster = CLUSTER + "-other";
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry secondTelemetry = new Telemetry();
+ Telemetry replacementTelemetry = new Telemetry();
+ Telemetry restartedTelemetry = new Telemetry();
+ Telemetry otherTelemetry = new Telemetry();
+ ScalableTopicMetrics first =
+ new ScalableTopicMetrics(firstTelemetry.meter, CLUSTER, registry, firstClock::get);
+ ScalableTopicMetrics second =
+ new ScalableTopicMetrics(secondTelemetry.meter, CLUSTER, registry, secondClock::get);
+ ScalableTopicMetrics other = new ScalableTopicMetrics(otherTelemetry.meter, otherCluster, registry)) {
+ first.sessionOpened(WatchType.TOPIC);
+ first.sessionOpened(WatchType.NAMESPACE);
+ recordAllOutcomesAndBoundaries(first, firstClock);
+ Map<CumulativeSample, Double> oneBroker = cumulativeSamples(registry, CLUSTER);
+ assertThat(oneBroker).hasSize(RequestType.values().length * 2 * (BUCKETS.size() + 3) + 2);
+ second.sessionOpened(WatchType.TOPIC);
+ recordAllOutcomesAndBoundaries(second, secondClock);
+ recordAllOutcomesAndBoundaries(second, secondClock);
+ other.sessionOpened(WatchType.NAMESPACE);
+ other.recordWatchUpdate(true);
+ Map<CumulativeSample, Double> beforeClose = cumulativeSamples(registry, CLUSTER);
+ Map<CumulativeSample, Double> otherBefore = cumulativeSamples(registry, otherCluster);
+ MetricData secondHistogram = secondTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME);
+ assertThat(secondHistogram.getHistogramData().getPoints()).hasSize(8).allSatisfy(point ->
+ assertThat(point.getCount()).isEqualTo(2L * (BUCKETS.size() + 2)));
+
+ first.close();
+ assertThat(cumulativeSamples(registry, CLUSTER))
+ .as("closing one broker must not subtract cumulative totals, buckets, counts or sums")
+ .isEqualTo(beforeClose);
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo(1);
+ assertThat(sessionSample(registry, CLUSTER, "namespace")).isEqualTo(0);
+ first.close();
+ first.recordWatchUpdate(true);
+ first.startRequest(RequestType.LOOKUP).failure();
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(beforeClose);
+ assertThat(longPoint(secondTelemetry, ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME,
+ statusAttributes("success"))).isEqualTo(8);
+ assertThat(secondTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).hasSize(8).allSatisfy(point -> {
+ assertThat(point.getCount()).isEqualTo(2L * (BUCKETS.size() + 2));
+ assertThat(point.getBoundaries()).isEqualTo(BUCKETS);
+ });
+
+ recordAllOutcomesAndBoundaries(second, secondClock);
+ assertCumulativeMultiple(registry, CLUSTER, oneBroker, 4);
+ assertThat(longPoint(secondTelemetry, ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME,
+ statusAttributes("success"))).isEqualTo(12);
+ assertThat(secondTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).hasSize(8).allSatisfy(point ->
+ assertThat(point.getCount()).isEqualTo(3L * (BUCKETS.size() + 2)));
+
+ Map<CumulativeSample, Double> beforeReplacement = cumulativeSamples(registry, CLUSTER);
+ try (ScalableTopicMetrics replacement = new ScalableTopicMetrics(
+ replacementTelemetry.meter, CLUSTER, registry, replacementClock::get)) {
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(beforeReplacement);
+ replacement.sessionOpened(WatchType.TOPIC);
+ recordAllOutcomesAndBoundaries(replacement, replacementClock);
+ assertCumulativeMultiple(registry, CLUSTER, oneBroker, 5);
+ Map<CumulativeSample, Double> beforeSecondClose = cumulativeSamples(registry, CLUSTER);
+ second.close();
+ second.close();
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(beforeSecondClose);
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo(1);
+ }
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEmpty();
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isNull();
+ assertThat(cumulativeSamples(registry, otherCluster)).isEqualTo(otherBefore);
+ assertThat(sessionSample(registry, otherCluster, "namespace")).isEqualTo(1);
+
+ // A cluster that starts a new lifetime must not inherit history while another cluster remains live.
+ try (ScalableTopicMetrics restarted = new ScalableTopicMetrics(
+ restartedTelemetry.meter, CLUSTER, registry, restartedClock::get)) {
+ assertThat(cumulativeSamples(registry, CLUSTER)).hasSize(2)
+ .allSatisfy((sample, value) -> assertThat(value).isZero());
+ recordAllOutcomesAndBoundaries(restarted, restartedClock);
+ assertCumulativeMultiple(registry, CLUSTER, oneBroker, 1);
+ }
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEmpty();
+ }
+ assertThat(Collections.list(registry.metricFamilySamples())).isEmpty();
+ try (Telemetry telemetry = new Telemetry();
+ ScalableTopicMetrics fresh = new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry)) {
+ assertThat(cumulativeSamples(registry, CLUSTER)).hasSize(2)
+ .allSatisfy((sample, value) -> assertThat(value).isZero());
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo(0);
+ }
+ }
+
+ @DataProvider
+ public Object[][] brokerCloseOrders() {
+ return new Object[][]{{new int[]{0, 1, 2}}, {new int[]{0, 2, 1}}, {new int[]{1, 0, 2}},
+ {new int[]{1, 2, 0}}, {new int[]{2, 0, 1}}, {new int[]{2, 1, 0}}};
+ }
+
+ @Test(dataProvider = "brokerCloseOrders")
+ public void testThreeBrokerCloseOrderPreservesExactHistogramSum(int[] closeOrder) {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong firstClock = new AtomicLong();
+ AtomicLong secondClock = new AtomicLong();
+ AtomicLong thirdClock = new AtomicLong();
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry secondTelemetry = new Telemetry();
+ Telemetry thirdTelemetry = new Telemetry();
+ ScalableTopicMetrics first =
+ new ScalableTopicMetrics(firstTelemetry.meter, CLUSTER, registry, firstClock::get);
+ ScalableTopicMetrics second =
+ new ScalableTopicMetrics(secondTelemetry.meter, CLUSTER, registry, secondClock::get);
+ ScalableTopicMetrics third =
+ new ScalableTopicMetrics(thirdTelemetry.meter, CLUSTER, registry, thirdClock::get)) {
+ List<ScalableTopicMetrics> brokers = List.of(first, second, third);
+ List<AtomicLong> clocks = List.of(firstClock, secondClock, thirdClock);
+ for (int i = 0; i < brokers.size(); i++) {
+ brokers.get(i).sessionOpened(WatchType.TOPIC);
+ brokers.get(i).recordWatchUpdate(true);
+ recordLookup(brokers.get(i), clocks.get(i), TimeUnit.MILLISECONDS.toNanos(100L * (i + 1)));
+ }
+ Map<CumulativeSample, Double> before = cumulativeSamples(registry, CLUSTER);
+ // Compare the collected sum itself, not a decimal literal with a different floating-point rounding.
+ for (int i = 0; i < closeOrder.length - 1; i++) {
+ brokers.get(closeOrder[i]).close();
+ assertThat(cumulativeSamples(registry, CLUSTER)).as("close order %s, step %s", closeOrder, i)
+ .isEqualTo(before);
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo(2 - i);
+ }
+ brokers.get(closeOrder[2]).close();
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEmpty();
+ assertThat(Collections.list(registry.metricFamilySamples())).isEmpty();
+ }
+ }
+
+ @Test
+ public void testRecordCloseAndScrapeHandoffPreservesCumulativeSamples() throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(3);
+ CountDownLatch clockEntered = new CountDownLatch(1);
+ CountDownLatch releaseClock = new CountDownLatch(1);
+ AtomicBoolean blockClock = new AtomicBoolean();
+ AtomicLong firstClock = new AtomicLong();
+ AtomicLong survivorClock = new AtomicLong();
+ CollectorRegistry registry = new CollectorRegistry();
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry survivorTelemetry = new Telemetry();
+ Telemetry stressTelemetry = new Telemetry();
+ ScalableTopicMetrics first = new ScalableTopicMetrics(firstTelemetry.meter, CLUSTER, registry, () -> {
+ if (blockClock.compareAndSet(true, false)) {
+ clockEntered.countDown();
+ awaitLatch(releaseClock);
+ }
+ return firstClock.get();
+ });
+ ScalableTopicMetrics survivor =
+ new ScalableTopicMetrics(survivorTelemetry.meter, CLUSTER, registry, survivorClock::get)) {
+ recordLookup(first, firstClock, TimeUnit.MILLISECONDS.toNanos(100));
+ recordLookup(survivor, survivorClock, TimeUnit.MILLISECONDS.toNanos(200));
+ Map<CumulativeSample, Double> before = cumulativeSamples(registry, CLUSTER);
+ blockClock.set(true);
+ Future<?> lateRecord = executor.submit(() -> first.startRequest(RequestType.SUBSCRIBE).success());
+ awaitLatch(clockEntered);
+ try {
+ // The pending request has not reached acceptance; closing must finish without waiting for its clock.
+ executor.submit(first::close).get(10, TimeUnit.SECONDS);
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(before);
+ } finally {
+ releaseClock.countDown();
+ }
+ lateRecord.get(10, TimeUnit.SECONDS);
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(before);
+ assertThat(firstTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).singleElement().satisfies(point -> {
+ assertThat(point.getAttributes()).isEqualTo(requestAttributes("lookup", "success"));
+ assertThat(point.getCount()).isEqualTo(1);
+ });
+ assertThat(durationSample(registry, "_count", "subscribe", "success")).isNull();
+ recordLookup(survivor, survivorClock, TimeUnit.MILLISECONDS.toNanos(100));
+ assertCumulativeNondecreasing(before, cumulativeSamples(registry, CLUSTER));
+ assertThat(durationSample(registry, "_count", "lookup", "success")).isEqualTo(3);
+ assertAcceptedSdkRecordDoesNotBlockClose(executor);
+
+ for (int iteration = 0; iteration < 100; iteration++) {
+ CollectorRegistry sharedRegistry = new CollectorRegistry();
+ AtomicLong clock = new AtomicLong();
+ try (ScalableTopicMetrics closing = new ScalableTopicMetrics(
+ stressTelemetry.meter, CLUSTER, sharedRegistry, clock::get);
+ ScalableTopicMetrics live = new ScalableTopicMetrics(
+ stressTelemetry.meter, CLUSTER, sharedRegistry, clock::get)) {
+ recordLookup(closing, clock, TimeUnit.MILLISECONDS.toNanos(100));
+ recordLookup(live, clock, TimeUnit.MILLISECONDS.toNanos(100));
+ closing.recordWatchUpdate(true);
+ live.recordWatchUpdate(true);
+ Map<CumulativeSample, Double> baseline = cumulativeSamples(sharedRegistry, CLUSTER);
+ CountDownLatch start = new CountDownLatch(1);
+ Future<?> scraping = executor.submit(() -> {
+ awaitLatch(start);
+ for (int scrape = 0; scrape < 30; scrape++) {
+ assertThat(cumulativeSamples(sharedRegistry, CLUSTER)).isEqualTo(baseline);
+ }
+ });
+ Future<?> closingBroker = executor.submit(() -> {
+ start.countDown();
+ closing.close();
+ });
+ scraping.get(10, TimeUnit.SECONDS);
+ closingBroker.get(10, TimeUnit.SECONDS);
+ assertThat(cumulativeSamples(sharedRegistry, CLUSTER)).isEqualTo(baseline);
+ recordLookup(live, clock, TimeUnit.MILLISECONDS.toNanos(100));
+ live.recordWatchUpdate(true);
+ assertCumulativeNondecreasing(baseline, cumulativeSamples(sharedRegistry, CLUSTER));
+ assertThat(durationSample(sharedRegistry, "_count", "lookup", "success")).isEqualTo(3);
+ assertThat(updateSample(sharedRegistry, CLUSTER, "success")).isEqualTo(3);
+ }
+ assertThat(Collections.list(sharedRegistry.metricFamilySamples())).isEmpty();
+ }
+ } finally {
+ releaseClock.countDown();
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ public void testSeparateRegistriesAreIndependent() {
+ CollectorRegistry firstRegistry = new CollectorRegistry();
+ CollectorRegistry secondRegistry = new CollectorRegistry();
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry secondTelemetry = new Telemetry();
+ ScalableTopicMetrics first = new ScalableTopicMetrics(firstTelemetry.meter, CLUSTER, firstRegistry);
+ ScalableTopicMetrics second = new ScalableTopicMetrics(secondTelemetry.meter, CLUSTER, secondRegistry)) {
+ first.sessionOpened(WatchType.TOPIC);
+ second.sessionOpened(WatchType.NAMESPACE);
+ assertThat(sessionSample(firstRegistry, CLUSTER, "topic")).isEqualTo(1);
+ assertThat(sessionSample(secondRegistry, CLUSTER, "topic")).isEqualTo(0);
+ first.close();
+ assertThat(Collections.list(firstRegistry.metricFamilySamples())).isEmpty();
+ assertThat(sessionSample(secondRegistry, CLUSTER, "namespace")).isEqualTo(1);
+ }
+ }
+
+ @Test
+ public void testFailedRegistrationDoesNotLeakCallbacksOrUnregisterOtherCollector() {
+ CollectorRegistry registry = new CollectorRegistry();
+ Gauge existing = Gauge.build(PROM_SESSIONS, "Existing collector").register(registry);
+ try (Telemetry telemetry = new Telemetry()) {
+ assertThatThrownBy(() -> new ScalableTopicMetrics(telemetry.meter, CLUSTER, registry))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThat(telemetry.reader.collectAllMetrics()).isEmpty();
+ assertThat(registry.getSampleValue(PROM_SESSIONS)).isEqualTo(0);
+ } finally {
+ registry.unregister(existing);
+ }
+ }
+
+ private static void assertAcceptedSdkRecordDoesNotBlockClose(ExecutorService executor) throws Exception {
+ CollectorRegistry registry = new CollectorRegistry();
+ AtomicLong clock = new AtomicLong();
+ CountDownLatch sdkEntered = new CountDownLatch(1);
+ CountDownLatch releaseSdk = new CountDownLatch(1);
+ try (Telemetry firstTelemetry = new Telemetry();
+ Telemetry survivorTelemetry = new Telemetry()) {
+ DoubleHistogram histogram = spy(firstTelemetry.meter
+ .histogramBuilder(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .setDescription("Scalable-topic request duration from arrival to the first response.")
+ .setUnit("s").setExplicitBucketBoundariesAdvice(BUCKETS).build());
+ doAnswer(invocation -> {
+ sdkEntered.countDown();
+ awaitLatch(releaseSdk);
+ return invocation.callRealMethod();
+ }).when(histogram).record(anyDouble(), any(Attributes.class));
+ DoubleHistogramBuilder builder = mock(DoubleHistogramBuilder.class, RETURNS_SELF);
+ when(builder.build()).thenReturn(histogram);
+ Meter meter = spy(firstTelemetry.meter);
+ doReturn(builder).when(meter).histogramBuilder(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME);
+ try (ScalableTopicMetrics first = new ScalableTopicMetrics(meter, CLUSTER, registry, clock::get);
+ ScalableTopicMetrics survivor = new ScalableTopicMetrics(survivorTelemetry.meter, CLUSTER, registry)) {
+ first.sessionOpened(WatchType.TOPIC);
+ survivor.sessionOpened(WatchType.TOPIC);
+ ScalableTopicMetrics.Request request = first.startRequest(RequestType.LOOKUP);
+ clock.addAndGet(TimeUnit.MILLISECONDS.toNanos(100));
+ Future<?> accepted = executor.submit(request::success);
+ try {
+ awaitLatch(sdkEntered);
+ assertThat(durationSample(registry, "_count", "lookup", "success")).isEqualTo(1);
+ Map<CumulativeSample, Double> acceptedProm = cumulativeSamples(registry, CLUSTER);
+ executor.submit(first::close).get(10, TimeUnit.SECONDS);
+ assertThat(cumulativeSamples(registry, CLUSTER)).isEqualTo(acceptedProm);
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo(1);
+ } finally {
+ releaseSdk.countDown();
+ }
+ accepted.get(10, TimeUnit.SECONDS);
+ assertThat(firstTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).singleElement().satisfies(point -> {
+ assertThat(point.getCount()).isEqualTo(1);
+ assertThat(point.getSum()).isEqualTo(0.1);
+ });
+ first.startRequest(RequestType.SUBSCRIBE).success();
+ assertThat(durationSample(registry, "_count", "lookup", "success")).isEqualTo(1);
+ assertThat(durationSample(registry, "_count", "subscribe", "success")).isNull();
+ assertThat(firstTelemetry.metric(ScalableTopicMetrics.REQUEST_DURATION_METRIC_NAME)
+ .getHistogramData().getPoints()).singleElement().satisfies(point ->
+ assertThat(point.getCount()).isEqualTo(1));
+ }
+ } finally {
+ releaseSdk.countDown();
+ }
+ }
+
+ private static void recordLookup(ScalableTopicMetrics metrics, AtomicLong clock, long nanos) {
+ ScalableTopicMetrics.Request request = metrics.startRequest(RequestType.LOOKUP);
+ clock.addAndGet(nanos);
+ request.success();
+ }
+
+ private static void awaitLatch(CountDownLatch latch) {
+ try {
+ assertThat(latch.await(10, TimeUnit.SECONDS)).as("latch reached before deadline").isTrue();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AssertionError("Interrupted waiting for test handoff", e);
+ }
+ }
+
+ private static void assertCumulativeNondecreasing(Map<CumulativeSample, Double> before,
+ Map<CumulativeSample, Double> after) {
+ assertThat(after.keySet()).isEqualTo(before.keySet());
+ before.forEach((sample, value) -> assertThat(after.get(sample)).as("%s", sample)
+ .isGreaterThanOrEqualTo(value));
+ }
+
+ private record CumulativeSample(String name, List<String> labels, List<String> values) {}
+
+ private static Map<CumulativeSample, Double> cumulativeSamples(CollectorRegistry registry, String cluster) {
+ Map<CumulativeSample, Double> samples = new LinkedHashMap<>();
+ for (Collector.MetricFamilySamples family : Collections.list(registry.metricFamilySamples())) {
+ if (family.type != Collector.Type.COUNTER && family.type != Collector.Type.HISTOGRAM) {
+ continue;
+ }
+ for (Collector.MetricFamilySamples.Sample sample : family.samples) {
+ int clusterIndex = sample.labelNames.indexOf("cluster");
+ if (clusterIndex >= 0 && sample.labelValues.get(clusterIndex).equals(cluster)
+ && !sample.name.endsWith("_created")) {
+ CumulativeSample key = new CumulativeSample(sample.name,
+ List.copyOf(sample.labelNames), List.copyOf(sample.labelValues));
+ assertThat(samples).as("one cumulative series per label set").doesNotContainKey(key);
+ samples.put(key, sample.value);
+ }
+ }
+ }
+ return Map.copyOf(samples);
+ }
+
+ private static void recordAllOutcomesAndBoundaries(ScalableTopicMetrics metrics, AtomicLong nanoTime) {
+ List<Double> durations = new ArrayList<>(BUCKETS);
+ durations.add(0.0005);
+ durations.add(31.0);
+ for (RequestType type : RequestType.values()) {
+ for (boolean success : new boolean[]{true, false}) {
+ metrics.recordWatchUpdate(success);
+ for (double seconds : durations) {
+ ScalableTopicMetrics.Request request = metrics.startRequest(type);
+ nanoTime.addAndGet((long) (seconds * 1_000_000_000));
+ complete(request, success);
+ }
+ }
+ }
+ }
+
+ private static void assertCumulativeMultiple(CollectorRegistry registry, String cluster,
+ Map<CumulativeSample, Double> oneBroker, int multiple) {
+ Map<CumulativeSample, Double> actual = cumulativeSamples(registry, cluster);
+ assertThat(actual.keySet()).isEqualTo(oneBroker.keySet());
+ oneBroker.forEach((sample, value) -> {
+ // Histogram sums can differ by a few rounding bits when aggregation groups brokers differently.
+ if (sample.name().endsWith("_sum")) {
+ assertThat(actual.get(sample)).isBetween(value * multiple - 1e-9, value * multiple + 1e-9);
+ } else {
+ assertThat(actual.get(sample)).as("%s", sample).isEqualTo(value * multiple);
+ }
+ });
+ }
+
+ private static void complete(ScalableTopicMetrics.Request request, boolean success) {
+ if (success) {
+ request.success();
+ } else {
+ request.failure();
+ }
+ }
+
+ private static Attributes requestAttributes(String type, String status) {
+ return Attributes.builder().put("pulsar.scalable_topic.request.type", type)
+ .put("pulsar.scalable_topic.operation.status", status).build();
+ }
+
+ private static Attributes watchAttributes(String type) {
+ return Attributes.builder().put("pulsar.scalable_topic.watch.type", type).build();
+ }
+
+ private static Attributes statusAttributes(String status) {
+ return Attributes.builder().put("pulsar.scalable_topic.operation.status", status).build();
+ }
+
+ private static long longPoint(Telemetry telemetry, String name, Attributes attributes) {
+ return telemetry.metric(name).getLongSumData().getPoints().stream()
+ .filter(point -> point.getAttributes().equals(attributes)).findFirst().orElseThrow().getValue();
+ }
+
+ private static HistogramPointData histogramPoint(MetricData metric, Attributes attributes) {
+ return metric.getHistogramData().getPoints().stream()
+ .filter(point -> point.getAttributes().equals(attributes)).findFirst().orElseThrow();
+ }
+
+ private static Collector.MetricFamilySamples family(CollectorRegistry registry, String name) {
+ return Collections.list(registry.metricFamilySamples()).stream()
+ .filter(family -> family.name.equals(name)).findFirst().orElseThrow();
+ }
+
+ private static Double durationSample(CollectorRegistry registry, String suffix, String type, String status) {
+ return registry.getSampleValue(PROM_DURATION + suffix,
+ new String[]{"cluster", "request_type", "operation_status"}, new String[]{CLUSTER, type, status});
+ }
+
+ private static Double sessionSample(CollectorRegistry registry, String cluster, String type) {
+ return registry.getSampleValue(PROM_SESSIONS,
+ new String[]{"cluster", "watch_type"}, new String[]{cluster, type});
+ }
+
+ private static Double updateSample(CollectorRegistry registry, String cluster, String status) {
+ return registry.getSampleValue(PROM_UPDATES,
+ new String[]{"cluster", "operation_status"}, new String[]{cluster, status});
+ }
+
+ private static void assertSessionsAndUpdates(Telemetry telemetry, CollectorRegistry registry,
+ long topics, long namespaces, long successes, long failures) {
+ assertThat(longPoint(telemetry, ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME, watchAttributes("topic")))
+ .isEqualTo(topics);
+ assertThat(longPoint(telemetry, ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME,
+ watchAttributes("namespace"))).isEqualTo(namespaces);
+ assertThat(longPoint(telemetry, ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME,
+ statusAttributes("success"))).isEqualTo(successes);
+ assertThat(longPoint(telemetry, ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME,
+ statusAttributes("failure"))).isEqualTo(failures);
+ assertThat(sessionSample(registry, CLUSTER, "topic")).isEqualTo((double) topics);
+ assertThat(sessionSample(registry, CLUSTER, "namespace")).isEqualTo((double) namespaces);
+ assertThat(updateSample(registry, CLUSTER, "success")).isEqualTo((double) successes);
+ assertThat(updateSample(registry, CLUSTER, "failure")).isEqualTo((double) failures);
+ assertThat(telemetry.metric(ScalableTopicMetrics.WATCH_SESSION_COUNT_METRIC_NAME)
+ .getLongSumData().getPoints()).hasSize(2);
+ assertThat(telemetry.metric(ScalableTopicMetrics.WATCH_UPDATE_COUNT_METRIC_NAME)
+ .getLongSumData().getPoints()).hasSize(2);
+ }
+
+ private static final class Telemetry implements AutoCloseable {
+ private final InMemoryMetricReader reader = InMemoryMetricReader.create();
+ private final SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build();
+ private final Meter meter = provider.get("scalable-topic-metrics-test");
+
+ private MetricData metric(String name) {
+ return reader.collectAllMetrics().stream().filter(metric -> metric.getName().equals(name))
+ .findFirst().orElseThrow();
+ }
+
+ @Override
+ public void close() {
+ provider.close();
+ }
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionDeleteRaceTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionDeleteRaceTest.java
index 9a0a3c3ee48e..12d2cf68d4e1 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionDeleteRaceTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionDeleteRaceTest.java
@@ -25,7 +25,10 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.DefaultChannelPromise;
+import io.netty.util.concurrent.ImmediateEventExecutor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -100,7 +103,7 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
when(cnx.ctx()).thenReturn(ctx);
when(ctx.writeAndFlush(any())).thenAnswer(invocation -> {
applyFrame(invocation.getArgument(0));
- return null;
+ return new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE).setSuccess();
});
scheduler = mock(ScheduledExecutorService.class);
when(scheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenAnswer(invocation -> {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionHashTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionHashTest.java
index 1e9d84897cdd..0f4836d027f3 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionHashTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionHashTest.java
@@ -24,9 +24,9 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultChannelPromise;
-import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;
import java.util.List;
import java.util.Map;
@@ -59,6 +59,7 @@ public class ScalableTopicsWatcherSessionHashTest {
private ServerCnx cnx;
private ChannelHandlerContext ctx;
private ScheduledExecutorService scheduler;
+ private ScalableTopicsWatcherSession session;
@BeforeMethod
public void setUp() throws Exception {
@@ -68,16 +69,19 @@ public class ScalableTopicsWatcherSessionHashTest {
cnx = mock(ServerCnx.class);
ctx = mock(ChannelHandlerContext.class);
when(cnx.ctx()).thenReturn(ctx);
- // writeAndFlush returns a ChannelFuture; provide a no-op promise to keep the
- // call chain happy. The ScalableTopicsWatcherSession ignores the return.
- when(ctx.writeAndFlush(org.mockito.ArgumentMatchers.any()))
- .thenReturn(new DefaultChannelPromise(new EmbeddedChannel(),
- ImmediateEventExecutor.INSTANCE));
+ when(ctx.writeAndFlush(org.mockito.ArgumentMatchers.any())).thenAnswer(invocation -> {
+ ByteBuf frame = invocation.getArgument(0);
+ frame.release();
+ return new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE).setSuccess();
+ });
scheduler = Executors.newSingleThreadScheduledExecutor();
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception {
+ if (session != null) {
+ session.close();
+ }
if (scheduler != null) {
scheduler.shutdownNow();
}
@@ -97,7 +101,7 @@ public class ScalableTopicsWatcherSessionHashTest {
TopicName tn = TopicName.get("topic://" + ns + "/t1");
resources.createScalableTopicAsync(tn, meta()).get();
- var session = new ScalableTopicsWatcherSession(1L, ns, Map.of(),
+ session = new ScalableTopicsWatcherSession(1L, ns, Map.of(),
/* clientHash= */ null, cnx, resources, scheduler);
session.start().get();
@@ -115,7 +119,7 @@ public class ScalableTopicsWatcherSessionHashTest {
// matching hash with the same function the broker uses (TopicList.crc32c).
String matchingHash = TopicList.calculateHash(List.of(tn.toString()));
- var session = new ScalableTopicsWatcherSession(2L, ns, Map.of(),
+ session = new ScalableTopicsWatcherSession(2L, ns, Map.of(),
/* clientHash= */ matchingHash, cnx, resources, scheduler);
session.start().get();
@@ -134,7 +138,7 @@ public class ScalableTopicsWatcherSessionHashTest {
// Snapshot so the client can reconcile.
String staleHash = TopicList.calculateHash(List.of("topic://" + ns + "/something-else"));
- var session = new ScalableTopicsWatcherSession(3L, ns, Map.of(),
+ session = new ScalableTopicsWatcherSession(3L, ns, Map.of(),
/* clientHash= */ staleHash, cnx, resources, scheduler);
session.start().get();
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionMetricsTest.java
new file mode 100644
index 000000000000..5b4cef87bfd3
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicsWatcherSessionMetricsTest.java
@@ -0,0 +1,320 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.DefaultChannelPromise;
+import io.netty.util.concurrent.ImmediateEventExecutor;
+import java.util.ArrayDeque;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
+import org.apache.pulsar.broker.service.ServerCnx;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.topics.TopicList;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class ScalableTopicsWatcherSessionMetricsTest {
+ private static final NamespaceName NAMESPACE = NamespaceName.get("tenant/ns");
+
+ private ScalableTopicResources resources;
+ private ScalableTopicMetrics metrics;
+ private ScalableTopicMetrics.Request request;
+ private ChannelHandlerContext ctx;
+ private ServerCnx cnx;
+ private ScheduledExecutorService scheduler;
+ private ScalableTopicsWatcherSession session;
+ private CompletableFuture<List<String>> initialListing;
+ private final Queue<ChannelPromise> writes = new ArrayDeque<>();
+ private final Queue<Runnable> scheduled = new ArrayDeque<>();
+
+ @BeforeMethod
+ public void setUp() {
+ session = null;
+ writes.clear();
+ scheduled.clear();
+ resources = mock(ScalableTopicResources.class);
+ metrics = mock(ScalableTopicMetrics.class);
+ request = mock(ScalableTopicMetrics.Request.class);
+ ctx = mock(ChannelHandlerContext.class);
+ cnx = mock(ServerCnx.class);
+ scheduler = mock(ScheduledExecutorService.class);
+ when(cnx.ctx()).thenReturn(ctx);
+ when(resources.namespacePath(NAMESPACE)).thenReturn("/topics/tenant/ns");
+ initialListing = new CompletableFuture<>();
+ when(resources.findScalableTopicsByPropertiesAsync(NAMESPACE, Map.of())).thenReturn(initialListing);
+ when(resources.getScalableTopicMetadataAsync(any(), anyBoolean())).thenReturn(
+ CompletableFuture.completedFuture(Optional.of(ScalableTopicMetadata.builder().build())));
+ when(ctx.writeAndFlush(any())).thenAnswer(invocation -> {
+ ByteBuf frame = invocation.getArgument(0);
+ frame.release();
+ ChannelPromise promise = new DefaultChannelPromise(mock(Channel.class), ImmediateEventExecutor.INSTANCE);
+ writes.add(promise);
+ return promise;
+ });
+ when(scheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenAnswer(invocation -> {
+ scheduled.add(invocation.getArgument(0));
+ return null;
+ });
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() {
+ if (session != null) {
+ session.close();
+ }
+ writes.forEach(promise -> promise.tryFailure(new IllegalStateException("Test finished")));
+ }
+
+ private void createSession(String clientHash) {
+ session = new ScalableTopicsWatcherSession(1L, NAMESPACE, Map.of(), clientHash,
+ cnx, resources, scheduler, metrics, request);
+ }
+
+ @Test
+ public void initializationIsCountedAndConcurrentCloseCountsOnce() throws Exception {
+ createSession(null);
+ verify(metrics).sessionOpened(ScalableTopicMetrics.WatchType.NAMESPACE);
+ CompletableFuture<Void> started = session.start();
+ assertThat(started).as("initial listing is still in flight").isNotDone();
+ verify(metrics, never()).sessionClosed(any());
+
+ CompletableFuture.allOf(CompletableFuture.runAsync(session::close),
+ CompletableFuture.runAsync(session::close)).get(10, TimeUnit.SECONDS);
+ initialListing.complete(List.of());
+ started.get(10, TimeUnit.SECONDS);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(ctx, never()).writeAndFlush(any());
+ }
+
+ @Test
+ public void closeBeforeStartRetainsOriginalRegistrationBehavior() {
+ createSession(null);
+ session.close();
+ CompletableFuture<Void> started = session.start();
+ initialListing.complete(List.of());
+ assertThat(started).isCompleted();
+ verify(resources).registerNamespaceListener(session);
+ verify(resources).deregisterNamespaceListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(request).failure();
+ }
+
+ @Test
+ public void closeRacingRegistrationRetainsOriginalLateListenerBehavior() {
+ createSession(null);
+ Set<ScalableTopicResources.NamespaceListener> listeners = new HashSet<>();
+ doAnswer(invocation -> {
+ session.close(); // The close wins before the registration becomes visible.
+ listeners.add(session);
+ return null;
+ }).when(resources).registerNamespaceListener(session);
+ doAnswer(invocation -> {
+ listeners.remove(session);
+ return null;
+ }).when(resources).deregisterNamespaceListener(session);
+
+ CompletableFuture<Void> started = session.start();
+ assertThat(started).isNotDone();
+ assertThat(listeners).as("metrics must not repair the pre-existing late-registration leak")
+ .containsExactly(session);
+ verify(resources).deregisterNamespaceListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(request).failure();
+ }
+
+ @Test
+ public void failedStartDoesNotCloseSessionOrCompleteRequest() {
+ createSession(null);
+ CompletableFuture<Void> started = session.start();
+ initialListing.completeExceptionally(new IllegalStateException("Listing failed"));
+ assertThat(started).isCompletedExceptionally();
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ verifyNoInteractions(request);
+ session.close();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(resources).deregisterNamespaceListener(session);
+ verify(request).failure();
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+ }
+
+ @Test
+ public void initialRequestWaitsForWriteCompletion() {
+ createSession(null);
+ session.start();
+ initialListing.complete(List.of());
+ verifyNoInteractions(request);
+ writes.remove().setSuccess();
+ session.close();
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+ }
+
+ @Test
+ public void failedSnapshotWriteFailsRequestWithoutClosingSession() {
+ createSession(null);
+ session.start();
+ initialListing.complete(List.of());
+ writes.remove().setFailure(new IllegalStateException("Write failed"));
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ session.onNotification(new Notification(NotificationType.Created, "/topics/tenant/ns/topic"));
+ scheduled.remove().run();
+ writes.remove().setSuccess();
+ verify(ctx, times(2)).writeAndFlush(any());
+ session.close();
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+ }
+
+ @Test
+ public void closeBeforeSnapshotWriteCompletesDoesNotCompleteRequestTwice() {
+ createSession(null);
+ session.start();
+ initialListing.complete(List.of());
+ session.close();
+ writes.remove().setSuccess();
+ verify(request).failure();
+ verify(request, never()).success();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ }
+
+ @Test
+ public void matchingReconnectHashSucceedsWithoutResponse() {
+ createSession(TopicList.calculateHash(List.of("topic://tenant/ns/topic")));
+ session.start();
+ initialListing.complete(List.of("topic://tenant/ns/topic"));
+ session.close();
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(ctx, never()).writeAndFlush(any());
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+ }
+
+ @Test
+ public void namespaceDiffsAreNotLayoutUpdates() {
+ createSession(null);
+ session.start();
+ initialListing.complete(List.of());
+ writes.remove().setSuccess();
+ session.onNotification(new Notification(NotificationType.Created, "/topics/tenant/ns/topic"));
+ scheduled.remove().run();
+ writes.remove().setSuccess();
+ session.onNotification(new Notification(NotificationType.Deleted, "/topics/tenant/ns/topic"));
+ scheduled.remove().run();
+ writes.remove().setFailure(new IllegalStateException("Diff write failed"));
+ verify(ctx, times(3)).writeAndFlush(any());
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+ }
+
+ @Test
+ public void metricOnlyStopDoesNotCloseSessionOrStopItsWork() {
+ createSession(null);
+ session.stopMetricsTracking();
+ session.stopMetricsTracking();
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ verify(resources, never()).deregisterNamespaceListener(any());
+ verifyNoInteractions(request);
+
+ session.start();
+ initialListing.complete(List.of());
+ writes.remove().setSuccess();
+ session.onNotification(new Notification(NotificationType.Created, "/topics/tenant/ns/topic"));
+ scheduled.remove().run();
+ writes.remove().setSuccess();
+ verify(ctx, times(2)).writeAndFlush(any());
+ verify(resources).registerNamespaceListener(session);
+ verify(resources).getScalableTopicMetadataAsync(any(), anyBoolean());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ verify(request).success();
+ verify(request, never()).failure();
+ verify(metrics, never()).recordWatchUpdate(anyBoolean());
+
+ session.close();
+ session.close();
+ verify(resources).deregisterNamespaceListener(session);
+ verify(metrics).sessionClosed(ScalableTopicMetrics.WatchType.NAMESPACE);
+ }
+
+ @Test
+ public void synchronousStartFailurePropagatesWithoutLifecycleChanges() {
+ createSession(null);
+ IllegalStateException failure = new IllegalStateException("Registration failed");
+ doThrow(failure).when(resources).registerNamespaceListener(session);
+ assertThatThrownBy(session::start).isSameAs(failure);
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ verifyNoInteractions(request);
+ }
+
+ @Test
+ public void synchronousSnapshotWriteFailureDoesNotCloseSession() {
+ createSession(null);
+ IllegalStateException failure = new IllegalStateException("Write failed");
+ doAnswer(invocation -> {
+ ByteBuf frame = invocation.getArgument(0);
+ frame.release();
+ throw failure;
+ }).when(ctx).writeAndFlush(any());
+ CompletableFuture<Void> started = session.start();
+ initialListing.complete(List.of());
+ assertThat(started).isCompletedExceptionally();
+ verify(metrics, never()).sessionClosed(any());
+ verify(resources, never()).deregisterNamespaceListener(any());
+ verifyNoInteractions(request);
+ }
+
+}