You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2026/10/13 00:26:02 UTC
(pulsar) branch master updated: [fix][broker] Keep the scalable-topics watch's initial listing from undoing newer events (#26876)
This is an automated email from the ASF dual-hosted git repository.
merlimat 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 9939ea2b3dd1 [fix][broker] Keep the scalable-topics watch's initial listing from undoing newer events (#26876)
9939ea2b3dd1 is described below
commit 9939ea2b3dd1cf20b235b146481a8dfee3b07ed9
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Mon Oct 12 17:25:54 2026 -0700
[fix][broker] Keep the scalable-topics watch's initial listing from undoing newer events (#26876)
---
.../scalable/ScalableTopicsWatcherSession.java | 108 +++++----
...ScalableTopicsWatcherSessionDeleteRaceTest.java | 269 +++++++++++++++++++--
2 files changed, 308 insertions(+), 69 deletions(-)
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 ca8521c0c485..055be5adc6df 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
@@ -20,10 +20,12 @@ package org.apache.pulsar.broker.service.scalable;
import io.github.merlimat.slog.Logger;
import java.time.Duration;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -98,15 +100,25 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
private final Set<String> currentSet = Collections.synchronizedSet(new HashSet<>());
/**
- * Id of the metadata read started by each topic's latest Created / Modified event, while
- * that read is in flight. Only that read may change the topic's membership: an earlier one
- * — or one still in flight when the topic is deleted — may have seen an older record, and
- * applying it would undo the later event, e.g. bring a deleted topic back. Guarded by
- * {@code currentSet}'s monitor, together with the membership changes it gates.
+ * Id of each topic's latest metadata read, while that read is in flight: the read started by
+ * the topic's latest Created / Modified event, or by {@link #start()} for a topic that changed
+ * while the initial listing was in flight. Only that read may change the topic's membership:
+ * an earlier one — or one still in flight when the topic is deleted — may have seen an older
+ * record, and applying it would undo the later event, e.g. bring a deleted topic back. Guarded
+ * by {@code currentSet}'s monitor, together with the membership changes it gates.
*/
private final Map<String, Long> inFlightReads = new HashMap<>();
private long lastReadId;
+ /**
+ * Last event of each topic that changed while the initial listing was in flight, or
+ * {@code null} once the listing has been applied. The listing may have read the store
+ * before or after any of these events, so it can't be trusted for these topics:
+ * {@link #start()} settles them once the listing is in place. Guarded by
+ * {@code currentSet}'s monitor.
+ */
+ private Map<String, NotificationType> changedDuringListing = new HashMap<>();
+
private final AtomicBoolean closed = new AtomicBoolean();
private final AtomicBoolean snapshotEmitted = new AtomicBoolean();
@@ -150,38 +162,46 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
* listener.
*/
public CompletableFuture<Void> start() {
- // Register BEFORE computing the initial set: any event that arrives mid-snapshot
- // is captured by the listener and either (a) already in the initial set we're
- // about to emit, in which case the redundant Add is a no-op on the client
- // (set semantics), or (b) genuinely newer than the snapshot, in which case it
- // correctly flows through as a Diff after the Snapshot frame.
+ // Register BEFORE computing the initial set, so that no event is lost. An event that
+ // arrives before the listing completes may or may not be reflected in it: it is only
+ // recorded in changedDuringListing, and settled once the listing is in place.
resources.registerNamespaceListener(this);
return resources.findScalableTopicsByPropertiesAsync(namespace, propertyFilters)
- .thenAccept(initialTopics -> {
+ .thenAccept(listedTopics -> {
if (closed.get()) {
return;
}
- // Replace currentSet under sync to avoid races with onNotification.
+ List<String> initialTopics;
+ List<String> topicsToRead = new ArrayList<>();
synchronized (currentSet) {
- currentSet.clear();
- currentSet.addAll(initialTopics);
+ currentSet.addAll(listedTopics);
+ changedDuringListing.forEach((topic, lastEvent) -> {
+ if (lastEvent == NotificationType.Deleted) {
+ // Gone, unless created again — and then a Created event follows.
+ currentSet.remove(topic);
+ } else {
+ // Created or Modified, possibly after the listing read the store.
+ topicsToRead.add(topic);
+ }
+ });
+ changedDuringListing = null;
+ initialTopics = new ArrayList<>(currentSet);
}
- snapshotEmitted.set(true);
// Hash short-circuit: if the client tells us it already has this
// exact set (reconnect within an unchanged window), don't waste
// bytes on the wire. Future Diffs flow as usual.
- if (clientHash != null) {
- String serverHash = TopicList.calculateHash(initialTopics);
- if (clientHash.equals(serverHash)) {
- log.info().attr("topics", initialTopics.size())
- .log("Reconnect hash matched; skipping snapshot");
- return;
- }
+ if (clientHash != null && clientHash.equals(TopicList.calculateHash(initialTopics))) {
+ log.info().attr("topics", initialTopics.size())
+ .log("Reconnect hash matched; skipping snapshot");
+ } else {
+ log.info().attr("topics", initialTopics.size()).log("Initial snapshot");
+ cnx.ctx().writeAndFlush(
+ Commands.newWatchScalableTopicsSnapshot(watchId, initialTopics));
}
- log.info().attr("topics", initialTopics.size()).log("Initial snapshot");
- cnx.ctx().writeAndFlush(
- Commands.newWatchScalableTopicsSnapshot(watchId, initialTopics));
+ // Diffs are computed against the snapshot's set: let them out only after it.
+ snapshotEmitted.set(true);
+ topicsToRead.forEach(this::evaluateTopic);
});
}
@@ -209,17 +229,27 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
String topicName = TopicName.get("topic", namespace, Codec.decode(rest)).toString();
- if (notification.getType() == NotificationType.Deleted) {
- synchronized (currentSet) {
+ synchronized (currentSet) {
+ if (changedDuringListing != null) {
+ // Settled by start() once the listing is in place.
+ changedDuringListing.put(topicName, notification.getType());
+ return;
+ }
+ if (notification.getType() == NotificationType.Deleted) {
inFlightReads.remove(topicName);
if (currentSet.remove(topicName)) {
enqueueRemoved(topicName);
}
+ return;
}
- return;
}
// Created or Modified — fetch the new value to evaluate the filter against.
+ evaluateTopic(topicName);
+ }
+
+ /** Read the topic's record and add it to, or remove it from, the matching set accordingly. */
+ private void evaluateTopic(String topicName) {
long readId;
synchronized (currentSet) {
readId = ++lastReadId;
@@ -299,6 +329,13 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
if (closed.get()) {
return;
}
+ // The pending changes are relative to the snapshot's set: send them only after the
+ // snapshot frame, and leave them pending until then, so that a later change can still
+ // cancel them out. flushScheduled stays set, so nothing else gets scheduled meanwhile.
+ if (!snapshotEmitted.get()) {
+ scheduler.schedule(this::flushPending, COALESCE_WINDOW.toMillis(), TimeUnit.MILLISECONDS);
+ return;
+ }
Set<String> added;
Set<String> removed;
synchronized (coalesceLock) {
@@ -311,21 +348,6 @@ public class ScalableTopicsWatcherSession implements ScalableTopicResources.Name
if (added.isEmpty() && removed.isEmpty()) {
return;
}
- // Wait until the initial snapshot was emitted: any deltas that fire before the
- // snapshot is sent have already been folded into currentSet via onNotification's
- // wasInSet check (same set we built the snapshot from), so they're correctly
- // represented. We just need to send them AFTER the snapshot frame.
- if (!snapshotEmitted.get()) {
- // Re-defer: the snapshot future is short-lived, retry shortly.
- scheduler.schedule(this::flushPending, COALESCE_WINDOW.toMillis(), TimeUnit.MILLISECONDS);
- // Re-enqueue what we drained, since the next flush will rebuild from pending.
- synchronized (coalesceLock) {
- pendingAdded.addAll(added);
- pendingRemoved.addAll(removed);
- flushScheduled = true;
- }
- return;
- }
log.info().attr("added", added.size()).attr("removed", removed.size()).log("Pushing diff");
cnx.ctx().writeAndFlush(Commands.newWatchScalableTopicsDiff(watchId, added, removed));
}
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 4fb36c78015d..9a0a3c3ee48e 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
@@ -21,6 +21,7 @@ package org.apache.pulsar.broker.service.scalable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf;
@@ -34,9 +35,10 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
import org.apache.pulsar.broker.resources.ScalableTopicResources;
import org.apache.pulsar.broker.service.ServerCnx;
@@ -44,6 +46,7 @@ import org.apache.pulsar.common.api.proto.BaseCommand;
import org.apache.pulsar.common.api.proto.CommandWatchScalableTopicsUpdate;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.topics.TopicList;
import org.apache.pulsar.metadata.api.MetadataStoreConfig;
import org.apache.pulsar.metadata.api.Notification;
import org.apache.pulsar.metadata.api.NotificationType;
@@ -57,11 +60,13 @@ import org.testng.annotations.Test;
/**
* A namespace watch session must report a deleted topic as removed even when a metadata read it
* started for an earlier event of the same topic completes only after the deletion: that read
- * saw the record before it was deleted and must not bring the topic back.
+ * saw the record before it was deleted and must not bring the topic back. Likewise, the listing
+ * a session starts from must not undo the events it handled while the listing was in flight:
+ * the listing may have read the store before them.
*
- * <p>Each test makes the race deterministic: the session's reads are held until the record is
- * deleted and the session has handled the {@code Deleted} notification, and the coalesced diff
- * is flushed by hand afterwards.
+ * <p>Each test makes the race deterministic: the session's reads — and, at start, its listing —
+ * are held until the record has changed and the session has handled the notification, and the
+ * coalesced diff is flushed by hand afterwards.
*/
public class ScalableTopicsWatcherSessionDeleteRaceTest {
@@ -72,10 +77,17 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
private final Queue<Notification> handledNotifications = new ConcurrentLinkedQueue<>();
/** The topic set a client applying the session's Snapshot / Diff frames would hold. */
private final Set<String> clientView = ConcurrentHashMap.newKeySet();
+ private NamespaceName namespace;
+ private ServerCnx cnx;
+ private ChannelHandlerContext ctx;
+ private ScheduledExecutorService scheduler;
private ScalableTopicsWatcherSession session;
@BeforeMethod
public void setUp() throws Exception {
+ scheduledFlushes.clear();
+ handledNotifications.clear();
+ clientView.clear();
store = new LocalMemoryMetadataStore("memory:local", MetadataStoreConfig.builder().build());
resources = new HeldReadsResources(store);
// Registered after the resources' own listener, and notifications reach the listeners
@@ -83,21 +95,21 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
// has handled it.
store.registerListener(handledNotifications::add);
- ServerCnx cnx = mock(ServerCnx.class);
- ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
+ cnx = mock(ServerCnx.class);
+ ctx = mock(ChannelHandlerContext.class);
when(cnx.ctx()).thenReturn(ctx);
when(ctx.writeAndFlush(any())).thenAnswer(invocation -> {
applyFrame(invocation.getArgument(0));
return null;
});
- ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
+ scheduler = mock(ScheduledExecutorService.class);
when(scheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenAnswer(invocation -> {
scheduledFlushes.add(invocation.getArgument(0));
return null;
});
- NamespaceName ns = NamespaceName.get("tenant/ns-" + UUID.randomUUID().toString().substring(0, 8));
- session = new ScalableTopicsWatcherSession(1L, ns, Map.of(), null, cnx, resources, scheduler);
+ namespace = NamespaceName.get("tenant/ns-" + UUID.randomUUID().toString().substring(0, 8));
+ session = newSession(Map.of(), null);
}
@AfterMethod(alwaysRun = true)
@@ -160,15 +172,159 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
assertThat(clientView).as("topics after the delete").doesNotContain(tn.toString());
}
+ @Test
+ public void topicDeletedWhileTheListingIsInFlightIsNotKept() throws Exception {
+ TopicName tn = newTopic();
+ CompletableFuture<Void> started = startWithListingHeld();
+
+ resources.deleteScalableTopicAsync(tn).get();
+ awaitHandled(NotificationType.Deleted, resources.topicPath(tn));
+ applyListing(started);
+
+ assertThat(clientView).as("topics after the listing").isEmpty();
+ }
+
+ @Test
+ public void topicDeletedWhileTheListingIsInFlightIsNotKeptOnReconnect() throws Exception {
+ TopicName tn = newTopic();
+ // A client reconnecting with the topic in its set: its hash matches the listing.
+ clientView.add(tn.toString());
+ session = newSession(Map.of(), TopicList.calculateHash(List.of(tn.toString())));
+ CompletableFuture<Void> started = startWithListingHeld();
+
+ resources.deleteScalableTopicAsync(tn).get();
+ awaitHandled(NotificationType.Deleted, resources.topicPath(tn));
+ applyListing(started);
+
+ assertThat(clientView).as("topics after the listing").isEmpty();
+ }
+
+ @Test
+ public void topicCreatedWhileTheListingIsInFlightIsRemovedOnDelete() throws Exception {
+ CompletableFuture<Void> started = startWithListingHeld();
+ TopicName tn = newTopic();
+ applyListing(started);
+ assertThat(clientView).as("topics after the listing").containsExactly(tn.toString());
+
+ resources.deleteScalableTopicAsync(tn).get();
+ awaitHandled(NotificationType.Deleted, resources.topicPath(tn));
+ flushDiffs();
+
+ assertThat(clientView).as("topics after the delete").isEmpty();
+ }
+
+ @Test
+ public void topicLeavingTheFilterWhileTheListingIsInFlightIsNotKept() throws Exception {
+ session = newSession(Map.of("owner", "alice"), null);
+ TopicName tn = newTopic(Map.of("owner", "alice"));
+ CompletableFuture<Void> started = startWithListingHeld();
+
+ setOwner(tn, "bob");
+ applyListing(started);
+
+ assertThat(clientView).as("topics after the listing").isEmpty();
+ }
+
+ @Test
+ public void topicJoiningTheFilterWhileTheListingIsInFlightIsRemovedWhenItLeaves() throws Exception {
+ session = newSession(Map.of("owner", "alice"), null);
+ TopicName tn = newTopic(Map.of("owner", "bob"));
+ CompletableFuture<Void> started = startWithListingHeld();
+
+ setOwner(tn, "alice");
+ applyListing(started);
+ assertThat(clientView).as("topics after the listing").containsExactly(tn.toString());
+
+ setOwner(tn, "bob");
+ resources.releaseReads();
+ flushDiffs();
+
+ assertThat(clientView).as("topics after leaving the filter").isEmpty();
+ }
+
+ @Test
+ public void diffScheduledBeforeTheSnapshotIsWrittenFollowsIt() throws Exception {
+ TopicName tn = newTopic();
+ CompletableFuture<Void> started = startWithListingHeld();
+ // Once the session has applied the listing, which has the topic, and right before it writes
+ // the snapshot: delete the topic and run the flush this schedules.
+ AtomicBoolean deleted = new AtomicBoolean();
+ when(cnx.ctx()).thenAnswer(invocation -> {
+ if (deleted.compareAndSet(false, true)) {
+ resources.deleteScalableTopicAsync(tn).get();
+ awaitHandled(NotificationType.Deleted, resources.topicPath(tn));
+ assertThat(scheduledFlushes).as("flush scheduled by the delete").isNotEmpty();
+ for (int due = scheduledFlushes.size(); due > 0; due--) {
+ scheduledFlushes.remove().run();
+ }
+ }
+ return ctx;
+ });
+ applyListing(started);
+
+ assertThat(clientView).as("topics after the delete").isEmpty();
+ }
+
+ @Test
+ public void topicDeletedWhileAFlushWaitsForTheSnapshotIsNotKept() throws Exception {
+ CompletableFuture<Void> started = startWithListingHeld();
+ // Once the session has applied the listing, and right before it writes the snapshot: create a
+ // topic, so that its add is pending, and run the flush this schedules. The flush has to wait for
+ // the snapshot: delete the topic while it schedules itself again.
+ AtomicReference<TopicName> created = new AtomicReference<>();
+ AtomicBoolean deleteOnNextSchedule = new AtomicBoolean();
+ doAnswer(invocation -> {
+ if (deleteOnNextSchedule.compareAndSet(true, false)) {
+ resources.deleteScalableTopicAsync(created.get()).get();
+ awaitHandled(NotificationType.Deleted, resources.topicPath(created.get()));
+ }
+ scheduledFlushes.add(invocation.getArgument(0));
+ return null;
+ }).when(scheduler).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ when(cnx.ctx()).thenAnswer(invocation -> {
+ if (created.get() == null) {
+ created.set(newTopic());
+ resources.releaseReads();
+ assertThat(scheduledFlushes).as("flush scheduled by the create").isNotEmpty();
+ deleteOnNextSchedule.set(true);
+ for (int due = scheduledFlushes.size(); due > 0; due--) {
+ scheduledFlushes.remove().run();
+ }
+ }
+ return ctx;
+ });
+ applyListing(started);
+
+ assertThat(deleteOnNextSchedule).as("topic deleted while the flush waited").isFalse();
+ assertThat(clientView).as("topics after the delete").isEmpty();
+ }
+
+ private ScalableTopicsWatcherSession newSession(Map<String, String> propertyFilters, String clientHash) {
+ return new ScalableTopicsWatcherSession(1L, namespace, propertyFilters, clientHash, cnx, resources,
+ scheduler);
+ }
+
/** Create a topic record and wait until its {@code Created} notification was handled. */
private TopicName newTopic() throws Exception {
- TopicName tn = TopicName.get("topic://" + session.getNamespaceName() + "/t-"
- + UUID.randomUUID().toString().substring(0, 8));
- resources.createScalableTopicAsync(tn, ScalableTopicMetadata.builder().build()).get();
+ return newTopic(Map.of());
+ }
+
+ private TopicName newTopic(Map<String, String> properties) throws Exception {
+ TopicName tn = TopicName.get("topic://" + namespace + "/t-" + UUID.randomUUID().toString().substring(0, 8));
+ resources.createScalableTopicAsync(tn, ScalableTopicMetadata.builder().properties(properties).build()).get();
awaitHandled(NotificationType.Created, resources.topicPath(tn));
return tn;
}
+ /** Set the topic's {@code owner} property and wait until the {@code Modified} notification was handled. */
+ private void setOwner(TopicName tn, String owner) throws Exception {
+ resources.updateScalableTopicAsync(tn, md -> {
+ md.setProperties(Map.of("owner", owner));
+ return md;
+ }).get();
+ awaitHandled(NotificationType.Modified, resources.topicPath(tn));
+ }
+
/**
* Delete the topic record while the reads the session started are held, wait until the
* session has handled the {@code Deleted} notification, then let the reads complete and push
@@ -178,6 +334,34 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
resources.deleteScalableTopicAsync(tn).get();
awaitHandled(NotificationType.Deleted, resources.topicPath(tn));
resources.releaseReads();
+ flushDiffs();
+ }
+
+ /**
+ * Start the session with its reads and its initial listing held, and wait until the listing
+ * has read the store: it misses every change made from now on.
+ */
+ private CompletableFuture<Void> startWithListingHeld() throws Exception {
+ resources.holdReads();
+ resources.holdListing();
+ CompletableFuture<Void> started = session.start();
+ resources.awaitListingRead();
+ return started;
+ }
+
+ /**
+ * Let the reads the session started so far complete, then its listing, then the reads it
+ * started on applying the listing, and push the coalesced diff.
+ */
+ private void applyListing(CompletableFuture<Void> started) throws Exception {
+ resources.releaseReads();
+ resources.releaseListing();
+ started.get(10, TimeUnit.SECONDS);
+ resources.releaseReads();
+ flushDiffs();
+ }
+
+ private void flushDiffs() {
for (Runnable flush; (flush = scheduledFlushes.poll()) != null; ) {
flush.run();
}
@@ -218,39 +402,72 @@ public class ScalableTopicsWatcherSessionDeleteRaceTest {
}
/**
- * Holds back every topic-record read the session starts after {@link #holdReads()}: the
- * read goes to the store right away, so it sees the record as it is at that moment, but its
- * result reaches the session only on {@link #releaseReads()}, in the calling thread.
+ * Holds back the session's topic-record reads and its initial listing. A held read or listing
+ * goes to the store right away, so it sees the store as it is at that moment, but its result
+ * reaches the session only when released, in the releasing thread.
*/
private static class HeldReadsResources extends ScalableTopicResources {
- private final List<CompletableFuture<?>> heldReads = new CopyOnWriteArrayList<>();
- private volatile CompletableFuture<Void> release;
+ private record HeldRead(CompletableFuture<?> result, CompletableFuture<Void> release) {
+ }
+
+ private final Queue<HeldRead> heldReads = new ConcurrentLinkedQueue<>();
+ private volatile boolean holdReads;
+ private volatile CompletableFuture<Void> listingRelease;
+ private volatile CompletableFuture<List<String>> heldListing;
HeldReadsResources(MetadataStoreExtended store) {
super(store, 30);
}
+ /** From now on, hold each read until the next {@link #releaseReads()}. */
void holdReads() {
- release = new CompletableFuture<>();
+ holdReads = true;
}
+ /** Let the reads held so far reach the session, in the order they were started. */
void releaseReads() throws Exception {
- for (CompletableFuture<?> read : heldReads) {
- read.get(10, TimeUnit.SECONDS);
+ for (HeldRead read; (read = heldReads.poll()) != null; ) {
+ read.result().get(10, TimeUnit.SECONDS);
+ read.release().complete(null);
}
- release.complete(null);
+ }
+
+ /** Hold the next listing, until {@link #releaseListing()}. */
+ void holdListing() {
+ listingRelease = new CompletableFuture<>();
+ }
+
+ void awaitListingRead() throws Exception {
+ heldListing.get(10, TimeUnit.SECONDS);
+ }
+
+ void releaseListing() throws Exception {
+ awaitListingRead();
+ listingRelease.complete(null);
}
@Override
public CompletableFuture<Optional<ScalableTopicMetadata>> getScalableTopicMetadataAsync(TopicName tn,
boolean refresh) {
CompletableFuture<Optional<ScalableTopicMetadata>> read = super.getScalableTopicMetadataAsync(tn, refresh);
- CompletableFuture<Void> gate = release;
- if (gate == null) {
+ if (!holdReads) {
return read;
}
- heldReads.add(read);
- return gate.thenCompose(__ -> read);
+ CompletableFuture<Void> release = new CompletableFuture<>();
+ heldReads.add(new HeldRead(read, release));
+ return release.thenCompose(__ -> read);
+ }
+
+ @Override
+ public CompletableFuture<List<String>> findScalableTopicsByPropertiesAsync(NamespaceName ns,
+ Map<String, String> filters) {
+ CompletableFuture<List<String>> listing = super.findScalableTopicsByPropertiesAsync(ns, filters);
+ CompletableFuture<Void> release = listingRelease;
+ if (release == null) {
+ return listing;
+ }
+ heldListing = listing;
+ return release.thenCompose(__ -> listing);
}
}
}