You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@bifromq.apache.org by po...@apache.org on 2025/11/20 01:20:09 UTC
(bifromq) branch main updated: Fixes and improvements (#189)
This is an automated email from the ASF dual-hosted git repository.
popduke pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/bifromq.git
The following commit(s) were added to refs/heads/main by this push:
new 7d2f6d21a Fixes and improvements (#189)
7d2f6d21a is described below
commit 7d2f6d21a3e02c111e070bd02f98f762fc73a631
Author: Yonny(Yu) Hao <po...@gmail.com>
AuthorDate: Thu Nov 20 09:20:04 2025 +0800
Fixes and improvements (#189)
* Improved the deduplication mechanism on both accuracy and efficiency
* Fixed the issue that affected DistWorkerCleaner's adaptive behavior
* Improve InboxStoreCleaner to reduce running overhead on memory and timeliness
* Resolved an issue that may cause fetch stop by flipping connection
* Improved test stability and log output
---
.../BaseKVBalancerStateProposeTest.java | 6 +-
.../apache/bifromq/basekv/raft/PeerLogTracker.java | 11 +-
.../apache/bifromq/basekv/raft/RaftNodeState.java | 24 +-
.../bifromq/basekv/raft/RaftNodeStateLeader.java | 143 ++++++
.../basekv/raft/exception/CompactionException.java | 10 +-
.../basekv/raft/RaftNodeStateLeaderTest.java | 178 ++++++-
.../basekv/raft/functest/LogReplicationTest.java | 23 +-
.../src/test/resources/log4j2-test.xml | 2 +-
.../basekv/store/range/KVRangeDumpSession.java | 11 +-
.../bifromq/basekv/store/range/KVRangeFSM.java | 30 +-
.../basekv/store/range/KVRangeQueryRunner.java | 1 -
.../basekv/store/range/KVRangeRestorer.java | 26 +-
.../apache/bifromq/basekv/utils/BoundaryUtil.java | 15 +
base-rpc/base-rpc-client/pom.xml | 25 +
.../baserpc/client/ManagedMessageStream.java | 1 +
.../baserpc/client/ManagedRequestPipeline.java | 1 +
.../client/loadbalancer/SubChannelPicker.java | 6 +-
.../client/loadbalancer/SubChannelPickerTest.java | 176 +++++++
.../src/test/resources/log4j2-test.xml | 1 -
.../bifromq/dist/worker/DistWorkerCleaner.java | 97 ++--
.../bifromq/dist/worker/DistWorkerCoProc.java | 20 +-
.../apache/bifromq/dist/worker/TenantsStats.java | 1 -
.../bifromq/dist/worker/DistWorkerCleanerTest.java | 274 ++++++----
.../dist/worker/DistWorkerCoProcGCTest.java | 2 +-
.../bifromq/dist/worker/DistWorkerCoProcTest.java | 6 -
.../main/proto/inboxservice/InboxStoreCoProc.proto | 10 +
.../bifromq/inbox/server/InboxFetchPipeline.java | 25 +-
.../apache/bifromq/inbox/server/InboxWriter.java | 7 +-
.../server/InboxFetchPipelineMappingTest.java | 240 +++++++++
.../bifromq/inbox/store/schema/KVSchemaUtil.java | 10 +-
.../org/apache/bifromq/inbox/store/InboxStore.java | 37 +-
.../bifromq/inbox/store/InboxStoreBuilder.java | 3 +-
.../bifromq/inbox/store/InboxStoreCleaner.java | 197 ++++---
.../bifromq/inbox/store/InboxStoreCoProc.java | 162 ++++--
.../apache/bifromq/inbox/store/TenantsStats.java | 1 -
.../inbox/store/InboxAttachEnsureRecoverIT.java | 111 ++++
.../inbox/store/InboxDetachEnsureRecoverIT.java | 124 +++++
.../bifromq/inbox/store/InboxStoreCleanerTest.java | 565 +++++++++++++++++++++
.../apache/bifromq/inbox/store/InboxStoreTest.java | 3 +-
.../org/apache/bifromq/metrics/TenantMetric.java | 1 +
.../apache/bifromq/mqtt/handler/DedupCache.java | 159 ++++++
.../mqtt/handler/MQTTPersistentSessionHandler.java | 75 ++-
.../bifromq/mqtt/handler/MQTTSessionHandler.java | 70 ++-
.../mqtt/handler/MQTTTransientSessionHandler.java | 18 +-
.../mqtt/handler/v5/MQTT5MessageBuilders.java | 18 +-
.../mqtt/handler/v5/MQTT5ProtocolHelper.java | 6 +-
.../bifromq/mqtt/handler/DedupCacheTest.java | 169 ++++++
.../mqtt/handler/MQTTSessionStallEventTest.java | 212 ++++++++
.../v3/MQTT3PersistentSessionHandlerTest.java | 42 ++
.../handler/v5/PersistentSessionHandlerTest.java | 219 +++++++-
.../mqtt/integration/v3/MQTTLastWillTest.java | 19 +-
.../bifromq/plugin/eventcollector/EventType.java | 1 +
.../eventcollector/mqttbroker/SubStalled.java | 36 +-
.../sessiondict/client/SessionDictClient.java | 4 +-
.../sysprops/props/MaxActiveDedupChannels.java | 29 +-
.../props/MaxActiveDedupTopicsPerChannel.java | 29 +-
.../config/model/inbox/InboxStoreConfig.java | 4 +-
.../bifromq/starter/module/InboxServiceModule.java | 4 +-
58 files changed, 3156 insertions(+), 544 deletions(-)
diff --git a/base-kv/base-kv-meta-service/src/test/java/org/apache/bifromq/basekv/metaservice/BaseKVBalancerStateProposeTest.java b/base-kv/base-kv-meta-service/src/test/java/org/apache/bifromq/basekv/metaservice/BaseKVBalancerStateProposeTest.java
index bd17c2970..d29d083df 100644
--- a/base-kv/base-kv-meta-service/src/test/java/org/apache/bifromq/basekv/metaservice/BaseKVBalancerStateProposeTest.java
+++ b/base-kv/base-kv-meta-service/src/test/java/org/apache/bifromq/basekv/metaservice/BaseKVBalancerStateProposeTest.java
@@ -95,8 +95,10 @@ public class BaseKVBalancerStateProposeTest {
IBaseKVStoreBalancerStatesProposer statesProposer = metaService.balancerStatesProposer("test");
statesProposer.proposeRunState("balancer1", true).join();
statesProposer.clearProposedState("balancer1").join();
-
- Map<String, BalancerStateSnapshot> expected = statesProposal.expectedBalancerStates().blockingFirst();
+ Map<String, BalancerStateSnapshot> expected = statesProposal.expectedBalancerStates()
+ .filter(map -> !map.containsKey("balancer1"))
+ .timeout(2, TimeUnit.SECONDS)
+ .blockingFirst();
assertFalse(expected.containsKey("balancer1"));
}
}
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/PeerLogTracker.java b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/PeerLogTracker.java
index 7cfed35d7..692aaee55 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/PeerLogTracker.java
+++ b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/PeerLogTracker.java
@@ -14,18 +14,19 @@
* "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.
+ * under the License.
*/
package org.apache.bifromq.basekv.raft;
-import org.apache.bifromq.basekv.raft.event.SyncStateChangedEvent;
-import org.apache.bifromq.basekv.raft.proto.RaftNodeSyncState;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
+import org.apache.bifromq.basekv.raft.event.SyncStateChangedEvent;
+import org.apache.bifromq.basekv.raft.proto.RaftNodeSyncState;
import org.slf4j.Logger;
class PeerLogTracker {
@@ -71,6 +72,10 @@ class PeerLogTracker {
return replicators.containsKey(peerId);
}
+ public Set<String> peers() {
+ return Collections.unmodifiableSet(replicators.keySet());
+ }
+
public void stopTracking(Set<String> peerIds) {
boolean notity = false;
for (String peerId : peerIds) {
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeState.java b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeState.java
index c6220f486..4149bd7f9 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeState.java
+++ b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeState.java
@@ -185,19 +185,27 @@ abstract class RaftNodeState implements IRaftNodeState {
.setTerm(compactEntry.map(LogEntry::getTerm).orElse(stateStorage.latestSnapshot().getTerm()))
.setData(fsmSnapshot)
.build();
- try {
- long firstIndex = stateStorage.firstIndex();
- stateStorage.applySnapshot(newSnapshot);
- log.debug("Compacted entries[{},{}]", firstIndex, compactIndex);
- onDone.complete(null);
- } catch (Throwable e) {
- onDone.completeExceptionally(new CompactionException("Failed to apply snapshot", e));
- }
+ onSnapshotReady(newSnapshot, onDone);
} else {
onDone.completeExceptionally(CompactionException.staleSnapshot());
}
}
+ protected void onSnapshotReady(Snapshot snapshot, CompletableFuture<Void> onDone) {
+ applySnapshot(snapshot, onDone);
+ }
+
+ protected final void applySnapshot(Snapshot snapshot, CompletableFuture<Void> onDone) {
+ try {
+ long firstIndex = stateStorage.firstIndex();
+ stateStorage.applySnapshot(snapshot);
+ log.debug("Compacted entries[{},{}]", firstIndex, snapshot.getIndex());
+ onDone.complete(null);
+ } catch (Throwable e) {
+ onDone.completeExceptionally(new CompactionException("Failed to apply snapshot", e));
+ }
+ }
+
protected Set<String> voters() {
ClusterConfig clusterConfig = stateStorage.latestClusterConfig();
Set<String> voters = new HashSet<>(clusterConfig.getVotersList());
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeader.java b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeader.java
index 24381d1a7..fa0c3209a 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeader.java
+++ b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeader.java
@@ -25,10 +25,13 @@ import static org.apache.bifromq.basekv.raft.RaftConfigChanger.State.JointConfig
import static org.apache.bifromq.basekv.raft.RaftConfigChanger.State.TargetConfigCommitting;
import com.google.protobuf.ByteString;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -62,7 +65,9 @@ class RaftNodeStateLeader extends RaftNodeState {
private final PeerLogTracker peerLogTracker;
private final RaftConfigChanger configChanger;
private final ReadProgressTracker readProgressTracker;
+ private final Deque<SnapshotTask> pendingCompactions = new ArrayDeque<>();
private LeaderTransferTask leaderTransferTask;
+ private PendingCompaction activeCompaction;
private int electionElapsedTick;
RaftNodeStateLeader(long term,
@@ -142,6 +147,7 @@ class RaftNodeStateLeader extends RaftNodeState {
onSnapshotInstalled,
tags);
abortPendingRequests(AbortReason.LeaderStepDown);
+ checkPendingCompaction(true);
return nextState;
}
@@ -154,6 +160,7 @@ class RaftNodeStateLeader extends RaftNodeState {
RaftNodeState tick() {
electionElapsedTick++;
peerLogTracker.tick();
+ onPendingCompactionTick();
if (configChanger.tick(currentTerm())) {
// there is a state change after tick
if (configChanger.state() == JointConfigCommitting
@@ -194,6 +201,7 @@ class RaftNodeStateLeader extends RaftNodeState {
// step down as a follower and abort any pending futures
log.warn("Quorum check failed[{}], leader stepped down to follower", quorumCheckResult);
abortPendingRequests(AbortReason.LeaderStepDown);
+ checkPendingCompaction(true);
return new RaftNodeStateFollower(
currentTerm(), // update term
commitIndex,
@@ -213,6 +221,7 @@ class RaftNodeStateLeader extends RaftNodeState {
if (!appendEntriesToSend.isEmpty()) {
submitRaftMessages(appendEntriesToSend);
}
+ checkPendingCompaction(false);
return this;
}
@@ -253,9 +262,16 @@ class RaftNodeStateLeader extends RaftNodeState {
// update self progress
log.trace("Log entries before index[{}] stabilized", stabledIndex);
peerLogTracker.confirmMatch(stateStorage.local(), stabledIndex);
+ checkPendingCompaction(false);
return commit();
}
+ @Override
+ protected void onSnapshotReady(Snapshot snapshot, CompletableFuture<Void> onDone) {
+ pendingCompactions.addLast(new SnapshotTask(snapshot, onDone));
+ scheduleCompactionQueue();
+ }
+
@Override
void readIndex(CompletableFuture<Long> onDone) {
// if no commit in current term
@@ -325,6 +341,7 @@ class RaftNodeStateLeader extends RaftNodeState {
log.debug("Got higher term[{}] message[{}] from peer[{}], start to step down",
message.getTerm(), message.getMessageTypeCase(), fromPeer);
abortPendingRequests(AbortReason.LeaderStepDown);
+ checkPendingCompaction(true);
nextState = new RaftNodeStateFollower(
message.getTerm(), // update term
commitIndex,
@@ -410,6 +427,7 @@ class RaftNodeStateLeader extends RaftNodeState {
public void stop() {
super.stop();
abortPendingRequests(AbortReason.Cancelled);
+ checkPendingCompaction(true);
}
private RaftNodeState handleAppendEntriesReply(String fromPeer, AppendEntriesReply reply) {
@@ -429,6 +447,7 @@ class RaftNodeStateLeader extends RaftNodeState {
log.debug("Follower[{}] with last entry[index:{},term:{}] rejected entries appending from index[{}]",
fromPeer, reject.getLastIndex(), reject.getTerm(), reject.getRejectedIndex());
peerLogTracker.backoff(fromPeer, reject.getRejectedIndex(), reject.getLastIndex());
+ checkPendingCompaction(false);
List<RaftMessage> messages = prepareAppendEntriesForPeer(fromPeer, true);
submitRaftMessages(fromPeer, messages);
return this;
@@ -437,6 +456,7 @@ class RaftNodeStateLeader extends RaftNodeState {
log.trace("Follower[{}] accepted entries, and advance match index[{}]",
fromPeer, accept.getLastIndex());
peerLogTracker.confirmMatch(fromPeer, accept.getLastIndex());
+ checkPendingCompaction(false);
if (leaderTransferTask != null && fromPeer.equals(leaderTransferTask.nextLeader)
&& peerLogTracker.matchIndex(fromPeer) == stateStorage.lastIndex()) {
log.info("Started leadership transfer by sending TimeoutNow to follower[{}]", fromPeer);
@@ -464,10 +484,12 @@ class RaftNodeStateLeader extends RaftNodeState {
log.debug("Follower[{}] rejected snapshot with last entry of index[{}]",
fromPeer, reply.getLastIndex());
peerLogTracker.backoff(fromPeer, reply.getLastIndex(), reply.getLastIndex());
+ checkPendingCompaction(false);
return this;
} else {
log.debug("Follower[{}] installed snapshot, advance last index[{}]", fromPeer, reply.getLastIndex());
peerLogTracker.confirmMatch(fromPeer, reply.getLastIndex());
+ checkPendingCompaction(false);
return commit();
}
}
@@ -505,6 +527,7 @@ class RaftNodeStateLeader extends RaftNodeState {
snapshot.getIndex(), snapshot.getTerm(), peer);
// there is a new snapshot generated, reset the tracker explicitly using previous snapshot
peerLogTracker.backoff(peer, peerLogTracker.matchIndex(peer), peerLogTracker.matchIndex(peer));
+ checkPendingCompaction(false);
}
break;
}
@@ -831,6 +854,56 @@ class RaftNodeStateLeader extends RaftNodeState {
}
}
+ private void checkPendingCompaction(boolean force) {
+ PendingCompaction pending = activeCompaction;
+ if (pending == null) {
+ return;
+ }
+ if (force) {
+ log.debug("Force finish pending compaction at index[{}]", pending.snapshot.getIndex());
+ completePendingCompaction(pending);
+ return;
+ }
+ pending.refresh();
+ if (pending.isDone()) {
+ completePendingCompaction(pending);
+ }
+ }
+
+ private void onPendingCompactionTick() {
+ PendingCompaction pending = activeCompaction;
+ if (pending != null) {
+ pending.onTick();
+ }
+ }
+
+ private void completePendingCompaction(PendingCompaction pending) {
+ if (activeCompaction != pending) {
+ return;
+ }
+ activeCompaction = null;
+ applySnapshot(pending.snapshot, pending.onDone);
+ scheduleCompactionQueue();
+ }
+
+ private void scheduleCompactionQueue() {
+ if (activeCompaction != null) {
+ return;
+ }
+ while (!pendingCompactions.isEmpty()) {
+ SnapshotTask task = pendingCompactions.pollFirst();
+ PendingCompaction pending = new PendingCompaction(task.snapshot, task.onDone);
+ if (pending.isDone()) {
+ applySnapshot(task.snapshot, task.onDone);
+ continue;
+ }
+ log.debug("Delay compaction at index[{}] until peers{} catch up", task.snapshot.getIndex(),
+ pending.waitingPeers);
+ activeCompaction = pending;
+ break;
+ }
+ }
+
private enum AbortReason {
LeaderStepDown,
Cancelled
@@ -853,4 +926,74 @@ class RaftNodeStateLeader extends RaftNodeState {
onDone.complete(null);
}
}
+
+ private static final class SnapshotTask {
+ final Snapshot snapshot;
+ final CompletableFuture<Void> onDone;
+
+ SnapshotTask(Snapshot snapshot, CompletableFuture<Void> onDone) {
+ this.snapshot = snapshot;
+ this.onDone = onDone;
+ }
+ }
+
+ private final class PendingCompaction {
+ final Snapshot snapshot;
+ final CompletableFuture<Void> onDone;
+ final Set<String> waitingPeers = new HashSet<>();
+ final Map<String, Integer> waitTicks = new HashMap<>();
+
+ PendingCompaction(Snapshot snapshot, CompletableFuture<Void> onDone) {
+ this.snapshot = snapshot;
+ this.onDone = onDone;
+ long targetIndex = snapshot.getIndex();
+ for (String peer : peerLogTracker.peers()) {
+ if (peer.equals(stateStorage.local())) {
+ continue;
+ }
+ if (peerLogTracker.status(peer) == RaftNodeSyncState.Replicating
+ && peerLogTracker.matchIndex(peer) < targetIndex) {
+ waitingPeers.add(peer);
+ waitTicks.put(peer, 0);
+ }
+ }
+ }
+
+ void onTick() {
+ waitingPeers.forEach(peer -> waitTicks.merge(peer, 1, Integer::sum));
+ }
+
+ void refresh() {
+ Iterator<String> itr = waitingPeers.iterator();
+ while (itr.hasNext()) {
+ String peer = itr.next();
+ if (!peerLogTracker.isTracking(peer)) {
+ itr.remove();
+ waitTicks.remove(peer);
+ continue;
+ }
+ if (peerLogTracker.status(peer) != RaftNodeSyncState.Replicating) {
+ itr.remove();
+ waitTicks.remove(peer);
+ continue;
+ }
+ if (peerLogTracker.matchIndex(peer) >= snapshot.getIndex()) {
+ itr.remove();
+ waitTicks.remove(peer);
+ continue;
+ }
+ int elapsed = waitTicks.getOrDefault(peer, 0);
+ if (elapsed >= config.getElectionTimeoutTick()) {
+ itr.remove();
+ waitTicks.remove(peer);
+ log.debug("Follower[{}] wait timeout for pending compaction at index[{}]", peer,
+ snapshot.getIndex());
+ }
+ }
+ }
+
+ boolean isDone() {
+ return waitingPeers.isEmpty();
+ }
+ }
}
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
index 800fd4d8a..d7fd40dab 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
+++ b/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
@@ -14,16 +14,12 @@
* "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.
+ * under the License.
*/
package org.apache.bifromq.basekv.raft.exception;
public class CompactionException extends RuntimeException {
- public static StaleSnapshotException staleSnapshot() {
- return new StaleSnapshotException();
- }
-
public CompactionException(String message, Throwable cause) {
super(message, cause);
}
@@ -32,6 +28,10 @@ public class CompactionException extends RuntimeException {
super(message);
}
+ public static StaleSnapshotException staleSnapshot() {
+ return new StaleSnapshotException();
+ }
+
public static class StaleSnapshotException extends CompactionException {
private StaleSnapshotException() {
super("Stale Snapshot");
diff --git a/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeaderTest.java b/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeaderTest.java
index 70e9ab345..2ec207880 100644
--- a/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeaderTest.java
+++ b/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/RaftNodeStateLeaderTest.java
@@ -14,17 +14,32 @@
* "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.
+ * under the License.
*/
package org.apache.bifromq.basekv.raft;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
+import com.google.protobuf.ByteString;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.bifromq.basekv.raft.event.CommitEvent;
import org.apache.bifromq.basekv.raft.event.ElectionEvent;
import org.apache.bifromq.basekv.raft.event.RaftEventType;
@@ -42,17 +57,9 @@ import org.apache.bifromq.basekv.raft.proto.RaftNodeSyncState;
import org.apache.bifromq.basekv.raft.proto.RequestVote;
import org.apache.bifromq.basekv.raft.proto.Snapshot;
import org.apache.bifromq.basekv.raft.proto.TimeoutNow;
-import com.google.protobuf.ByteString;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.atomic.AtomicInteger;
+import org.mockito.AdditionalAnswers;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -91,7 +98,8 @@ public class RaftNodeStateLeaderTest extends RaftNodeStateTest {
// 1 targetConfigEntry
// 2 commandEntry
// commitIndex = 2, compact all entries
- leader.compact(ByteString.copyFromUtf8("appSMSnapshot"), 2, new CompletableFuture<>());
+ CompletableFuture<Void> compactDone = new CompletableFuture<>();
+ leader.compact(ByteString.copyFromUtf8("appSMSnapshot"), 2, compactDone);
// tick to heartbeat, send empty appendEntry to v1 and v2
leader.tick();
@@ -125,11 +133,13 @@ public class RaftNodeStateLeaderTest extends RaftNodeStateTest {
.build())
.build();
leader.receive("v2", appendEntriesReplyRejected);
+ compactDone.join();
+ // follower rejects again after leader probes with truncated log, then switches to snapshot syncing
+ leader.receive("v2", appendEntriesReplyRejected);
assertSame(peerLogTracker.status("v2"), RaftNodeSyncState.SnapshotSyncing);
// tick to heartbeat, send empty appendEntry to v1 and send snapshot to v2
leader.tick();
leader.tick();
- leader.tick();
// v2 responds to installSnapshot normally, and state of the log tracker change to Probing
@@ -144,6 +154,108 @@ public class RaftNodeStateLeaderTest extends RaftNodeStateTest {
assertSame(peerLogTracker.status("v2"), RaftNodeSyncState.Replicating);
}
+ @Test
+ public void testCompactWaitsUntilReplicatingFollowerCatchesUp() {
+ IRaftStateStore delegate = new InMemoryStateStore("testLocal", Snapshot.newBuilder()
+ .setClusterConfig(clusterConfig).build());
+ IRaftStateStore stateStorage = Mockito.mock(IRaftStateStore.class, AdditionalAnswers.delegatesTo(delegate));
+ RaftNodeStateLeader leader = startUpLeader(stateStorage, null);
+ long compactIndex = prepareCommittedEntryBehindLearner(leader, stateStorage);
+ CompletableFuture<Void> onCompact = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, onCompact);
+ assertFalse(onCompact.isDone());
+ verify(stateStorage, never()).applySnapshot(any(Snapshot.class));
+ leader.receive("l1", acceptReply(compactIndex));
+ assertTrue(onCompact.isDone());
+ ArgumentCaptor<Snapshot> snapshotCaptor = ArgumentCaptor.forClass(Snapshot.class);
+ verify(stateStorage, times(1)).applySnapshot(snapshotCaptor.capture());
+ assertEquals(snapshotCaptor.getValue().getIndex(), compactIndex);
+ }
+
+ @Test
+ public void testCompactCompletesWhenReplicatingFollowerFallsBehind() {
+ IRaftStateStore delegate = new InMemoryStateStore("testLocal", Snapshot.newBuilder()
+ .setClusterConfig(clusterConfig).build());
+ IRaftStateStore stateStorage = Mockito.mock(IRaftStateStore.class, AdditionalAnswers.delegatesTo(delegate));
+ RaftNodeStateLeader leader = startUpLeader(stateStorage, null);
+ long compactIndex = prepareCommittedEntryBehindLearner(leader, stateStorage);
+ CompletableFuture<Void> onCompact = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, onCompact);
+ assertFalse(onCompact.isDone());
+
+ leader.receive("l1", rejectReply(compactIndex, compactIndex - 1));
+ assertTrue(onCompact.isDone());
+ ArgumentCaptor<Snapshot> snapshotCaptor = ArgumentCaptor.forClass(Snapshot.class);
+ verify(stateStorage, times(1)).applySnapshot(snapshotCaptor.capture());
+ assertEquals(snapshotCaptor.getValue().getIndex(), compactIndex);
+ }
+
+ @Test
+ public void testCompactForcedWhenReelectionHappens() {
+ IRaftStateStore delegate = new InMemoryStateStore("testLocal", Snapshot.newBuilder()
+ .setClusterConfig(clusterConfig).build());
+ IRaftStateStore stateStorage = Mockito.mock(IRaftStateStore.class, AdditionalAnswers.delegatesTo(delegate));
+ RaftNodeStateLeader leader = startUpLeader(stateStorage, null);
+ long compactIndex = prepareCommittedEntryBehindLearner(leader, stateStorage);
+ CompletableFuture<Void> onCompact = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, onCompact);
+ assertFalse(onCompact.isDone());
+
+ leader.receive("v2", RaftMessage.newBuilder()
+ .setTerm(2)
+ .setRequestVote(RequestVote.newBuilder().setCandidateId("v2").build())
+ .build());
+ assertTrue(onCompact.isDone());
+ ArgumentCaptor<Snapshot> snapshotCaptor = ArgumentCaptor.forClass(Snapshot.class);
+ verify(stateStorage, times(1)).applySnapshot(snapshotCaptor.capture());
+ assertEquals(snapshotCaptor.getValue().getIndex(), compactIndex);
+ }
+
+ @Test
+ public void testCompactQueuedWhenAnotherIsPending() {
+ IRaftStateStore delegate = new InMemoryStateStore("testLocal", Snapshot.newBuilder()
+ .setClusterConfig(clusterConfig).build());
+ IRaftStateStore stateStorage = Mockito.mock(IRaftStateStore.class, AdditionalAnswers.delegatesTo(delegate));
+ RaftNodeStateLeader leader = startUpLeader(stateStorage, null);
+ long compactIndex = prepareCommittedEntryBehindLearner(leader, stateStorage);
+ CompletableFuture<Void> first = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, first);
+ assertFalse(first.isDone());
+
+ CompletableFuture<Void> second = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, second);
+ assertFalse(second.isDone());
+
+ leader.receive("l1", acceptReply(compactIndex));
+ assertTrue(first.isDone());
+ assertTrue(second.isDone());
+ ArgumentCaptor<Snapshot> snapshotCaptor = ArgumentCaptor.forClass(Snapshot.class);
+ verify(stateStorage, times(2)).applySnapshot(snapshotCaptor.capture());
+ snapshotCaptor.getAllValues().forEach(snapshot -> assertEquals(snapshot.getIndex(), compactIndex));
+ }
+
+ @Test
+ public void testCompactCompletesAfterReplicatingFollowerWaitTimeout() {
+ IRaftStateStore delegate = new InMemoryStateStore("testLocal", Snapshot.newBuilder()
+ .setClusterConfig(clusterConfig).build());
+ IRaftStateStore stateStorage = Mockito.mock(IRaftStateStore.class, AdditionalAnswers.delegatesTo(delegate));
+ RaftNodeStateLeader leader = startUpLeader(stateStorage, null);
+ long compactIndex = prepareCommittedEntryBehindLearner(leader, stateStorage);
+ CompletableFuture<Void> onCompact = new CompletableFuture<>();
+ leader.compact(ByteString.EMPTY, compactIndex, onCompact);
+ assertFalse(onCompact.isDone());
+
+ for (int i = 0; i < defaultRaftConfig.getElectionTimeoutTick(); i++) {
+ leader.tick();
+ leader.receive("l1", acceptReply(compactIndex - 1));
+ }
+
+ assertTrue(onCompact.isDone());
+ ArgumentCaptor<Snapshot> snapshotCaptor = ArgumentCaptor.forClass(Snapshot.class);
+ verify(stateStorage, times(1)).applySnapshot(snapshotCaptor.capture());
+ assertEquals(snapshotCaptor.getValue().getIndex(), compactIndex);
+ }
+
@Test
public void testProposeExceptionally() {
RaftNodeStateLeader proposeThrottledLeader = startUpLeader();
@@ -339,6 +451,42 @@ public class RaftNodeStateLeaderTest extends RaftNodeStateTest {
assertTrue(onDone.isCompletedExceptionally());
}
+ private long prepareCommittedEntryBehindLearner(RaftNodeStateLeader leader, IRaftStateStore stateStorage) {
+ leader.receive("l1", acceptReply(stateStorage.lastIndex()));
+ CompletableFuture<Long> proposalDone = new CompletableFuture<>();
+ leader.propose(command, proposalDone);
+ long newIndex = stateStorage.lastIndex();
+ RaftMessage accept = acceptReply(newIndex);
+ leader.receive("v1", accept);
+ leader.receive("v2", accept);
+ assertTrue(proposalDone.isDone());
+ return newIndex;
+ }
+
+ private RaftMessage acceptReply(long lastIndex) {
+ return RaftMessage.newBuilder()
+ .setTerm(1)
+ .setAppendEntriesReply(AppendEntriesReply.newBuilder()
+ .setAccept(AppendEntriesReply.Accept.newBuilder()
+ .setLastIndex(lastIndex)
+ .build())
+ .build())
+ .build();
+ }
+
+ private RaftMessage rejectReply(long rejectedIndex, long lastIndex) {
+ return RaftMessage.newBuilder()
+ .setTerm(1)
+ .setAppendEntriesReply(AppendEntriesReply.newBuilder()
+ .setReject(AppendEntriesReply.Reject.newBuilder()
+ .setTerm(1)
+ .setRejectedIndex(rejectedIndex)
+ .setLastIndex(lastIndex)
+ .build())
+ .build())
+ .build();
+ }
+
@Test
public void testChangeClusterConfig() {
RaftNodeStateLeader leader = startUpLeader();
@@ -638,4 +786,4 @@ public class RaftNodeStateLeaderTest extends RaftNodeStateTest {
itr.forEachRemaining(entries::add);
return entries;
}
-}
\ No newline at end of file
+}
diff --git a/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/functest/LogReplicationTest.java b/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/functest/LogReplicationTest.java
index 42ebbf0a2..3de6ecf96 100644
--- a/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/functest/LogReplicationTest.java
+++ b/base-kv/base-kv-raft/src/test/java/org/apache/bifromq/basekv/raft/functest/LogReplicationTest.java
@@ -14,22 +14,21 @@
* "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.
+ * under the License.
*/
package org.apache.bifromq.basekv.raft.functest;
-import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
-import org.apache.bifromq.basekv.raft.functest.annotation.Cluster;
-import org.apache.bifromq.basekv.raft.functest.template.SharedRaftConfigTestTemplate;
-import org.apache.bifromq.basekv.raft.proto.RaftNodeSyncState;
import com.google.protobuf.ByteString;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
+import org.apache.bifromq.basekv.raft.functest.annotation.Cluster;
+import org.apache.bifromq.basekv.raft.functest.template.SharedRaftConfigTestTemplate;
+import org.apache.bifromq.basekv.raft.proto.RaftNodeSyncState;
import org.testng.annotations.Test;
@Slf4j
@@ -124,8 +123,16 @@ public class LogReplicationTest extends SharedRaftConfigTestTemplate {
fail();
}
}
- assertEquals(group.syncStateLogs(slowFollower),
- Arrays.asList(RaftNodeSyncState.Probing, RaftNodeSyncState.Replicating,
- RaftNodeSyncState.SnapshotSyncing, RaftNodeSyncState.Replicating));
+ assertTrue(statusLog.equals(Arrays.asList(
+ RaftNodeSyncState.Probing,
+ RaftNodeSyncState.Replicating,
+ RaftNodeSyncState.SnapshotSyncing,
+ RaftNodeSyncState.Replicating)) || statusLog.equals(Arrays.asList(
+ RaftNodeSyncState.Probing,
+ RaftNodeSyncState.Replicating,
+ RaftNodeSyncState.Probing,
+ RaftNodeSyncState.SnapshotSyncing,
+ RaftNodeSyncState.Replicating)),
+ "Unexpected sync state transitions: " + statusLog);
}
}
diff --git a/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml b/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml
index 9f7137626..f1e262ce0 100644
--- a/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml
+++ b/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml
@@ -29,7 +29,7 @@
</Console>
</Appenders>
<Loggers>
- <Logger name="org.apache.bifromq.basekv.raft" level="DEBUG"/>
+ <Logger name="org.apache.bifromq.basekv.raft" level="INFO"/>
<Root level="INFO">
<AppenderRef ref="CONSOLE"/>
</Root>
diff --git a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeDumpSession.java b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeDumpSession.java
index cc70dcd00..96560a448 100644
--- a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeDumpSession.java
+++ b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeDumpSession.java
@@ -52,6 +52,7 @@ class KVRangeDumpSession {
private static final int MAX_CHUNK_BYTES = 2 * 1024 * 1024;
private static final double TARGET_ROUND_TRIP_NANOS = Duration.ofMillis(70).toNanos();
private static final double EMA_ALPHA = 0.2d;
+ private static final long PROGRESS_LOG_INTERVAL_NANOS = Duration.ofSeconds(5).toNanos();
private final Logger log;
private final String sessionId;
private final KVRangeSnapshot snapshot;
@@ -72,6 +73,7 @@ class KVRangeDumpSession {
private long totalEntries = 0;
private long totalBytes = 0;
private long lastSendTS;
+ private long lastProgressLogTS = startDumpTS;
private double buildTimeEwma = TARGET_ROUND_TRIP_NANOS;
private double roundTripEwma = TARGET_ROUND_TRIP_NANOS;
private int chunkHint;
@@ -301,9 +303,12 @@ class KVRangeDumpSession {
"Dump snapshot completed: sessionId={}, follower={}, totalEntries={}, totalBytes={}, cost={}ms",
sessionId, receiverStoreId, totalEntries, totalBytes,
TimeUnit.NANOSECONDS.toMillis(now - startDumpTS));
- } else {
- log.info("Dump snapshot data: sessionId={}, follower={}, entries={}, bytes={}",
- sessionId, receiverStoreId, reqBuilder.getKvCount(), dumpBytes);
+ } else if (now - lastProgressLogTS >= PROGRESS_LOG_INTERVAL_NANOS) {
+ log.info(
+ "Dump snapshot progress: sessionId={}, follower={}, totalEntries={}, totalBytes={}, elapsed={}ms",
+ sessionId, receiverStoreId, totalEntries, totalBytes,
+ TimeUnit.NANOSECONDS.toMillis(now - startDumpTS));
+ lastProgressLogTS = now;
}
messenger.send(currentRequest);
if (currentRequest.getSaveSnapshotDataRequest().getFlag() == SaveSnapshotDataRequest.Flag.Error) {
diff --git a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeFSM.java b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeFSM.java
index 1a9b609db..c57d75ae4 100644
--- a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeFSM.java
+++ b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeFSM.java
@@ -75,6 +75,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
@@ -547,15 +548,11 @@ public class KVRangeFSM implements IKVRangeFSM {
return CompletableFuture.failedFuture(
new KVRangeException.InternalException("Range not open:" + KVRangeIdUtil.toString(id)));
}
- return changeReplicaConfig(nextTaskId(), ver, newVoters, newLearners);
- }
-
- private CompletableFuture<Void> changeReplicaConfig(String taskId,
- long ver,
- Set<String> newVoters,
- Set<String> newLearners) {
+ if (!dumpSessions.isEmpty()) {
+ return CompletableFuture.failedFuture(new KVRangeException.TryLater("Range is dumping data, try later"));
+ }
return metricManager.recordConfigChange(() -> submitManagementCommand(KVRangeCommand.newBuilder()
- .setTaskId(taskId)
+ .setTaskId(nextTaskId())
.setVer(ver)
.setChangeConfig(ChangeConfig.newBuilder()
.addAllVoters(newVoters)
@@ -566,6 +563,9 @@ public class KVRangeFSM implements IKVRangeFSM {
@Override
public CompletableFuture<Void> split(long ver, ByteString splitKey) {
+ if (!dumpSessions.isEmpty()) {
+ return CompletableFuture.failedFuture(new KVRangeException.TryLater("Range is dumping data, try later"));
+ }
return metricManager.recordSplit(() -> submitManagementCommand(KVRangeCommand.newBuilder()
.setTaskId(nextTaskId())
.setVer(ver)
@@ -578,6 +578,9 @@ public class KVRangeFSM implements IKVRangeFSM {
@Override
public CompletableFuture<Void> merge(long ver, KVRangeId mergeeId, Set<String> mergeeVoters) {
+ if (!dumpSessions.isEmpty()) {
+ return CompletableFuture.failedFuture(new KVRangeException.TryLater("Range is dumping data, try later"));
+ }
return metricManager.recordMerge(() -> submitManagementCommand(KVRangeCommand.newBuilder()
.setTaskId(nextTaskId())
.setVer(ver)
@@ -866,7 +869,10 @@ public class KVRangeFSM implements IKVRangeFSM {
.setType(Normal)
.setTaskId(taskId)
.build());
- return () -> compactWAL().thenRunAsync(() -> finishCommand(taskId), fsmExecutor);
+ return () -> {
+ finishCommand(taskId);
+ return CompletableFuture.completedFuture(null);
+ };
}
} else {
rangeWriter.state(State.newBuilder()
@@ -2018,7 +2024,9 @@ public class KVRangeFSM implements IKVRangeFSM {
return wal.compact(snapshot)
.whenComplete((v, e) -> {
if (e != null) {
- log.error("Failed to compact WAL due to {}: \n{}", e.getMessage(), snapshot);
+ Throwable cause = e instanceof CompletionException && e.getCause() != null
+ ? e.getCause() : e;
+ log.error("Failed to compact WAL due to {}: \n{}", cause.getMessage(), snapshot);
}
});
});
@@ -2346,6 +2354,7 @@ public class KVRangeFSM implements IKVRangeFSM {
}, tags);
dumpSessions.put(session.id(), session);
session.awaitDone().whenComplete((result, e) -> {
+ dumpSessions.remove(session.id(), session);
switch (result) {
case OK -> log.info("Snapshot dumped: session={}, follower={}", session.id(), targetStoreId);
case Canceled ->
@@ -2360,7 +2369,6 @@ public class KVRangeFSM implements IKVRangeFSM {
// do nothing
}
}
- dumpSessions.remove(session.id(), session);
});
}
diff --git a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeQueryRunner.java b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeQueryRunner.java
index 80bb78fc7..e5734351a 100644
--- a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeQueryRunner.java
+++ b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeQueryRunner.java
@@ -188,7 +188,6 @@ class KVRangeQueryRunner implements IKVRangeQueryRunner {
new KVRangeException.TryLater("Range has been in state: " + state.getType().name().toLowerCase()));
return onDone;
}
- refreshableReader.refresh();
return queryFn.apply(refreshableReader)
.whenCompleteAsync((v, e) -> {
queryLock.unlockRead(stamp);
diff --git a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeRestorer.java b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeRestorer.java
index 113536611..a122e2d26 100644
--- a/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeRestorer.java
+++ b/base-kv/base-kv-store-server/src/main/java/org/apache/bifromq/basekv/store/range/KVRangeRestorer.java
@@ -19,6 +19,7 @@
package org.apache.bifromq.basekv.store.range;
+import java.time.Duration;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -33,6 +34,7 @@ import org.apache.bifromq.logger.MDCLogger;
import org.slf4j.Logger;
class KVRangeRestorer {
+ private static final long PROGRESS_LOG_INTERVAL_NANOS = Duration.ofSeconds(5).toNanos();
private final Logger log;
private final IKVRange range;
private final IKVRangeMessenger messenger;
@@ -84,9 +86,18 @@ class KVRangeRestorer {
CompletableFuture<Void> onDone = session.doneFuture;
long startNanos = System.nanoTime();
try {
- IKVRangeRestoreSession restoreSession = range.startRestore(rangeSnapshot, (count, bytes) ->
- log.info("Received snapshot data: session={}, leader={}, entries={}, bytes={}",
- session.id, leader, count, bytes));
+ IKVRangeRestoreSession restoreSession = range.startRestore(rangeSnapshot, (count, bytes) -> {
+ session.totalEntries += count;
+ session.totalBytes += bytes;
+ long now = System.nanoTime();
+ if (now - session.lastProgressLogTS >= PROGRESS_LOG_INTERVAL_NANOS) {
+ log.info(
+ "Restore snapshot progress: sessionId={}, leader={}, totalEntries={}, totalBytes={}, elapsed={}ms",
+ session.id, leader, session.totalEntries, session.totalBytes,
+ TimeUnit.NANOSECONDS.toMillis(now - session.startNanos));
+ session.lastProgressLogTS = now;
+ }
+ });
log.info("Restoring from snapshot: session={}, leader={} \n{}", session.id, leader, rangeSnapshot);
IKVRangeSnapshotReceiver receiver = new KVRangeSnapshotReceiver(session.id, rangeSnapshot.getId(), leader,
messenger, metricManager, executor, idleTimeSec, log);
@@ -136,10 +147,19 @@ class KVRangeRestorer {
final KVRangeSnapshot snapshot;
final CompletableFuture<Void> doneFuture = new CompletableFuture<>();
final String leader;
+ // fields for progress tracking
+ long startNanos;
+ long lastProgressLogTS;
+ long totalEntries;
+ long totalBytes;
private RestoreSession(KVRangeSnapshot snapshot, String leader) {
this.snapshot = snapshot;
this.leader = leader;
+ this.startNanos = System.nanoTime();
+ this.lastProgressLogTS = startNanos;
+ this.totalEntries = 0L;
+ this.totalBytes = 0L;
}
}
}
diff --git a/base-kv/base-kv-type-proto/src/main/java/org/apache/bifromq/basekv/utils/BoundaryUtil.java b/base-kv/base-kv-type-proto/src/main/java/org/apache/bifromq/basekv/utils/BoundaryUtil.java
index 4e718a5fb..0f548371e 100644
--- a/base-kv/base-kv-type-proto/src/main/java/org/apache/bifromq/basekv/utils/BoundaryUtil.java
+++ b/base-kv/base-kv-type-proto/src/main/java/org/apache/bifromq/basekv/utils/BoundaryUtil.java
@@ -354,6 +354,21 @@ public class BoundaryUtil {
return boundary.hasEndKey() ? boundary.getEndKey().toByteArray() : null;
}
+ public static ByteString clampToBoundary(ByteString key, Boundary boundary) {
+ if (key == null) {
+ return null;
+ }
+ ByteString startBoundary = BoundaryUtil.startKey(boundary);
+ ByteString endBoundary = BoundaryUtil.endKey(boundary);
+ if (startBoundary != null && BoundaryUtil.compare(key, startBoundary) < 0) {
+ return startBoundary;
+ }
+ if (endBoundary != null && BoundaryUtil.compare(key, endBoundary) >= 0) {
+ return startBoundary;
+ }
+ return key;
+ }
+
private static ByteString minStartKey(ByteString a, ByteString b) {
return (compareStartKey(a, b) < 0) ? a : b;
}
diff --git a/base-rpc/base-rpc-client/pom.xml b/base-rpc/base-rpc-client/pom.xml
index 4df9a0ab6..305f1b46f 100644
--- a/base-rpc/base-rpc-client/pom.xml
+++ b/base-rpc/base-rpc-client/pom.xml
@@ -67,6 +67,31 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
+ <!-- test dependencies -->
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j2-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedMessageStream.java b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedMessageStream.java
index 2a44018c1..764959915 100644
--- a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedMessageStream.java
+++ b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedMessageStream.java
@@ -107,6 +107,7 @@ class ManagedMessageStream<MsgT, AckT> extends ManagedBiDiStream<AckT, MsgT>
public void close() {
if (isClosed.compareAndSet(false, true)) {
super.close();
+ meter.recordCount(RPCMetric.StreamCompleteCount);
ackSendingBuffers.clear();
msgSubject.onComplete();
retargetSubject.onComplete();
diff --git a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedRequestPipeline.java b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedRequestPipeline.java
index dd2d5b4cc..a351ae5b1 100644
--- a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedRequestPipeline.java
+++ b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/ManagedRequestPipeline.java
@@ -140,6 +140,7 @@ public class ManagedRequestPipeline<ReqT, RespT> extends ManagedBiDiStream<ReqT,
public void close() {
if (isClosed.compareAndSet(false, true)) {
super.close();
+ meter.recordCount(RPCMetric.ReqPipelineCompleteCount);
cancelPreflightTasks(new RequestAbortException("Pipeline has closed"));
}
}
diff --git a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPicker.java b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPicker.java
index 56a89f4a4..da1adc390 100644
--- a/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPicker.java
+++ b/base-rpc/base-rpc-client/src/main/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPicker.java
@@ -19,9 +19,9 @@
package org.apache.bifromq.baserpc.client.loadbalancer;
+import static io.grpc.ConnectivityState.READY;
import static org.apache.bifromq.baserpc.client.exception.ExceptionUtil.SERVER_NOT_FOUND;
import static org.apache.bifromq.baserpc.client.exception.ExceptionUtil.SERVER_UNREACHABLE;
-import static io.grpc.ConnectivityState.READY;
import io.grpc.LoadBalancer;
import java.util.HashMap;
@@ -51,9 +51,9 @@ class SubChannelPicker extends LoadBalancer.SubchannelPicker {
pickSubchannelArgs.getHeaders().remove(Constants.DESIRED_SERVER_META_KEY, desiredServerId);
Optional<LoadBalancer.Subchannel> selectedSubChannel = getSubChannel(desiredServerId);
return selectedSubChannel.map(LoadBalancer.PickResult::withSubchannel)
- .orElseGet(() -> LoadBalancer.PickResult.withDrop(SERVER_UNREACHABLE));
+ .orElseGet(() -> LoadBalancer.PickResult.withError(SERVER_UNREACHABLE));
}
- return LoadBalancer.PickResult.withDrop(SERVER_NOT_FOUND);
+ return LoadBalancer.PickResult.withError(SERVER_NOT_FOUND);
}
private Optional<LoadBalancer.Subchannel> getSubChannel(String serverId) {
diff --git a/base-rpc/base-rpc-client/src/test/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPickerTest.java b/base-rpc/base-rpc-client/src/test/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPickerTest.java
new file mode 100644
index 000000000..d07490409
--- /dev/null
+++ b/base-rpc/base-rpc-client/src/test/java/org/apache/bifromq/baserpc/client/loadbalancer/SubChannelPickerTest.java
@@ -0,0 +1,176 @@
+/*
+ * 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.bifromq.baserpc.client.loadbalancer;
+
+import static org.apache.bifromq.baserpc.client.exception.ExceptionUtil.SERVER_NOT_FOUND;
+import static org.apache.bifromq.baserpc.client.exception.ExceptionUtil.SERVER_UNREACHABLE;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+
+import io.grpc.Attributes;
+import io.grpc.CallOptions;
+import io.grpc.ConnectivityState;
+import io.grpc.ConnectivityStateInfo;
+import io.grpc.EquivalentAddressGroup;
+import io.grpc.LoadBalancer;
+import io.grpc.Metadata;
+import io.grpc.MethodDescriptor;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import org.testng.annotations.Test;
+
+public class SubChannelPickerTest {
+ private static final MethodDescriptor<Void, Void> TEST_METHOD =
+ MethodDescriptor.<Void, Void>newBuilder()
+ .setType(MethodDescriptor.MethodType.UNARY)
+ .setFullMethodName(MethodDescriptor.generateFullMethodName("service", "method"))
+ .setRequestMarshaller(new VoidMarshaller())
+ .setResponseMarshaller(new VoidMarshaller())
+ .build();
+
+ @Test
+ public void pickReadySubchannel() {
+ SubChannelPicker picker = new SubChannelPicker();
+ ChannelList channelList = new ChannelList(false);
+ LoadBalancer.Subchannel readyChannel = new TestSubchannel(readyAttributes());
+ channelList.subChannels.add(readyChannel);
+ picker.refresh(Map.of("serverA", channelList));
+
+ Metadata headers = new Metadata();
+ headers.put(Constants.DESIRED_SERVER_META_KEY, "serverA");
+ LoadBalancer.PickResult result = picker.pickSubchannel(new TestPickArgs(headers));
+
+ assertSame(result.getSubchannel(), readyChannel);
+ assertTrue(result.getStatus().isOk());
+ assertFalse(result.isDrop());
+ }
+
+ @Test
+ public void pickReturnsUnavailableWhenNoReadyChannel() {
+ SubChannelPicker picker = new SubChannelPicker();
+ ChannelList channelList = new ChannelList(false);
+ channelList.subChannels.add(new TestSubchannel(connectingAttributes()));
+ picker.refresh(Map.of("serverA", channelList));
+
+ Metadata headers = new Metadata();
+ headers.put(Constants.DESIRED_SERVER_META_KEY, "serverA");
+ LoadBalancer.PickResult result = picker.pickSubchannel(new TestPickArgs(headers));
+
+ assertNull(result.getSubchannel());
+ assertEquals(result.getStatus(), SERVER_UNREACHABLE);
+ assertFalse(result.isDrop());
+ }
+
+ @Test
+ public void pickReturnsNotFoundWhenServerMissing() {
+ SubChannelPicker picker = new SubChannelPicker();
+ picker.refresh(Collections.emptyMap());
+
+ Metadata headers = new Metadata();
+ headers.put(Constants.DESIRED_SERVER_META_KEY, "serverA");
+ LoadBalancer.PickResult result = picker.pickSubchannel(new TestPickArgs(headers));
+
+ assertNull(result.getSubchannel());
+ assertEquals(result.getStatus(), SERVER_NOT_FOUND);
+ assertFalse(result.isDrop());
+ }
+
+ private static Attributes readyAttributes() {
+ return Attributes.newBuilder()
+ .set(Constants.STATE_INFO,
+ new AtomicReference<>(ConnectivityStateInfo.forNonError(ConnectivityState.READY)))
+ .build();
+ }
+
+ private static Attributes connectingAttributes() {
+ return Attributes.newBuilder()
+ .set(Constants.STATE_INFO,
+ new AtomicReference<>(ConnectivityStateInfo.forNonError(ConnectivityState.CONNECTING)))
+ .build();
+ }
+
+ private static class TestPickArgs extends LoadBalancer.PickSubchannelArgs {
+ private final Metadata headers;
+
+ TestPickArgs(Metadata headers) {
+ this.headers = headers;
+ }
+
+ @Override
+ public CallOptions getCallOptions() {
+ return CallOptions.DEFAULT;
+ }
+
+ @Override
+ public Metadata getHeaders() {
+ return headers;
+ }
+
+ @Override
+ public MethodDescriptor<?, ?> getMethodDescriptor() {
+ return TEST_METHOD;
+ }
+ }
+
+ private static class TestSubchannel extends LoadBalancer.Subchannel {
+ private final Attributes attributes;
+
+ TestSubchannel(Attributes attributes) {
+ this.attributes = attributes;
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ @Override
+ public void requestConnection() {
+ }
+
+ @Override
+ public List<EquivalentAddressGroup> getAllAddresses() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public Attributes getAttributes() {
+ return attributes;
+ }
+ }
+
+ private static class VoidMarshaller implements MethodDescriptor.Marshaller<Void> {
+ @Override
+ public InputStream stream(Void value) {
+ return new ByteArrayInputStream(new byte[0]);
+ }
+
+ @Override
+ public Void parse(InputStream stream) {
+ return null;
+ }
+ }
+}
diff --git a/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml b/base-rpc/base-rpc-client/src/test/resources/log4j2-test.xml
similarity index 95%
copy from base-kv/base-kv-raft/src/test/resources/log4j2-test.xml
copy to base-rpc/base-rpc-client/src/test/resources/log4j2-test.xml
index 9f7137626..40b2f5ce5 100644
--- a/base-kv/base-kv-raft/src/test/resources/log4j2-test.xml
+++ b/base-rpc/base-rpc-client/src/test/resources/log4j2-test.xml
@@ -29,7 +29,6 @@
</Console>
</Appenders>
<Loggers>
- <Logger name="org.apache.bifromq.basekv.raft" level="DEBUG"/>
<Root level="INFO">
<AppenderRef ref="CONSOLE"/>
</Root>
diff --git a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java
index bbcc20549..c5f3a37b4 100644
--- a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java
+++ b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java
@@ -21,8 +21,12 @@ package org.apache.bifromq.dist.worker;
import static org.apache.bifromq.basekv.client.KVRangeRouterUtil.findByBoundary;
import static org.apache.bifromq.basekv.utils.BoundaryUtil.FULL_BOUNDARY;
+import static org.apache.bifromq.basekv.utils.BoundaryUtil.clampToBoundary;
import com.google.protobuf.ByteString;
+import io.micrometer.core.instrument.Gauge;
+import io.micrometer.core.instrument.Metrics;
+import io.micrometer.core.instrument.Tags;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -44,7 +48,6 @@ import org.apache.bifromq.basekv.proto.KVRangeId;
import org.apache.bifromq.basekv.store.proto.KVRangeRORequest;
import org.apache.bifromq.basekv.store.proto.ROCoProcInput;
import org.apache.bifromq.basekv.store.proto.ReplyCode;
-import org.apache.bifromq.basekv.utils.BoundaryUtil;
import org.apache.bifromq.basekv.utils.KVRangeIdUtil;
import org.apache.bifromq.dist.rpc.proto.DistServiceROCoProcInput;
import org.apache.bifromq.dist.rpc.proto.GCReply;
@@ -54,6 +57,8 @@ import org.apache.bifromq.dist.rpc.proto.GCRequest;
class DistWorkerCleaner {
private static final int MAX_STEP = 10;
private static final int SCAN_QUOTA_BASE = 512;
+ private static final int FIRST_SWEEP_SCAN_QUOTA = 50_000;
+ private static final Duration FIRST_SWEEP_INTERVAL = Duration.ofSeconds(5);
private static final double HIGH_SUCCESS_RATIO = 0.005; // 0.5%
private static final int LOW_HIT_THRESHOLD = 3;
private static final double QUOTA_HIT_RATIO = 0.8;
@@ -90,7 +95,7 @@ class DistWorkerCleaner {
void start(String storeId) {
if (started.compareAndSet(false, true)) {
- log.debug("DistWorkerCleaner started");
+ log.info("DistWorkerCleaner started");
doStart(storeId);
}
}
@@ -100,7 +105,16 @@ class DistWorkerCleaner {
cleanerFuture.cancel(true);
CompletableFuture<Void> onDone = new CompletableFuture<>();
jobScheduler.execute(() -> {
- log.debug("DistWorkerCleaner stopped");
+ log.info("DistWorkerCleaner stopped");
+ // remove all gauges on stop
+ for (RangeGcState st : rangeStates.values()) {
+ if (st.stepGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.stepGauge.getId());
+ }
+ if (st.intervalGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.intervalGauge.getId());
+ }
+ }
onDone.complete(null);
});
return onDone;
@@ -142,13 +156,21 @@ class DistWorkerCleaner {
RangeGcState state = rangeStates.get(rs.id());
if (state == null) {
state = new RangeGcState();
- state.step = MAX_STEP;
- state.interval = minCleanInterval;
+ state.step = 1;
+ state.interval = FIRST_SWEEP_INTERVAL;
state.lowRatioHits = 0;
- state.nextDue = Instant.EPOCH; // run asap
+ state.nextDue = Instant.EPOCH;
state.ver = rs.ver();
state.boundary = rs.boundary();
state.wrappedOnce = false;
+ state.sprinted = false;
+ Tags tags = Tags.of("storeId", storeId).and("rangeId", KVRangeIdUtil.toString(rs.id()));
+ state.intervalGauge = Gauge.builder("dist.gc.interval.ms", state, s -> s.interval.toMillis())
+ .tags(tags)
+ .register(Metrics.globalRegistry);
+ state.stepGauge = Gauge.builder("dist.gc.step", state, s -> (double) s.step)
+ .tags(tags)
+ .register(Metrics.globalRegistry);
rangeStates.put(rs.id(), state);
} else {
if (state.ver != rs.ver() || !state.boundary.equals(rs.boundary())) {
@@ -157,7 +179,7 @@ class DistWorkerCleaner {
state.nextKey = clampToBoundary(state.nextKey, rs.boundary());
}
state.step = 1;
- state.interval = minCleanInterval;
+ state.interval = state.sprinted ? minCleanInterval : FIRST_SWEEP_INTERVAL;
state.lowRatioHits = 0;
state.wrappedOnce = false;
state.ver = rs.ver();
@@ -165,8 +187,19 @@ class DistWorkerCleaner {
}
}
}
- // remove states for ranges not leader anymore
- rangeStates.keySet().removeIf(rid -> !currentLeaderMap.containsKey(rid));
+ rangeStates.entrySet().removeIf(e -> {
+ boolean remove = !currentLeaderMap.containsKey(e.getKey());
+ if (remove) {
+ RangeGcState st = e.getValue();
+ if (st.stepGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.stepGauge.getId());
+ }
+ if (st.intervalGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.intervalGauge.getId());
+ }
+ }
+ return remove;
+ });
long reqId = HLC.INST.getPhysical();
Instant now = clock.instant();
@@ -180,8 +213,8 @@ class DistWorkerCleaner {
return CompletableFuture.<Void>completedFuture(null);
}
GCRequest.Builder gcReq = GCRequest.newBuilder().setReqId(reqId)
- .setStepHint(s.step)
- .setScanQuota(SCAN_QUOTA_BASE * s.step);
+ .setStepHint(s.sprinted ? Math.max(1, s.step) : 1)
+ .setScanQuota(s.sprinted ? SCAN_QUOTA_BASE * Math.max(1, s.step) : FIRST_SWEEP_SCAN_QUOTA);
if (s.nextKey != null) {
ByteString start = clampToBoundary(s.nextKey, rs.boundary());
if (start != null) {
@@ -189,8 +222,10 @@ class DistWorkerCleaner {
}
}
String rangeIdStr = KVRangeIdUtil.toString(rs.id());
- log.debug("[DistWorker] start gc: reqId={}, rangeId={}, step={}, quota={}",
- reqId, rangeIdStr, s.step, SCAN_QUOTA_BASE * s.step);
+ int stepHint = gcReq.getStepHint();
+ int quota = gcReq.getScanQuota();
+ log.debug("[DistWorker] start gc: reqId={}, rangeId={}, stepHint={}, quota={}",
+ reqId, rangeIdStr, stepHint, quota);
return distWorkerClient.query(rs.leader(), KVRangeRORequest.newBuilder()
.setReqId(reqId)
.setKvRangeId(rs.id())
@@ -233,7 +268,7 @@ class DistWorkerCleaner {
private void onGCFailure(RangeGcState s) {
// reset on failure
s.step = 1;
- s.interval = minCleanInterval;
+ s.interval = s.sprinted ? minCleanInterval : FIRST_SWEEP_INTERVAL;
s.lowRatioHits = 0;
s.wrappedOnce = false;
}
@@ -247,13 +282,22 @@ class DistWorkerCleaner {
if (reply.getWrapped()) {
s.wrappedOnce = true;
}
+ if (!s.sprinted) {
+ if (reply.getWrapped()) {
+ s.sprinted = true;
+ s.step = 1;
+ s.interval = minCleanInterval;
+ s.lowRatioHits = 0;
+ s.wrappedOnce = false;
+ }
+ return;
+ }
int inspected = reply.getInspectedCount();
int removeSuccess = reply.getRemoveSuccess();
double successRatio = inspected == 0 ? 0 : ((double) removeSuccess) / inspected;
int scanQuota = SCAN_QUOTA_BASE * Math.max(1, s.step);
boolean coverageOK = s.wrappedOnce || inspected >= (int) (scanQuota * QUOTA_HIT_RATIO);
- // Shrink when removal success ratio is high
if (successRatio >= HIGH_SUCCESS_RATIO) {
s.step = Math.max(s.step / 2, 1);
long shrunk = (long) (s.interval.toMillis() / SHRINK);
@@ -261,21 +305,18 @@ class DistWorkerCleaner {
s.lowRatioHits = 0;
s.wrappedOnce = false;
} else {
- // Grow only when no removals for sustained rounds with sufficient coverage and a full wrap
if (coverageOK && removeSuccess == 0) {
s.lowRatioHits++;
if (s.lowRatioHits >= LOW_HIT_THRESHOLD && s.wrappedOnce) {
- // grow step only when quota is sufficiently utilized
if (inspected >= (int) (scanQuota * QUOTA_HIT_RATIO)) {
s.step = Math.min(s.step + 1, MAX_STEP);
}
long grown = (long) (s.interval.toMillis() * GROWTH);
s.interval = Duration.ofMillis(Math.min(grown, maxCleanInterval.toMillis()));
s.lowRatioHits = 0;
- s.wrappedOnce = false; // require another full wrap before next growth
+ s.wrappedOnce = false;
}
} else {
- // If not yet wrapped once and this round didn't wrap, accelerate to finish a full circle
if (!s.wrappedOnce) {
s.interval = minCleanInterval;
}
@@ -283,21 +324,6 @@ class DistWorkerCleaner {
}
}
- private ByteString clampToBoundary(ByteString key, Boundary boundary) {
- if (key == null) {
- return null;
- }
- ByteString startBoundary = BoundaryUtil.startKey(boundary);
- ByteString endBoundary = BoundaryUtil.endKey(boundary);
- if (startBoundary != null && BoundaryUtil.compare(key, startBoundary) < 0) {
- return startBoundary;
- }
- if (endBoundary != null && BoundaryUtil.compare(key, endBoundary) >= 0) {
- return startBoundary;
- }
- return key;
- }
-
private static class RangeGcState {
ByteString nextKey;
int step;
@@ -307,5 +333,8 @@ class DistWorkerCleaner {
Instant nextDue;
long ver;
Boundary boundary;
+ boolean sprinted;
+ Gauge stepGauge;
+ Gauge intervalGauge;
}
}
diff --git a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCoProc.java b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCoProc.java
index 19b2da1c5..d49176e90 100644
--- a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCoProc.java
+++ b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCoProc.java
@@ -249,7 +249,6 @@ class DistWorkerCoProc implements IKVRangeCoProc {
}
if (needRefresh) {
try (IKVRangeRefreshableReader reader = readerProvider.get(); IKVIterator itr = reader.iterator()) {
- reader.refresh();
setFact(itr);
}
}
@@ -582,19 +581,19 @@ class DistWorkerCoProc implements IKVRangeCoProc {
itr.seekToFirst();
}
- // if range is empty, return immediately
if (!itr.isValid()) {
return CompletableFuture.completedFuture(GCReply.newBuilder()
.setReqId(request.getReqId())
.setInspectedCount(0)
.setRemoveSuccess(0)
- .setWrapped(false)
+ .setWrapped(true)
.build());
}
AtomicInteger inspectedCount = new AtomicInteger();
AtomicBoolean wrapped = new AtomicBoolean(false);
ByteString sessionStartKey = null;
+ AtomicReference<ByteString> nextStartKeySnapshot = new AtomicReference<>();
outer:
while (true) {
@@ -637,7 +636,8 @@ class DistWorkerCoProc implements IKVRangeCoProc {
GroupMatching groupMatching = ((GroupMatching) matching);
if (!routeCache.isCached(groupMatching.tenantId(), matching.matcher.getFilterLevelList())) {
for (NormalMatching normalMatching : groupMatching.receiverList) {
- checkRequestBuilders.computeIfAbsent(normalMatching.subBrokerId(), k -> new HashMap<>())
+ checkRequestBuilders.computeIfAbsent(normalMatching.subBrokerId(),
+ k -> new HashMap<>())
.computeIfAbsent(normalMatching.delivererKey(), k -> new HashMap<>())
.computeIfAbsent(normalMatching.tenantId(), k -> CheckRequest.newBuilder()
.setTenantId(k)
@@ -652,24 +652,24 @@ class DistWorkerCoProc implements IKVRangeCoProc {
}
inspectedCount.incrementAndGet();
if (inspectedCount.get() >= scanQuota) {
- // stop by quota
itr.next();
break;
}
- // skip over stepUsed-1 entries
int skip = stepUsed - 1;
while (skip-- > 0) {
itr.next();
if (!itr.isValid()) {
- // let outer loop handle wrap or stop
continue outer;
}
}
- // move to next for next iteration
itr.next();
}
+ if (itr.isValid()) {
+ nextStartKeySnapshot.set(itr.key());
+ }
+
// aggregate sweep results
List<CompletableFuture<ISubscriptionCleaner.GCStats>> checkFutures = new ArrayList<>();
for (int subBrokerId : checkRequestBuilders.keySet()) {
@@ -692,8 +692,8 @@ class DistWorkerCoProc implements IKVRangeCoProc {
.setInspectedCount(inspectedCount.get())
.setRemoveSuccess(success)
.setWrapped(wrapped.get());
- if (itr.isValid()) {
- reply.setNextStartKey(itr.key());
+ if (nextStartKeySnapshot.get() != null) {
+ reply.setNextStartKey(nextStartKeySnapshot.get());
}
return reply.build();
});
diff --git a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/TenantsStats.java b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/TenantsStats.java
index 336f88663..860ad482f 100644
--- a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/TenantsStats.java
+++ b/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/TenantsStats.java
@@ -230,7 +230,6 @@ class TenantsStats implements ITenantsStats {
try (IKVRangeRefreshableReader reader = readerSupplier.get(); IKVIterator itr = reader.iterator()) {
tenantStatsMap.values().forEach(TenantStats::destroy);
tenantStatsMap.clear();
- reader.refresh();
// enqueue full reload task; don't block caller
for (itr.seekToFirst(); itr.isValid(); itr.next()) {
String tenantId = parseTenantId(itr.key());
diff --git a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCleanerTest.java b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCleanerTest.java
index 42145157e..8b4bd0570 100644
--- a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCleanerTest.java
+++ b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCleanerTest.java
@@ -24,22 +24,23 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.inOrder;
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 static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+import io.micrometer.core.instrument.Gauge;
+import io.micrometer.core.instrument.Metrics;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
-import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
@@ -60,7 +61,6 @@ import org.apache.bifromq.basekv.utils.KVRangeIdUtil;
import org.apache.bifromq.dist.rpc.proto.DistServiceROCoProcOutput;
import org.apache.bifromq.dist.rpc.proto.GCReply;
import org.mockito.ArgumentCaptor;
-import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.AfterMethod;
@@ -75,6 +75,7 @@ public class DistWorkerCleanerTest {
private DistWorkerCleaner cleaner;
private AutoCloseable openMocks;
private ManualClock manualClock;
+ private SimpleMeterRegistry meterRegistry;
@BeforeMethod
public void setup() {
@@ -87,34 +88,33 @@ public class DistWorkerCleanerTest {
task.run();
return null;
}).when(jobScheduler).execute(any(Runnable.class));
+ meterRegistry = new SimpleMeterRegistry();
+ Metrics.globalRegistry.add(meterRegistry);
}
@AfterMethod
public void tearDown() throws Exception {
+ Metrics.globalRegistry.getMeters().forEach(Metrics.globalRegistry::remove);
+ Metrics.globalRegistry.remove(meterRegistry);
openMocks.close();
}
@Test
public void testStartSchedulesRecurringTask() {
- // Mock scheduler to capture the scheduled task
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
- // Start the cleaner
cleaner.start("store1");
- // Verify initial scheduling
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), eq(TimeUnit.MILLISECONDS));
}
@Test
public void testGCOperationExecuted() {
- // Mock scheduler to capture the task
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
- // Setup KVRange data
KVRangeSetting leaderRange = new KVRangeSetting("dist.worker", "store1", new HashMap<>() {
{
put("store1", KVRangeDescriptor.newBuilder()
@@ -127,46 +127,36 @@ public class DistWorkerCleanerTest {
router.put(FULL_BOUNDARY, leaderRange);
when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
- // Mock query response
when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
.thenReturn(CompletableFuture.completedFuture(KVRangeROReply.newBuilder().build()));
- // Start and trigger the task
cleaner.start("store1");
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- // Execute the captured task (simulate timer trigger)
taskCaptor.getValue().run();
- // Verify GC executed for leader range
verify(distWorkerClient).query(eq("store1"), any(KVRangeRORequest.class));
- // Verify rescheduling after execution
verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), eq(TimeUnit.MILLISECONDS));
}
@Test
public void testStopPreventsFurtherExecution() {
- // Mock scheduler and future
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
.thenReturn(mockFuture);
- // Start and stop
cleaner.start("store1");
cleaner.stop().join();
- // Verify cancellation
verify(mockFuture).cancel(true);
- // Ensure no more scheduling after stop
verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
}
@Test
public void testHandleGCFailure() {
- // Setup
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
.thenReturn(mockFuture);
@@ -184,23 +174,19 @@ public class DistWorkerCleanerTest {
router.put(FULL_BOUNDARY, leaderRange);
when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
- // Simulate query failure
when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("Failed")));
- // Trigger execution
cleaner.start("store1");
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
taskCaptor.getValue().run();
- // Verify rescheduled despite failure
verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
}
@Test
public void testNoGcForNonLeaderRanges() {
- // Setup non-leader range
KVRangeSetting nonLeaderRange = new KVRangeSetting("dist.worker", "store2", new HashMap<>() {
{
put("store2", KVRangeDescriptor.newBuilder()
@@ -214,7 +200,6 @@ public class DistWorkerCleanerTest {
router.put(FULL_BOUNDARY, nonLeaderRange);
when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
- // Trigger execution
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
.thenReturn(mockFuture);
@@ -223,7 +208,6 @@ public class DistWorkerCleanerTest {
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
taskCaptor.getValue().run();
- // Verify no GC requests sent
verify(distWorkerClient, never()).query(any(), any());
}
@@ -235,12 +219,11 @@ public class DistWorkerCleanerTest {
cleaner.start("store1");
cleaner.start("store1"); // Duplicate call
- // Verify only one scheduling
verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
}
@Test
- public void testShrinkOnHighSuccessRatio() {
+ public void testFirstSweepQuotaAndStepHint() {
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
@@ -256,29 +239,58 @@ public class DistWorkerCleanerTest {
router.put(FULL_BOUNDARY, leaderRange);
when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
- AtomicInteger callCount = new AtomicInteger();
+ when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.completedFuture(
+ KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setDistService(DistServiceROCoProcOutput.newBuilder()
+ .setGc(GCReply.newBuilder().setInspectedCount(10).setRemoveSuccess(0).setWrapped(false).build())
+ .build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
+ taskCaptor.getValue().run();
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(distWorkerClient).query(eq("store1"), reqCaptor.capture());
+ int stepHint = reqCaptor.getValue().getRoCoProc().getDistService().getGc().getStepHint();
+ int quota = reqCaptor.getValue().getRoCoProc().getDistService().getGc().getScanQuota();
+ assertEquals(1, stepHint);
+ assertEquals(50_000, quota);
+ }
+
+ @Test
+ public void testSwitchToAdaptiveAfterFirstWrap() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("dist.worker", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder()
+ .setId(KVRangeIdUtil.generate())
+ .setVer(1)
+ .build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
+
+ AtomicInteger call = new AtomicInteger();
when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
.thenAnswer(inv -> {
- int c = callCount.incrementAndGet();
- GCReply gcReply;
- if (c == 1) {
- // high removal success ratio: removeSuccess ~= inspected
- gcReply = GCReply.newBuilder()
- .setInspectedCount(100)
- .setRemoveSuccess(100)
- .setWrapped(false)
- .build();
- } else {
- // default low work
- gcReply = GCReply.getDefaultInstance();
- }
+ GCReply reply = call.getAndIncrement() == 0
+ ? GCReply.newBuilder().setInspectedCount(10).setRemoveSuccess(0).setWrapped(true).build()
+ : GCReply.getDefaultInstance();
return CompletableFuture.completedFuture(
KVRangeROReply.newBuilder()
.setCode(ReplyCode.Ok)
.setRoCoProcResult(ROCoProcOutput.newBuilder()
- .setDistService(DistServiceROCoProcOutput.newBuilder()
- .setGc(gcReply)
- .build())
+ .setDistService(DistServiceROCoProcOutput.newBuilder().setGc(reply).build())
.build())
.build());
});
@@ -286,26 +298,22 @@ public class DistWorkerCleanerTest {
cleaner.start("store1");
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- // 1st run: trigger shrink
taskCaptor.getValue().run();
verify(jobScheduler, times(2)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- InOrder inOrder = inOrder(distWorkerClient);
- ArgumentCaptor<KVRangeRORequest> reqCaptor1 = ArgumentCaptor.forClass(KVRangeRORequest.class);
- inOrder.verify(distWorkerClient).query(eq("store1"), reqCaptor1.capture());
- // Advance time to allow next GC and run second task
- manualClock.advance(Duration.ofHours(1));
+ manualClock.advance(Duration.ofMinutes(10));
taskCaptor.getAllValues().get(1).run();
- ArgumentCaptor<KVRangeRORequest> reqCaptor2 = ArgumentCaptor.forClass(KVRangeRORequest.class);
- inOrder.verify(distWorkerClient).query(eq("store1"), reqCaptor2.capture());
- int stepHintFirst = reqCaptor1.getValue().getRoCoProc().getDistService().getGc().getStepHint();
- int stepHintSecond = reqCaptor2.getValue().getRoCoProc().getDistService().getGc().getStepHint();
- assertEquals(10, stepHintFirst);
- assertEquals(5, stepHintSecond);
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(distWorkerClient, times(2)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest secondReq = reqCaptor.getAllValues().get(1);
+ int stepHint2 = secondReq.getRoCoProc().getDistService().getGc().getStepHint();
+ int quota2 = secondReq.getRoCoProc().getDistService().getGc().getScanQuota();
+ assertEquals(1, stepHint2);
+ assertEquals(512, quota2);
}
@Test
- public void testLowHitSmallRangeGrowIntervalWithoutStep() {
+ public void testFirstSweepFailureKeepsSprint() {
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
@@ -321,70 +329,132 @@ public class DistWorkerCleanerTest {
router.put(FULL_BOUNDARY, leaderRange);
when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
- // Sequence: 1) shrink by high candidate 2/3/4) low-hit with wrapped=true and small inspected
- AtomicInteger callCount = new AtomicInteger();
+ AtomicInteger call = new AtomicInteger();
when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
.thenAnswer(inv -> {
- int c = callCount.incrementAndGet();
- GCReply gcReply;
- if (c == 1) {
- // shrink by high success ratio
- gcReply = GCReply.newBuilder()
- .setInspectedCount(100)
- .setRemoveSuccess(100)
- .setWrapped(false)
- .build();
- } else {
- // low candidate, small inspected, but wrapped=true ensures coverageOK
- gcReply = GCReply.newBuilder()
- .setInspectedCount(10)
- .setRemoveSuccess(0)
- .setWrapped(true)
- .build();
+ if (call.getAndIncrement() == 0) {
+ return CompletableFuture.failedFuture(new RuntimeException("network"));
}
return CompletableFuture.completedFuture(
KVRangeROReply.newBuilder()
.setCode(ReplyCode.Ok)
.setRoCoProcResult(ROCoProcOutput.newBuilder()
.setDistService(DistServiceROCoProcOutput.newBuilder()
- .setGc(gcReply)
+ .setGc(GCReply.newBuilder().setWrapped(false).build())
.build())
.build())
.build());
});
cleaner.start("store1");
-
- // capture scheduled tasks and run 5 cycles (1 shrink + 3 low-hit + 1 observe)
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
- List<Runnable> scheduled = new ArrayList<>();
verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- scheduled.add(taskCaptor.getValue());
- scheduled.get(0).run(); // 1st: shrink to step 5
+ taskCaptor.getValue().run();
verify(jobScheduler, times(2)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- scheduled.add(taskCaptor.getValue());
- manualClock.advance(Duration.ofHours(1));
- scheduled.get(1).run(); // 2nd: low-hit
- verify(jobScheduler, times(3)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- scheduled.add(taskCaptor.getValue());
- manualClock.advance(Duration.ofHours(1));
- scheduled.get(2).run(); // 3rd: low-hit
- verify(jobScheduler, times(4)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- scheduled.add(taskCaptor.getValue());
- manualClock.advance(Duration.ofHours(1));
- scheduled.get(3).run(); // 4th: low-hit triggers growth (interval) without step growth
- // 5th scheduling for observation
- verify(jobScheduler, times(5)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
- scheduled.add(taskCaptor.getValue());
+ manualClock.advance(Duration.ofSeconds(5));
+ taskCaptor.getAllValues().get(1).run();
ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
- verify(distWorkerClient, times(4)).query(eq("store1"), reqCaptor.capture());
- List<KVRangeRORequest> reqs = reqCaptor.getAllValues();
- int stepAfterShrink = reqs.get(1).getRoCoProc().getDistService().getGc().getStepHint();
- int stepAfterGrowth = reqs.get(3).getRoCoProc().getDistService().getGc().getStepHint();
- // Step should remain unchanged (no growth) for small-range low-hit
- assertEquals(5, stepAfterShrink);
- assertEquals(5, stepAfterGrowth);
+ verify(distWorkerClient, times(2)).query(eq("store1"), reqCaptor.capture());
+ int stepHint = reqCaptor.getAllValues().get(1).getRoCoProc().getDistService().getGc().getStepHint();
+ int quota = reqCaptor.getAllValues().get(1).getRoCoProc().getDistService().getGc().getScanQuota();
+ assertEquals(1, stepHint);
+ assertEquals(50_000, quota);
+ }
+
+ @Test
+ public void testMetricsRegisteredAndUpdated() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("dist.worker", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder()
+ .setId(KVRangeIdUtil.generate())
+ .setVer(1)
+ .build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(distWorkerClient.latestEffectiveRouter()).thenReturn(router);
+
+ when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.completedFuture(
+ KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setDistService(DistServiceROCoProcOutput.newBuilder()
+ .setGc(GCReply.newBuilder().setInspectedCount(10).setRemoveSuccess(0).setWrapped(true).build())
+ .build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
+ taskCaptor.getValue().run();
+
+ String rangeIdStr = KVRangeIdUtil.toString(leaderRange.id());
+ Gauge stepGauge = Metrics.globalRegistry.find("dist.gc.step")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+ Gauge intervalGauge = Metrics.globalRegistry.find("dist.gc.interval.ms")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+
+ assertEquals(1.0, stepGauge.value(), 0.0);
+ assertEquals(100.0, intervalGauge.value(), 0.0);
+ }
+
+ @Test
+ public void testMetricsRemovedOnLeadershipLost() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("dist.worker", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder()
+ .setId(KVRangeIdUtil.generate())
+ .setVer(1)
+ .build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router1 = new TreeMap<>(BoundaryUtil::compare);
+ router1.put(FULL_BOUNDARY, leaderRange);
+ NavigableMap<Boundary, KVRangeSetting> router2 = new TreeMap<>(BoundaryUtil::compare); // empty -> lose leadership
+ when(distWorkerClient.latestEffectiveRouter()).thenReturn(router1, router2);
+
+ when(distWorkerClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.completedFuture(
+ KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setDistService(DistServiceROCoProcOutput.newBuilder()
+ .setGc(GCReply.getDefaultInstance())
+ .build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
+ taskCaptor.getValue().run();
+ String rangeIdStr = KVRangeIdUtil.toString(leaderRange.id());
+ Gauge stepGauge = Metrics.globalRegistry.find("dist.gc.step")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+ Gauge intervalGauge = Metrics.globalRegistry.find("dist.gc.interval.ms")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+ assertEquals(1.0, stepGauge.value(), 0.0);
+
+ verify(jobScheduler, times(2)).schedule(taskCaptor.capture(), anyLong(), any(TimeUnit.class));
+ manualClock.advance(Duration.ofMinutes(10));
+ taskCaptor.getAllValues().get(1).run();
+
+ Gauge stepGaugeAfter = Metrics.globalRegistry.find("dist.gc.step")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+ Gauge intervalGaugeAfter = Metrics.globalRegistry.find("dist.gc.interval.ms")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr).gauge();
+ assertNull(stepGaugeAfter);
+ assertNull(intervalGaugeAfter);
}
static class ManualClock extends Clock {
diff --git a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcGCTest.java b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcGCTest.java
index 90d74cd85..5c2f9e8f0 100644
--- a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcGCTest.java
+++ b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcGCTest.java
@@ -128,7 +128,7 @@ public class DistWorkerCoProcGCTest {
assertEquals(r.getReqId(), 1001L);
assertEquals(r.getInspectedCount(), 0);
assertEquals(r.getRemoveSuccess(), 0);
- assertFalse(r.getWrapped());
+ assertTrue(r.getWrapped());
assertFalse(r.hasNextStartKey());
}
diff --git a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcTest.java b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcTest.java
index 631298843..d862f1558 100644
--- a/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcTest.java
+++ b/bifromq-dist/bifromq-dist-worker/src/test/java/org/apache/bifromq/dist/worker/DistWorkerCoProcTest.java
@@ -308,8 +308,6 @@ public class DistWorkerCoProcTest {
// at least once (added map refresh); there may also be an empty removed map refresh
verify(routeCache, atLeast(1)).refresh(any());
verify(tenantsState, times(1)).incNormalRoutes(eq("tenant0"), eq(1));
-
- verify(refreshableReader, times(1)).refresh();
}
@SneakyThrows
@@ -351,8 +349,6 @@ public class DistWorkerCoProcTest {
verify(writer, times(1)).put(any(), eq(BSUtil.toByteString(1L)));
verify(routeCache, atLeast(1)).refresh(any());
verify(tenantsState, times(1)).incNormalRoutes(eq("tenantC"), eq(1));
-
- verify(refreshableReader, times(1)).refresh();
}
@SneakyThrows
@@ -395,7 +391,6 @@ public class DistWorkerCoProcTest {
&& m.get("tenantA").routes.keySet()
.contains(TopicUtil.from("topicA"))));
verify(tenantsState, times(1)).decNormalRoutes(eq("tenantA"), eq(1));
- verify(refreshableReader, times(1)).refresh();
}
@SneakyThrows
@@ -437,7 +432,6 @@ public class DistWorkerCoProcTest {
verify(routeCache, times(1)).refresh(argThat(m -> m.containsKey("tenantB")
&& m.get("tenantB").routes.keySet().contains(TopicUtil.from("topicB"))));
verify(tenantsState, times(1)).decNormalRoutes(eq("tenantB"), eq(1));
- verify(refreshableReader, times(1)).refresh();
}
@Test
diff --git a/bifromq-inbox/bifromq-inbox-coproc-proto/src/main/proto/inboxservice/InboxStoreCoProc.proto b/bifromq-inbox/bifromq-inbox-coproc-proto/src/main/proto/inboxservice/InboxStoreCoProc.proto
index 3aae19bdd..4ddaff723 100644
--- a/bifromq-inbox/bifromq-inbox-coproc-proto/src/main/proto/inboxservice/InboxStoreCoProc.proto
+++ b/bifromq-inbox/bifromq-inbox-coproc-proto/src/main/proto/inboxservice/InboxStoreCoProc.proto
@@ -323,9 +323,19 @@ message ExpireTenantReply{
message GCRequest {
uint64 now = 1;
+ optional bytes startKey = 2;
+ uint32 scanQuota = 3;
}
message GCReply {
+ // next start key for the following round
+ optional bytes nextStartKey = 1;
+ // number of metadata keys inspected in this round
+ uint32 inspectedCount = 2;
+ // number of successfully scheduled removals in this round
+ uint32 removeSuccess = 3;
+ // whether wrapped to range start in this round
+ bool wrapped = 4;
}
message InboxServiceRWCoProcInput{
diff --git a/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxFetchPipeline.java b/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxFetchPipeline.java
index 230012058..f06e56040 100644
--- a/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxFetchPipeline.java
+++ b/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxFetchPipeline.java
@@ -76,7 +76,10 @@ final class InboxFetchPipeline extends AckStream<InboxFetchHint, InboxFetched> i
log.trace("Got hint: tenantId={}, inboxId={}\n{}", tenantId, inboxId, fetchHint);
if (fetchHint.getCapacity() < 0) {
inboxFetchSessions.computeIfPresent(fetchHint.getSessionId(), (k, v) -> {
- inboxSessionMap.remove(new InboxId(v.inboxId, v.incarnation));
+ inboxSessionMap.computeIfPresent(new InboxId(v.inboxId, v.incarnation), (k1, set) -> {
+ set.remove(fetchHint.getSessionId());
+ return set.isEmpty() ? null : set;
+ });
return null;
});
} else {
@@ -89,8 +92,10 @@ final class InboxFetchPipeline extends AckStream<InboxFetchHint, InboxFetched> i
new InboxId(fetchHint.getInboxId(), fetchHint.getIncarnation()),
k1 -> new HashSet<>()).add(fetchHint.getSessionId());
}
- v.lastFetchQoS0Seq.set(fetchHint.getLastFetchQoS0Seq());
- v.lastFetchSendBufferSeq.set(fetchHint.getLastFetchSendBufferSeq());
+ v.lastFetchQoS0Seq.set(
+ Math.max(fetchHint.getLastFetchQoS0Seq(), v.lastFetchQoS0Seq.get()));
+ v.lastFetchSendBufferSeq.set(
+ Math.max(fetchHint.getLastFetchSendBufferSeq(), v.lastFetchSendBufferSeq.get()));
v.downStreamCapacity.set(Math.max(0, fetchHint.getCapacity()));
return v;
});
@@ -175,10 +180,6 @@ final class InboxFetchPipeline extends AckStream<InboxFetchHint, InboxFetched> i
}
if (e != null) {
try {
- inboxFetchSessions.computeIfPresent(sessionId, (k, v) -> {
- inboxSessionMap.remove(new InboxId(v.inboxId, v.incarnation));
- return null;
- });
if (e instanceof BatcherUnavailableException) {
send(InboxFetched.newBuilder()
.setSessionId(fetchState.sessionId)
@@ -211,9 +212,10 @@ final class InboxFetchPipeline extends AckStream<InboxFetchHint, InboxFetched> i
.setResult(Fetched.Result.ERROR)
.build())
.build());
-
} catch (Throwable t) {
log.error("Unexpected error", t);
+ } finally {
+ fetchState.fetching.set(false);
}
} else {
log.trace("Fetched inbox: tenantId={}, inboxId={}, incarnation={}\n{}",
@@ -243,13 +245,6 @@ final class InboxFetchPipeline extends AckStream<InboxFetchHint, InboxFetched> i
fetchState.hasMore.set(fetchState.signalFetchTS.get() > fetchTS);
}
fetchState.fetching.set(false);
- inboxFetchSessions.compute(sessionId, (k, v) -> {
- if (v == null) {
- inboxSessionMap.computeIfAbsent(new InboxId(fetchState.inboxId, fetchState.incarnation),
- k1 -> new HashSet<>()).add(fetchState.sessionId);
- }
- return fetchState;
- });
if (fetchState.downStreamCapacity.get() > 0 && fetchState.hasMore.get()) {
fetch(sessionId);
}
diff --git a/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxWriter.java b/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxWriter.java
index 9e7f73b62..45010fd1b 100644
--- a/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxWriter.java
+++ b/bifromq-inbox/bifromq-inbox-server/src/main/java/org/apache/bifromq/inbox/server/InboxWriter.java
@@ -103,9 +103,14 @@ class InboxWriter implements InboxWriterPipeline.ISendRequestHandler {
if (e == null) {
return false;
}
- return e instanceof BatcherUnavailableException
+ boolean needRetry = e instanceof BatcherUnavailableException
|| e instanceof TryLaterException
|| e instanceof BadVersionException;
+ if (needRetry) {
+ log.debug("Retrying insert for inbox {} incarnation {} due to {}",
+ insertRequest.getInboxId(), insertRequest.getIncarnation(), e.getClass().getSimpleName());
+ }
+ return needRetry;
}, retryTimeoutNanos / 5, retryTimeoutNanos);
}).toList();
return CompletableFuture.allOf(replyFutures.toArray(new CompletableFuture[0]))
diff --git a/bifromq-inbox/bifromq-inbox-server/src/test/java/org/apache/bifromq/inbox/server/InboxFetchPipelineMappingTest.java b/bifromq-inbox/bifromq-inbox-server/src/test/java/org/apache/bifromq/inbox/server/InboxFetchPipelineMappingTest.java
new file mode 100644
index 000000000..071fab65c
--- /dev/null
+++ b/bifromq-inbox/bifromq-inbox-server/src/test/java/org/apache/bifromq/inbox/server/InboxFetchPipelineMappingTest.java
@@ -0,0 +1,240 @@
+/*
+ * 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.bifromq.inbox.server;
+
+import static org.apache.bifromq.inbox.util.PipelineUtil.PIPELINE_ATTR_KEY_DELIVERERKEY;
+import static org.apache.bifromq.inbox.util.PipelineUtil.PIPELINE_ATTR_KEY_ID;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import io.grpc.Context;
+import io.grpc.stub.ServerCallStreamObserver;
+import io.micrometer.core.instrument.Timer;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.LinkedBlockingQueue;
+import lombok.SneakyThrows;
+import org.apache.bifromq.baserpc.RPCContext;
+import org.apache.bifromq.baserpc.metrics.IRPCMeter;
+import org.apache.bifromq.baserpc.metrics.RPCMetric;
+import org.apache.bifromq.inbox.rpc.proto.InboxFetchHint;
+import org.apache.bifromq.inbox.rpc.proto.InboxFetched;
+import org.apache.bifromq.inbox.server.scheduler.FetchRequest;
+import org.apache.bifromq.inbox.storage.proto.Fetched;
+import org.apache.bifromq.inbox.storage.proto.InboxMessage;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.stubbing.Answer;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class InboxFetchPipelineMappingTest {
+ private static final String TENANT = "tenantA";
+ private static final String DELIVERER = "delivererA";
+ private static final String INBOX = "inboxA";
+ private static final long INCARNATION = 1L;
+ private final List<InboxFetched> received = new ArrayList<>();
+ private AutoCloseable closeable;
+ @Mock
+ private ServerCallStreamObserver<InboxFetched> responseObserver;
+
+ private static InboxFetchHint hint(long sessionId, int capacity) {
+ return hint(sessionId, capacity, -1, -1);
+ }
+
+ private static InboxFetchHint hint(long sessionId,
+ int capacity,
+ long lastFetchQoS0Seq,
+ long lastFetchSendBufferSeq) {
+ return InboxFetchHint.newBuilder()
+ .setSessionId(sessionId)
+ .setInboxId(INBOX)
+ .setIncarnation(INCARNATION)
+ .setCapacity(capacity)
+ .setLastFetchQoS0Seq(lastFetchQoS0Seq)
+ .setLastFetchSendBufferSeq(lastFetchSendBufferSeq)
+ .build();
+ }
+
+ @BeforeMethod
+ public void setup() {
+ closeable = MockitoAnnotations.openMocks(this);
+ setupContext();
+ doAnswer((Answer<Void>) invocation -> {
+ InboxFetched v = invocation.getArgument(0);
+ synchronized (received) {
+ received.add(v);
+ }
+ return null;
+ }).when(responseObserver).onNext(any());
+ }
+
+ private void setupContext() {
+ Map<String, String> meta = new HashMap<>();
+ meta.put(PIPELINE_ATTR_KEY_ID, "p1");
+ meta.put(PIPELINE_ATTR_KEY_DELIVERERKEY, DELIVERER);
+ Context.current()
+ .withValue(RPCContext.TENANT_ID_CTX_KEY, TENANT)
+ .withValue(RPCContext.CUSTOM_METADATA_CTX_KEY, meta)
+ .withValue(RPCContext.METER_KEY_CTX_KEY, new IRPCMeter.IRPCMethodMeter() {
+ @Override
+ public void recordCount(RPCMetric metric) {}
+
+ @Override
+ public void recordCount(RPCMetric metric, double inc) {}
+
+ @Override
+ public Timer timer(RPCMetric metric) {
+ return Timer.builder("dummy").register(new SimpleMeterRegistry());
+ }
+
+ @Override
+ public void recordSummary(RPCMetric metric, int depth) {}
+ }).attach();
+ }
+
+ @SneakyThrows
+ @AfterMethod
+ public void teardown() {
+ closeable.close();
+ }
+
+ private InboxFetchPipeline.Fetcher noopFetcher() {
+ return req -> CompletableFuture.completedFuture(Fetched.newBuilder()
+ .setResult(Fetched.Result.OK)
+ .build());
+ }
+
+ @Test
+ public void closeOneSessionShouldNotRemoveOthers() {
+ InboxFetcherRegistry registry = new InboxFetcherRegistry();
+ InboxFetchPipeline pipeline = new InboxFetchPipeline(responseObserver, noopFetcher(), registry);
+
+ long sessionA = 1001L;
+ long sessionB = 2002L;
+
+ pipeline.onNext(hint(sessionA, 10));
+ pipeline.onNext(hint(sessionB, 10));
+
+ await().until(() -> {
+ synchronized (received) {
+ return received.size() >= 2;
+ }
+ });
+
+ // close session B (capacity < 0)
+ pipeline.onNext(hint(sessionB, -1));
+
+ // signal fetch for the inbox; should still reach session A only
+ boolean signalled = pipeline.signalFetch(INBOX, INCARNATION, System.nanoTime());
+ assertTrue(signalled);
+
+ await().until(() -> {
+ synchronized (received) {
+ return received.size() >= 3;
+ }
+ });
+ InboxFetched last = lastReceived();
+ assertEquals(last.getSessionId(), sessionA);
+ }
+
+ @Test
+ public void shouldNotRewindStartAfterWhenHintIsStale() {
+ InboxFetcherRegistry registry = new InboxFetcherRegistry();
+ TestFetcher fetcher = new TestFetcher();
+ InboxFetchPipeline pipeline = new InboxFetchPipeline(responseObserver, fetcher, registry);
+
+ long sessionId = 3003L;
+ pipeline.onNext(hint(sessionId, 2, -1, -1));
+
+ FetchRequest firstRequest = fetcher.awaitRequest();
+ assertEquals(firstRequest.params().getQos0StartAfter(), -1);
+ assertEquals(firstRequest.params().getSendBufferStartAfter(), -1);
+
+ fetcher.completeNext(Fetched.newBuilder()
+ .setResult(Fetched.Result.OK)
+ .addQos0Msg(InboxMessage.newBuilder().setSeq(5).build())
+ .addQos0Msg(InboxMessage.newBuilder().setSeq(6).build())
+ .addSendBufferMsg(InboxMessage.newBuilder().setSeq(10).build())
+ .addSendBufferMsg(InboxMessage.newBuilder().setSeq(11).build())
+ .build());
+
+ await().until(() -> {
+ synchronized (received) {
+ return !received.isEmpty();
+ }
+ });
+
+ pipeline.onNext(hint(sessionId, 3, 1, 7));
+
+ FetchRequest secondRequest = fetcher.awaitRequest();
+ assertEquals(secondRequest.params().getQos0StartAfter(), 6);
+ assertEquals(secondRequest.params().getSendBufferStartAfter(), 11);
+
+ fetcher.completeNext(Fetched.newBuilder()
+ .setResult(Fetched.Result.OK)
+ .build());
+
+ pipeline.close();
+ }
+
+ private InboxFetched lastReceived() {
+ synchronized (received) {
+ return received.get(received.size() - 1);
+ }
+ }
+
+ private static class TestFetcher implements InboxFetchPipeline.Fetcher {
+ private final BlockingQueue<FetchRequest> requests = new LinkedBlockingQueue<>();
+ private final BlockingQueue<CompletableFuture<Fetched>> responses = new LinkedBlockingQueue<>();
+
+ @Override
+ public CompletableFuture<Fetched> fetch(FetchRequest request) {
+ CompletableFuture<Fetched> future = new CompletableFuture<>();
+ requests.add(request);
+ responses.add(future);
+ return future;
+ }
+
+ FetchRequest awaitRequest() {
+ await().until(() -> !requests.isEmpty());
+ FetchRequest request = requests.poll();
+ assertNotNull(request);
+ return request;
+ }
+
+ void completeNext(Fetched fetched) {
+ await().until(() -> !responses.isEmpty());
+ CompletableFuture<Fetched> future = responses.poll();
+ assertNotNull(future);
+ future.complete(fetched);
+ }
+ }
+}
diff --git a/bifromq-inbox/bifromq-inbox-store-schema/src/main/java/org/apache/bifromq/inbox/store/schema/KVSchemaUtil.java b/bifromq-inbox/bifromq-inbox-store-schema/src/main/java/org/apache/bifromq/inbox/store/schema/KVSchemaUtil.java
index 41c6d2eeb..f0a2961e1 100644
--- a/bifromq-inbox/bifromq-inbox-store-schema/src/main/java/org/apache/bifromq/inbox/store/schema/KVSchemaUtil.java
+++ b/bifromq-inbox/bifromq-inbox-store-schema/src/main/java/org/apache/bifromq/inbox/store/schema/KVSchemaUtil.java
@@ -14,14 +14,14 @@
* "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.
+ * under the License.
*/
package org.apache.bifromq.inbox.store.schema;
+import static com.google.protobuf.UnsafeByteOperations.unsafeWrap;
import static org.apache.bifromq.util.BSUtil.toByteString;
import static org.apache.bifromq.util.BSUtil.toShort;
-import static com.google.protobuf.UnsafeByteOperations.unsafeWrap;
import com.google.protobuf.ByteString;
import java.nio.charset.StandardCharsets;
@@ -98,7 +98,7 @@ public class KVSchemaUtil {
}
private static int inboxInstanceStartKeyPrefixLength(ByteString inboxStoreKey) {
- // inboxInstanceStartKeyPrefix: <INBOX_INSTANCE_START_KEY_PREFIX><incarnation>
+ // inboxInstanceStartKeyPrefix: <INBOX_START_KEY_PREFIX><incarnation>
return inboxStartKeyPrefixLength(inboxStoreKey) + Long.BYTES;
}
@@ -117,6 +117,10 @@ public class KVSchemaUtil {
return false;
}
+ public static ByteString parseInboxStartKeyPrefix(ByteString inboxInstanceStartKey) {
+ return inboxInstanceStartKey.substring(0, inboxInstanceStartKey.size() - Long.BYTES);
+ }
+
public static String parseTenantId(ByteString inboxStoreKey) {
int tenantIdLength = tenantIdLength(inboxStoreKey);
int startAt = SCHEMA_VER.size() + Short.BYTES;
diff --git a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStore.java b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStore.java
index b8794178a..3cfe64333 100644
--- a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStore.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStore.java
@@ -22,11 +22,9 @@ package org.apache.bifromq.inbox.store;
import com.google.common.util.concurrent.MoreExecutors;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
-import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
@@ -37,7 +35,6 @@ import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.bifromq.base.util.AsyncRunner;
import org.apache.bifromq.baseenv.EnvProvider;
-import org.apache.bifromq.basehlc.HLC;
import org.apache.bifromq.basehookloader.BaseHookLoader;
import org.apache.bifromq.basekv.balance.KVStoreBalanceController;
import org.apache.bifromq.basekv.client.IBaseKVStoreClient;
@@ -57,15 +54,12 @@ class InboxStore implements IInboxStore {
private final AsyncRunner jobRunner;
private final ScheduledExecutorService jobScheduler;
private final boolean jobExecutorOwner;
- private final Duration gcInterval;
private final List<IInboxStoreBalancerFactory> effectiveBalancerFactories = new LinkedList<>();
- private IInboxStoreGCProcessor inboxStoreGCProc;
- private volatile CompletableFuture<Void> gcJob;
+ private final InboxStoreCleaner cleaner;
InboxStore(InboxStoreBuilder builder) {
this.clusterId = builder.clusterId;
this.inboxStoreClient = builder.inboxStoreClient;
- this.gcInterval = builder.gcInterval;
coProcFactory =
new InboxStoreCoProcFactory(
builder.distClient,
@@ -133,6 +127,8 @@ class InboxStore implements IInboxStore {
.attributes(builder.attributes)
.finish()
.build();
+ this.cleaner = new InboxStoreCleaner(inboxStoreClient, builder.minGCInterval, builder.maxGCInterval,
+ jobScheduler);
start();
}
@@ -144,15 +140,15 @@ class InboxStore implements IInboxStore {
if (status.compareAndSet(Status.INIT, Status.STARTING)) {
log.info("Starting inbox store");
storeServer.start();
+ String storeId = storeServer.storeId(clusterId);
balanceController.start(storeServer.storeId(clusterId));
status.compareAndSet(Status.STARTING, Status.STARTED);
- this.inboxStoreGCProc = new InboxStoreGCProcessor(inboxStoreClient, id());
inboxStoreClient
.connState()
// observe the first READY state
.filter(connState -> connState == IConnectable.ConnState.READY)
.takeUntil(connState -> connState == IConnectable.ConnState.READY)
- .doOnComplete(() -> scheduleGC(Duration.ofSeconds(5)))
+ .doOnComplete(() -> cleaner.start(storeId))
.subscribe();
log.debug("Inbox store started");
}
@@ -162,6 +158,7 @@ class InboxStore implements IInboxStore {
if (status.compareAndSet(Status.STARTED, Status.STOPPING)) {
log.info("Stopping InboxStore");
jobRunner.awaitDone().toCompletableFuture().join();
+ cleaner.stop().join();
balanceController.stop();
storeServer.stop();
log.debug("Stopping CoProcFactory");
@@ -177,28 +174,6 @@ class InboxStore implements IInboxStore {
}
}
- private void scheduleGC(Duration delay) {
- if (status.get() != Status.STARTED) {
- return;
- }
- jobScheduler.schedule(this::gc, delay.toMillis(), TimeUnit.MILLISECONDS);
- }
-
- private void gc() {
- jobRunner.add(() -> {
- if (status.get() != Status.STARTED) {
- return;
- }
- long reqId = HLC.INST.getPhysical();
- log.debug("Start GC job, reqId={}", reqId);
- gcJob = inboxStoreGCProc.gc(reqId, HLC.INST.getPhysical())
- .handle((v, e) -> {
- scheduleGC(gcInterval);
- return null;
- });
- });
- }
-
private enum Status {
INIT, STARTING, STARTED, STOPPING, STOPPED
}
diff --git a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreBuilder.java b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreBuilder.java
index fc3bd8552..8c2966abd 100644
--- a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreBuilder.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreBuilder.java
@@ -73,7 +73,8 @@ public class InboxStoreBuilder {
Duration detachTimeout = Duration.ofSeconds(PersistentSessionDetachTimeoutSecond.INSTANCE.get());
Duration metaCacheExpireTime = Duration.ofSeconds(InboxMetaCacheExpirySeconds.INSTANCE.get());
int expireRateLimit = 1000;
- Duration gcInterval = Duration.ofMinutes(5);
+ Duration minGCInterval = Duration.ofMinutes(5);
+ Duration maxGCInterval = Duration.ofHours(24);
Map<String, String> attributes = new HashMap<>();
public IInboxStore build() {
diff --git a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCleaner.java
similarity index 61%
copy from bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java
copy to bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCleaner.java
index bbcc20549..6cdf4fb7f 100644
--- a/bifromq-dist/bifromq-dist-worker/src/main/java/org/apache/bifromq/dist/worker/DistWorkerCleaner.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCleaner.java
@@ -17,18 +17,22 @@
* under the License.
*/
-package org.apache.bifromq.dist.worker;
+package org.apache.bifromq.inbox.store;
import static org.apache.bifromq.basekv.client.KVRangeRouterUtil.findByBoundary;
import static org.apache.bifromq.basekv.utils.BoundaryUtil.FULL_BOUNDARY;
+import static org.apache.bifromq.basekv.utils.BoundaryUtil.clampToBoundary;
import com.google.protobuf.ByteString;
+import io.micrometer.core.instrument.Gauge;
+import io.micrometer.core.instrument.Metrics;
+import io.micrometer.core.instrument.Tags;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
-import java.util.List;
+import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
@@ -46,21 +50,23 @@ import org.apache.bifromq.basekv.store.proto.ROCoProcInput;
import org.apache.bifromq.basekv.store.proto.ReplyCode;
import org.apache.bifromq.basekv.utils.BoundaryUtil;
import org.apache.bifromq.basekv.utils.KVRangeIdUtil;
-import org.apache.bifromq.dist.rpc.proto.DistServiceROCoProcInput;
-import org.apache.bifromq.dist.rpc.proto.GCReply;
-import org.apache.bifromq.dist.rpc.proto.GCRequest;
+import org.apache.bifromq.inbox.storage.proto.GCReply;
+import org.apache.bifromq.inbox.storage.proto.GCRequest;
+import org.apache.bifromq.inbox.storage.proto.InboxServiceROCoProcInput;
@Slf4j
-class DistWorkerCleaner {
+class InboxStoreCleaner {
private static final int MAX_STEP = 10;
private static final int SCAN_QUOTA_BASE = 512;
+ private static final int FIRST_SWEEP_SCAN_QUOTA = 50_000;
+ private static final Duration FIRST_SWEEP_INTERVAL = Duration.ofSeconds(5);
private static final double HIGH_SUCCESS_RATIO = 0.005; // 0.5%
private static final int LOW_HIT_THRESHOLD = 3;
private static final double QUOTA_HIT_RATIO = 0.8;
private static final double GROWTH = 1.5;
private static final double SHRINK = 2.0;
private final AtomicBoolean started = new AtomicBoolean(false);
- private final IBaseKVStoreClient distWorkerClient;
+ private final IBaseKVStoreClient inboxStoreClient;
private final Duration minCleanInterval;
private final Duration maxCleanInterval;
private final ScheduledExecutorService jobScheduler;
@@ -69,28 +75,33 @@ class DistWorkerCleaner {
private final Map<KVRangeId, RangeGcState> rangeStates = new HashMap<>();
private volatile ScheduledFuture<?> cleanerFuture;
- DistWorkerCleaner(IBaseKVStoreClient distWorkerClient,
+ InboxStoreCleaner(IBaseKVStoreClient inboxStoreClient,
Duration minCleanInterval,
Duration maxCleanInterval,
ScheduledExecutorService jobScheduler) {
- this(distWorkerClient, minCleanInterval, maxCleanInterval, jobScheduler, Clock.systemUTC());
+ this(inboxStoreClient, minCleanInterval, maxCleanInterval, jobScheduler, Clock.systemUTC());
}
- DistWorkerCleaner(IBaseKVStoreClient distWorkerClient,
+ InboxStoreCleaner(IBaseKVStoreClient inboxStoreClient,
Duration minCleanInterval,
Duration maxCleanInterval,
ScheduledExecutorService jobScheduler,
Clock clock) {
- this.distWorkerClient = distWorkerClient;
+ this.inboxStoreClient = inboxStoreClient;
this.minCleanInterval = minCleanInterval;
this.maxCleanInterval = maxCleanInterval;
this.jobScheduler = jobScheduler;
this.clock = clock;
}
+ private static boolean equalsBoundary(Boundary a, Boundary b) {
+ return BoundaryUtil.compareStartKey(BoundaryUtil.startKey(a), BoundaryUtil.startKey(b)) == 0
+ && BoundaryUtil.compareEndKeys(BoundaryUtil.endKey(a), BoundaryUtil.endKey(b)) == 0;
+ }
+
void start(String storeId) {
if (started.compareAndSet(false, true)) {
- log.debug("DistWorkerCleaner started");
+ log.info("InboxStoreCleaner started");
doStart(storeId);
}
}
@@ -100,7 +111,17 @@ class DistWorkerCleaner {
cleanerFuture.cancel(true);
CompletableFuture<Void> onDone = new CompletableFuture<>();
jobScheduler.execute(() -> {
- log.debug("DistWorkerCleaner stopped");
+ log.info("InboxStoreCleaner stopped");
+ // remove all gauges on stop
+ for (RangeGcState st : rangeStates.values()) {
+ if (st.stepGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.stepGauge.getId());
+ }
+ if (st.intervalGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.intervalGauge.getId());
+ }
+ }
+ rangeStates.clear();
onDone.complete(null);
});
return onDone;
@@ -125,63 +146,80 @@ class DistWorkerCleaner {
anyDueNow = true;
}
}
- Duration delay = anyDueNow ? Duration.ZERO : (chosenDelay != null ? chosenDelay : minCleanInterval);
- log.debug("DistWorkerCleaner next round in {} ms", delay.toMillis());
+ Duration delay = anyDueNow ? Duration.ZERO : chosenDelay == null ? minCleanInterval : chosenDelay;
cleanerFuture = jobScheduler.schedule(() -> {
- doGC(storeId).thenRun(() -> doStart(storeId));
+ doClean(storeId).thenRun(() -> doStart(storeId));
}, delay.toMillis(), TimeUnit.MILLISECONDS);
}
- private CompletableFuture<Void> doGC(String storeId) {
- Collection<KVRangeSetting> leaders = findByBoundary(FULL_BOUNDARY, distWorkerClient.latestEffectiveRouter())
+ private CompletableFuture<Void> doClean(String storeId) {
+ if (!started.get()) {
+ return CompletableFuture.completedFuture(null);
+ }
+ Collection<KVRangeSetting> leaders = findByBoundary(FULL_BOUNDARY, inboxStoreClient.latestEffectiveRouter())
.stream().filter(r -> r.leader().equals(storeId)).toList();
-
Map<KVRangeId, KVRangeSetting> currentLeaderMap = new HashMap<>();
for (KVRangeSetting rs : leaders) {
currentLeaderMap.put(rs.id(), rs);
- RangeGcState state = rangeStates.get(rs.id());
- if (state == null) {
- state = new RangeGcState();
- state.step = MAX_STEP;
- state.interval = minCleanInterval;
+ RangeGcState state = rangeStates.computeIfAbsent(rs.id(), rid -> {
+ RangeGcState ns = new RangeGcState();
+ ns.step = 1;
+ ns.interval = FIRST_SWEEP_INTERVAL;
+ ns.lowRatioHits = 0;
+ ns.wrappedOnce = false;
+ ns.nextDue = clock.instant();
+ ns.ver = rs.ver();
+ ns.boundary = rs.boundary();
+ ns.sprinted = false;
+ // register per-range gauges when state created
+ Tags tags = Tags.of("storeId", storeId).and("rangeId", KVRangeIdUtil.toString(rs.id()));
+ ns.intervalGauge = Gauge.builder("inbox.gc.interval.ms", ns, s -> s.interval.toMillis())
+ .tags(tags)
+ .register(Metrics.globalRegistry);
+ ns.stepGauge = Gauge.builder("inbox.gc.step", ns, s -> (double) s.step)
+ .tags(tags)
+ .register(Metrics.globalRegistry);
+ return ns;
+ });
+ if (state.ver != rs.ver() || !equalsBoundary(state.boundary, rs.boundary())) {
+ if (state.nextKey != null) {
+ state.nextKey = clampToBoundary(state.nextKey, rs.boundary());
+ }
+ state.step = 1;
+ state.interval = state.sprinted ? minCleanInterval : FIRST_SWEEP_INTERVAL;
state.lowRatioHits = 0;
- state.nextDue = Instant.EPOCH; // run asap
+ state.wrappedOnce = false;
state.ver = rs.ver();
state.boundary = rs.boundary();
- state.wrappedOnce = false;
- rangeStates.put(rs.id(), state);
- } else {
- if (state.ver != rs.ver() || !state.boundary.equals(rs.boundary())) {
- // clamp nextKey into new boundary and reset step/interval
- if (state.nextKey != null) {
- state.nextKey = clampToBoundary(state.nextKey, rs.boundary());
- }
- state.step = 1;
- state.interval = minCleanInterval;
- state.lowRatioHits = 0;
- state.wrappedOnce = false;
- state.ver = rs.ver();
- state.boundary = rs.boundary();
+ }
+ }
+ // clean up metrics for ranges no longer led by this store
+ Iterator<Map.Entry<KVRangeId, RangeGcState>> iter = rangeStates.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry<KVRangeId, RangeGcState> e = iter.next();
+ if (!currentLeaderMap.containsKey(e.getKey())) {
+ RangeGcState st = e.getValue();
+ if (st.stepGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.stepGauge.getId());
+ }
+ if (st.intervalGauge != null) {
+ Metrics.globalRegistry.removeByPreFilterId(st.intervalGauge.getId());
}
+ iter.remove();
}
}
- // remove states for ranges not leader anymore
- rangeStates.keySet().removeIf(rid -> !currentLeaderMap.containsKey(rid));
long reqId = HLC.INST.getPhysical();
Instant now = clock.instant();
- List<CompletableFuture<?>> futures = leaders.stream()
+ CompletableFuture<?>[] futures = leaders.stream()
.map(rs -> {
RangeGcState s = rangeStates.get(rs.id());
- if (s == null) {
- return CompletableFuture.<Void>completedFuture(null);
+ if (s == null || s.nextDue.isAfter(now)) {
+ return CompletableFuture.completedFuture(null);
}
- if (s.nextDue.isAfter(now)) {
- return CompletableFuture.<Void>completedFuture(null);
- }
- GCRequest.Builder gcReq = GCRequest.newBuilder().setReqId(reqId)
- .setStepHint(s.step)
- .setScanQuota(SCAN_QUOTA_BASE * s.step);
+ GCRequest.Builder gcReq = GCRequest.newBuilder().setNow(now.toEpochMilli());
+ int quotaToUse = s.sprinted ? SCAN_QUOTA_BASE * s.step : FIRST_SWEEP_SCAN_QUOTA;
+ gcReq.setScanQuota(quotaToUse);
if (s.nextKey != null) {
ByteString start = clampToBoundary(s.nextKey, rs.boundary());
if (start != null) {
@@ -189,14 +227,15 @@ class DistWorkerCleaner {
}
}
String rangeIdStr = KVRangeIdUtil.toString(rs.id());
- log.debug("[DistWorker] start gc: reqId={}, rangeId={}, step={}, quota={}",
- reqId, rangeIdStr, s.step, SCAN_QUOTA_BASE * s.step);
- return distWorkerClient.query(rs.leader(), KVRangeRORequest.newBuilder()
+ log.debug("[InboxStore] start gc: reqId={}, rangeId={}, step={}, quota={}",
+ reqId, rangeIdStr, s.step, quotaToUse);
+ return inboxStoreClient.query(rs.leader(), KVRangeRORequest.newBuilder()
.setReqId(reqId)
.setKvRangeId(rs.id())
.setVer(rs.ver())
.setRoCoProc(ROCoProcInput.newBuilder()
- .setDistService(DistServiceROCoProcInput.newBuilder()
+ .setInboxService(InboxServiceROCoProcInput.newBuilder()
+ .setReqId(reqId)
.setGc(gcReq.build())
.build())
.build())
@@ -204,20 +243,20 @@ class DistWorkerCleaner {
.handle((v, e) -> {
try {
if (e != null) {
- log.debug("[DistWorker] gc error: reqId={}, rangeId={}", reqId, rangeIdStr, e);
+ log.debug("[InboxStore] gc error: reqId={}, rangeId={}", reqId, rangeIdStr, e);
onGCFailure(s);
return null;
}
if (v.getCode() != ReplyCode.Ok) {
- log.debug("[DistWorker] gc rejected: reqId={}, rangeId={}, reason={}", reqId,
+ log.debug("[InboxStore] gc rejected: reqId={}, rangeId={}, reason={}", reqId,
rangeIdStr, v.getCode());
onGCFailure(s);
return null;
}
- GCReply reply = v.getRoCoProcResult().getDistService().getGc();
+ GCReply reply = v.getRoCoProcResult().getInboxService().getGc();
onGCSuccess(s, reply);
log.debug(
- "[DistWorker] gc done: reqId={}, rangeId={}, inspected={}, removeSuccess={}, wrapped={}",
+ "[InboxStore] gc done: reqId={}, rangeId={}, inspected={}, removed={}, wrapped={}",
reqId, rangeIdStr, reply.getInspectedCount(), reply.getRemoveSuccess(),
reply.getWrapped());
} finally {
@@ -226,14 +265,13 @@ class DistWorkerCleaner {
return null;
});
})
- .toList();
- return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
+ .toArray(CompletableFuture[]::new);
+ return CompletableFuture.allOf(futures);
}
private void onGCFailure(RangeGcState s) {
- // reset on failure
s.step = 1;
- s.interval = minCleanInterval;
+ s.interval = s.sprinted ? minCleanInterval : FIRST_SWEEP_INTERVAL;
s.lowRatioHits = 0;
s.wrappedOnce = false;
}
@@ -247,13 +285,22 @@ class DistWorkerCleaner {
if (reply.getWrapped()) {
s.wrappedOnce = true;
}
+ if (!s.sprinted) {
+ if (reply.getWrapped()) {
+ s.sprinted = true;
+ s.step = 1;
+ s.interval = minCleanInterval;
+ s.lowRatioHits = 0;
+ s.wrappedOnce = false;
+ }
+ return;
+ }
int inspected = reply.getInspectedCount();
int removeSuccess = reply.getRemoveSuccess();
double successRatio = inspected == 0 ? 0 : ((double) removeSuccess) / inspected;
int scanQuota = SCAN_QUOTA_BASE * Math.max(1, s.step);
boolean coverageOK = s.wrappedOnce || inspected >= (int) (scanQuota * QUOTA_HIT_RATIO);
- // Shrink when removal success ratio is high
if (successRatio >= HIGH_SUCCESS_RATIO) {
s.step = Math.max(s.step / 2, 1);
long shrunk = (long) (s.interval.toMillis() / SHRINK);
@@ -261,21 +308,18 @@ class DistWorkerCleaner {
s.lowRatioHits = 0;
s.wrappedOnce = false;
} else {
- // Grow only when no removals for sustained rounds with sufficient coverage and a full wrap
if (coverageOK && removeSuccess == 0) {
s.lowRatioHits++;
if (s.lowRatioHits >= LOW_HIT_THRESHOLD && s.wrappedOnce) {
- // grow step only when quota is sufficiently utilized
if (inspected >= (int) (scanQuota * QUOTA_HIT_RATIO)) {
s.step = Math.min(s.step + 1, MAX_STEP);
}
long grown = (long) (s.interval.toMillis() * GROWTH);
s.interval = Duration.ofMillis(Math.min(grown, maxCleanInterval.toMillis()));
s.lowRatioHits = 0;
- s.wrappedOnce = false; // require another full wrap before next growth
+ s.wrappedOnce = false;
}
} else {
- // If not yet wrapped once and this round didn't wrap, accelerate to finish a full circle
if (!s.wrappedOnce) {
s.interval = minCleanInterval;
}
@@ -283,21 +327,6 @@ class DistWorkerCleaner {
}
}
- private ByteString clampToBoundary(ByteString key, Boundary boundary) {
- if (key == null) {
- return null;
- }
- ByteString startBoundary = BoundaryUtil.startKey(boundary);
- ByteString endBoundary = BoundaryUtil.endKey(boundary);
- if (startBoundary != null && BoundaryUtil.compare(key, startBoundary) < 0) {
- return startBoundary;
- }
- if (endBoundary != null && BoundaryUtil.compare(key, endBoundary) >= 0) {
- return startBoundary;
- }
- return key;
- }
-
private static class RangeGcState {
ByteString nextKey;
int step;
@@ -307,5 +336,9 @@ class DistWorkerCleaner {
Instant nextDue;
long ver;
Boundary boundary;
+ boolean sprinted;
+ // metrics
+ Gauge stepGauge; // gauge for adaptive step
+ Gauge intervalGauge; // gauge for gc interval in ms
}
}
diff --git a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCoProc.java b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCoProc.java
index 53a3abb39..4a2440ac7 100644
--- a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCoProc.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/InboxStoreCoProc.java
@@ -27,6 +27,7 @@ import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.inboxStartKeyPr
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.isInboxInstanceKey;
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.isInboxInstanceStartKey;
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.parseInboxInstanceStartKeyPrefix;
+import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.parseInboxStartKeyPrefix;
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.parseSeq;
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.parseTenantId;
import static org.apache.bifromq.inbox.store.schema.KVSchemaUtil.qos0QueuePrefix;
@@ -56,6 +57,8 @@ import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
@@ -792,21 +795,13 @@ final class InboxStoreCoProc implements IKVRangeCoProc {
TenantInboxInstance inboxInstance = new TenantInboxInstance(
TENANT_ID_INTERNER.intern(tenantId),
new InboxInstance(metadata.getInboxId(), metadata.getIncarnation()));
- // schedule a task for sending LWT or expiry session
+ // schedule tasks for historical incarnations immediately
if (metadata.hasLwt()) {
- Duration delay = ofSeconds(
- Integer.compareUnsigned(metadata.getLwt().getDelaySeconds(), metadata.getExpirySeconds())
- < 0 ? metadata.getLwt().getDelaySeconds() : metadata.getExpirySeconds())
- .plusMillis(ThreadLocalRandom.current().nextLong(0, 1000));
delayTaskRunner.scheduleIfAbsent(inboxInstance,
- new SendLWTTask(delay, metadata.getMod(), inboxClient));
+ new SendLWTTask(Duration.ZERO, metadata.getMod(), inboxClient));
} else {
- if (Integer.compareUnsigned(metadata.getExpirySeconds(), UINT_MAX) < 0) {
- // UINT_MAX never expire according to MQTT5 spec
- Duration delay = ofSeconds(metadata.getExpirySeconds());
- delayTaskRunner.scheduleIfAbsent(inboxInstance,
- new ExpireInboxTask(delay, metadata.getMod(), inboxClient));
- }
+ delayTaskRunner.scheduleIfAbsent(inboxInstance,
+ new ExpireInboxTask(Duration.ZERO, metadata.getMod(), inboxClient));
}
}));
};
@@ -889,21 +884,13 @@ final class InboxStoreCoProc implements IKVRangeCoProc {
TenantInboxInstance inboxInstance = new TenantInboxInstance(
TENANT_ID_INTERNER.intern(tenantId),
new InboxInstance(metadata.getInboxId(), metadata.getIncarnation()));
- // schedule a task for sending LWT or expiry session
+ // schedule tasks for historical incarnations immediately
if (metadata.hasLwt()) {
- Duration delay = ofSeconds(
- Integer.compareUnsigned(metadata.getLwt().getDelaySeconds(), metadata.getExpirySeconds())
- < 0 ? metadata.getLwt().getDelaySeconds() : metadata.getExpirySeconds())
- .plusMillis(ThreadLocalRandom.current().nextLong(0, 1000));
delayTaskRunner.scheduleIfAbsent(inboxInstance,
- new SendLWTTask(delay, metadata.getMod(), inboxClient));
+ new SendLWTTask(Duration.ZERO, metadata.getMod(), inboxClient));
} else {
- if (Integer.compareUnsigned(metadata.getExpirySeconds(), UINT_MAX) < 0) {
- // UINT_MAX never expire according to MQTT5 spec
- Duration delay = ofSeconds(metadata.getExpirySeconds());
- delayTaskRunner.scheduleIfAbsent(inboxInstance,
- new ExpireInboxTask(delay, metadata.getMod(), inboxClient));
- }
+ delayTaskRunner.scheduleIfAbsent(inboxInstance,
+ new ExpireInboxTask(Duration.ZERO, metadata.getMod(), inboxClient));
}
}));
};
@@ -1161,16 +1148,126 @@ final class InboxStoreCoProc implements IKVRangeCoProc {
@SneakyThrows
private CompletableFuture<GCReply> gc(GCRequest request, IKVRangeReader reader) {
+ int scanQuota = request.getScanQuota();
+ AtomicInteger inspectedAcc = new AtomicInteger();
+ AtomicBoolean wrapped = new AtomicBoolean(false);
+ AtomicReference<ByteString> nextStartKeyRef = new AtomicReference<>(null);
+ List<CompletableFuture<Integer>> inboxFutures = new LinkedList<>();
+ int probe = 0;
try (IKVIterator itr = reader.iterator()) {
- List<CompletableFuture<Void>> expireFutures = new LinkedList<>();
- for (itr.seekToFirst(); itr.isValid(); ) {
- String tenantId = parseTenantId(itr.key());
- expireFutures.add(expireTenant(tenantId, Duration.ZERO, request.getNow(), reader));
- itr.seek(upperBound(tenantBeginKeyPrefix(tenantId)));
- }
- return CompletableFuture.allOf(expireFutures.toArray(CompletableFuture[]::new))
- .thenApply(v -> GCReply.newBuilder().build());
+ if (request.hasStartKey()) {
+ ByteString start = request.getStartKey();
+ if (isInboxInstanceKey(start)) {
+ itr.seek(parseInboxInstanceStartKeyPrefix(start));
+ } else {
+ itr.seek(start);
+ }
+ if (!itr.isValid()) {
+ wrapped.set(true);
+ itr.seekToFirst();
+ }
+ } else {
+ itr.seekToFirst();
+ }
+
+ while (itr.isValid() && inspectedAcc.get() < scanQuota) {
+ ByteString key = itr.key();
+ if (!isInboxInstanceStartKey(key)) {
+ if (isInboxInstanceKey(key)) {
+ ByteString inboxPrefix = parseInboxInstanceStartKeyPrefix(key);
+ itr.seek(upperBound(parseInboxStartKeyPrefix(inboxPrefix)));
+ probe = 0;
+ } else {
+ if (probe < 20) {
+ itr.next();
+ probe++;
+ } else {
+ String tenantId = parseTenantId(key);
+ itr.seek(upperBound(tenantBeginKeyPrefix(tenantId)));
+ probe = 0;
+ }
+ }
+ continue;
+ }
+
+ InboxMetadata metadata;
+ try {
+ metadata = InboxMetadata.parseFrom(itr.value());
+ } catch (InvalidProtocolBufferException e) {
+ ByteString inboxPrefix = parseInboxInstanceStartKeyPrefix(key);
+ itr.seek(upperBound(parseInboxStartKeyPrefix(inboxPrefix)));
+ probe = 0;
+ continue;
+ }
+
+ String tenantId = parseTenantId(key);
+ String inboxId = metadata.getInboxId();
+ SortedMap<Long, InboxMetadata> inboxVersions = getAllInboxVersions(tenantId, inboxId, reader);
+ if (inboxVersions.isEmpty()) {
+ // inconsistent state, skip this inbox group
+ ByteString inboxPrefix = parseInboxInstanceStartKeyPrefix(key);
+ itr.seek(upperBound(parseInboxStartKeyPrefix(inboxPrefix)));
+ probe = 0;
+ continue;
+ }
+
+ inspectedAcc.addAndGet(inboxVersions.size());
+
+ List<CompletableFuture<ExpireCheckResult>> checks = new LinkedList<>();
+ checkInboxOnline(tenantId, Duration.ZERO, request.getNow(), inboxVersions, checks);
+ CompletableFuture<Integer> inboxDone = CompletableFuture
+ .allOf(checks.toArray(CompletableFuture[]::new))
+ .thenApply(v -> {
+ int expiredCount = 0;
+ for (CompletableFuture<ExpireCheckResult> f : checks) {
+ ExpireCheckResult r = f.join();
+ if (r.expired) {
+ TenantInboxInstance inboxInstance = new TenantInboxInstance(
+ TENANT_ID_INTERNER.intern(tenantId),
+ new InboxInstance(r.metadata.getInboxId(), r.metadata.getIncarnation()));
+ delayTaskRunner.schedule(inboxInstance,
+ new ExpireInboxTask(Duration.ofMillis(0), r.metadata.getMod(), inboxClient));
+ expiredCount++;
+ }
+ }
+ return expiredCount;
+ });
+ inboxFutures.add(inboxDone);
+
+ ByteString inboxPrefix = parseInboxInstanceStartKeyPrefix(key);
+ itr.seek(upperBound(parseInboxStartKeyPrefix(inboxPrefix)));
+ probe = 0;
+ }
+
+ if (itr.isValid()) {
+ ByteString k = itr.key();
+ if (isInboxInstanceKey(k)) {
+ ByteString inboxPrefix = parseInboxInstanceStartKeyPrefix(k);
+ nextStartKeyRef.set(parseInboxStartKeyPrefix(inboxPrefix));
+ } else {
+ nextStartKeyRef.set(k);
+ }
+ } else {
+ wrapped.set(true);
+ }
}
+
+ final AtomicInteger removedAcc = new AtomicInteger();
+ CompletableFuture<?>[] waits = inboxFutures.stream()
+ .map(f -> f.thenAccept(removedAcc::addAndGet))
+ .toArray(CompletableFuture[]::new);
+ return CompletableFuture.allOf(waits).thenApply(v -> {
+ int removed = removedAcc.get();
+ GCReply.Builder reply = GCReply.newBuilder()
+ .setInspectedCount(inspectedAcc.get())
+ .setRemoveSuccess(removed)
+ .setWrapped(wrapped.get());
+ ByteString ns = nextStartKeyRef.get();
+ if (ns != null) {
+ reply.setNextStartKey(ns);
+ }
+ return reply.build();
+ });
}
private Runnable batchInsert(BatchInsertRequest request,
@@ -1819,6 +1916,7 @@ final class InboxStoreCoProc implements IKVRangeCoProc {
latestInboxMetadata.getClient().getMetadataMap().get(MQTT_USER_ID_KEY),
latestInboxMetadata.getClient().getMetadataMap().get(MQTT_CLIENT_ID_KEY));
futuresHolder.add(sessionDictClient.exist(clientId)
+ .exceptionally(e -> OnlineCheckResult.ERROR)
.thenApply((v) -> {
if (v == OnlineCheckResult.NOT_EXISTS) {
return new ExpireCheckResult(latestInboxMetadata, true);
diff --git a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/TenantsStats.java b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/TenantsStats.java
index 344fa3a7a..123fc122c 100644
--- a/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/TenantsStats.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/main/java/org/apache/bifromq/inbox/store/TenantsStats.java
@@ -198,7 +198,6 @@ public class TenantsStats implements ITenantStats {
tenantStatsMap.values().forEach(TenantStats::destroy);
tenantStatsMap.clear();
try (IKVRangeRefreshableReader reader = readerSupplier.get(); IKVIterator itr = reader.iterator()) {
- reader.refresh();
for (itr.seekToFirst(); itr.isValid(); ) {
String tenantId = parseTenantId(itr.key());
loadStats(tenantId, itr);
diff --git a/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxAttachEnsureRecoverIT.java b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxAttachEnsureRecoverIT.java
new file mode 100644
index 000000000..25c452896
--- /dev/null
+++ b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxAttachEnsureRecoverIT.java
@@ -0,0 +1,111 @@
+/*
+ * 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.bifromq.inbox.store;
+
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import org.apache.bifromq.basehlc.HLC;
+import org.apache.bifromq.inbox.rpc.proto.DeleteReply;
+import org.apache.bifromq.inbox.storage.proto.BatchAttachRequest;
+import org.apache.bifromq.inbox.storage.proto.BatchDetachReply;
+import org.apache.bifromq.inbox.storage.proto.BatchDetachRequest;
+import org.apache.bifromq.inbox.storage.proto.BatchExistRequest;
+import org.apache.bifromq.inbox.storage.proto.InboxVersion;
+import org.apache.bifromq.sessiondict.client.type.OnlineCheckResult;
+import org.apache.bifromq.type.ClientInfo;
+import org.testng.annotations.Test;
+
+public class InboxAttachEnsureRecoverIT extends InboxStoreTest {
+
+ @Test(groups = "integration")
+ public void ensureSchedulesImmediateExpireAfterRestart() throws Exception {
+ long now = HLC.INST.getPhysical();
+ String tenantId = "tenant-" + System.nanoTime();
+ String inboxId = "inbox-" + System.nanoTime();
+ long inc1 = System.nanoTime();
+ ClientInfo client = ClientInfo.newBuilder().setTenantId(tenantId).build();
+
+ when(sessionDictClient.exist(org.mockito.ArgumentMatchers.any()))
+ .thenReturn(CompletableFuture.completedFuture(OnlineCheckResult.NOT_EXISTS));
+ when(inboxClient.delete(org.mockito.ArgumentMatchers.any()))
+ .thenReturn(CompletableFuture.completedFuture(DeleteReply.newBuilder()
+ .setReqId(System.nanoTime())
+ .setCode(DeleteReply.Code.OK)
+ .build()));
+
+ InboxVersion v1 = requestAttach(BatchAttachRequest.Params.newBuilder()
+ .setInboxId(inboxId)
+ .setIncarnation(inc1)
+ .setExpirySeconds(3)
+ .setClient(client)
+ .setNow(now)
+ .build())
+ .get(0);
+
+ assertEquals(requestDetach(BatchDetachRequest.Params.newBuilder()
+ .setTenantId(tenantId)
+ .setInboxId(inboxId)
+ .setExpirySeconds(3)
+ .setVersion(v1)
+ .setNow(now)
+ .build())
+ .get(0), BatchDetachReply.Code.OK);
+
+ restartStoreServer();
+
+ await().forever().until(() -> {
+ try {
+ requestExist(BatchExistRequest.Params.newBuilder()
+ .setTenantId(tenantId)
+ .setInboxId(inboxId)
+ .setNow(HLC.INST.getPhysical())
+ .build());
+ return true;
+ } catch (Throwable e) {
+ return false;
+ }
+ });
+
+ Thread.sleep(3500);
+
+ requestAttach(BatchAttachRequest.Params.newBuilder()
+ .setInboxId(inboxId)
+ .setIncarnation(System.nanoTime())
+ .setExpirySeconds(3)
+ .setClient(client)
+ .setNow(HLC.INST.getPhysical())
+ .build());
+
+ long expectedInc = v1.getIncarnation();
+ long expectedMod = v1.getMod() + 1;
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ verify(inboxClient, atLeastOnce()).delete(argThat(req -> req.getTenantId().equals(tenantId)
+ && req.getInboxId().equals(inboxId)
+ && req.getVersion().getIncarnation() == expectedInc
+ && req.getVersion().getMod() == expectedMod)));
+ }
+}
diff --git a/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxDetachEnsureRecoverIT.java b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxDetachEnsureRecoverIT.java
new file mode 100644
index 000000000..7667e68ae
--- /dev/null
+++ b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxDetachEnsureRecoverIT.java
@@ -0,0 +1,124 @@
+/*
+ * 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.bifromq.inbox.store;
+
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import org.apache.bifromq.basehlc.HLC;
+import org.apache.bifromq.inbox.rpc.proto.DeleteReply;
+import org.apache.bifromq.inbox.storage.proto.BatchAttachRequest;
+import org.apache.bifromq.inbox.storage.proto.BatchDetachReply;
+import org.apache.bifromq.inbox.storage.proto.BatchDetachRequest;
+import org.apache.bifromq.inbox.storage.proto.BatchExistRequest;
+import org.apache.bifromq.inbox.storage.proto.InboxVersion;
+import org.apache.bifromq.sessiondict.client.type.OnlineCheckResult;
+import org.apache.bifromq.type.ClientInfo;
+import org.testng.annotations.Test;
+
+public class InboxDetachEnsureRecoverIT extends InboxStoreTest {
+
+ @Test(groups = "integration")
+ public void ensureSchedulesImmediateExpireForHistoricalAfterRestart() throws Exception {
+ long now = HLC.INST.getPhysical();
+ String tenantId = "tenant-" + System.nanoTime();
+ String inboxId = "inbox-" + System.nanoTime();
+ ClientInfo client = ClientInfo.newBuilder().setTenantId(tenantId).build();
+
+ when(sessionDictClient.exist(org.mockito.ArgumentMatchers.any()))
+ .thenReturn(CompletableFuture.completedFuture(OnlineCheckResult.NOT_EXISTS));
+ when(inboxClient.delete(org.mockito.ArgumentMatchers.any()))
+ .thenReturn(CompletableFuture.completedFuture(DeleteReply.newBuilder()
+ .setReqId(System.nanoTime())
+ .setCode(DeleteReply.Code.OK)
+ .build()));
+
+ // Create first incarnation and detach with short expiry
+ long inc1 = System.nanoTime();
+ InboxVersion v1 = requestAttach(BatchAttachRequest.Params.newBuilder()
+ .setInboxId(inboxId)
+ .setIncarnation(inc1)
+ .setExpirySeconds(3)
+ .setClient(client)
+ .setNow(now)
+ .build())
+ .get(0);
+ assertEquals(requestDetach(BatchDetachRequest.Params.newBuilder()
+ .setTenantId(tenantId)
+ .setInboxId(inboxId)
+ .setExpirySeconds(3)
+ .setVersion(v1)
+ .setNow(now)
+ .build())
+ .get(0), BatchDetachReply.Code.OK);
+
+ // Restart to lose scheduled tasks
+ restartStoreServer();
+ await().forever().until(() -> {
+ try {
+ requestExist(BatchExistRequest.Params.newBuilder()
+ .setTenantId(tenantId)
+ .setInboxId(inboxId)
+ .setNow(HLC.INST.getPhysical())
+ .build());
+ return true;
+ } catch (Throwable e) {
+ return false;
+ }
+ });
+
+ Thread.sleep(3500);
+
+ // Attach a new incarnation and then detach it to trigger toBeEnsured for historical inc1
+ long inc2 = System.nanoTime();
+ InboxVersion v2 = requestAttach(BatchAttachRequest.Params.newBuilder()
+ .setInboxId(inboxId)
+ .setIncarnation(inc2)
+ .setExpirySeconds(10)
+ .setClient(client)
+ .setNow(HLC.INST.getPhysical())
+ .build())
+ .get(0);
+
+ assertEquals(requestDetach(BatchDetachRequest.Params.newBuilder()
+ .setTenantId(tenantId)
+ .setInboxId(inboxId)
+ .setExpirySeconds(10)
+ .setVersion(v2)
+ .setNow(HLC.INST.getPhysical())
+ .build())
+ .get(0), BatchDetachReply.Code.OK);
+
+ long expectedInc = v1.getIncarnation();
+ long expectedMod = v1.getMod() + 1;
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ verify(inboxClient, atLeastOnce()).delete(argThat(req -> req.getTenantId().equals(tenantId)
+ && req.getInboxId().equals(inboxId)
+ && req.getVersion().getIncarnation() == expectedInc
+ && req.getVersion().getMod() == expectedMod)));
+ }
+}
+
diff --git a/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreCleanerTest.java b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreCleanerTest.java
new file mode 100644
index 000000000..86189c6e4
--- /dev/null
+++ b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreCleanerTest.java
@@ -0,0 +1,565 @@
+/*
+ * 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.bifromq.inbox.store;
+
+import static org.apache.bifromq.basekv.utils.BoundaryUtil.FULL_BOUNDARY;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.doAnswer;
+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 static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+
+import com.google.protobuf.ByteString;
+import io.micrometer.core.instrument.Metrics;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.HashMap;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.bifromq.basekv.client.IBaseKVStoreClient;
+import org.apache.bifromq.basekv.client.KVRangeSetting;
+import org.apache.bifromq.basekv.proto.Boundary;
+import org.apache.bifromq.basekv.proto.KVRangeDescriptor;
+import org.apache.bifromq.basekv.store.proto.KVRangeROReply;
+import org.apache.bifromq.basekv.store.proto.KVRangeRORequest;
+import org.apache.bifromq.basekv.store.proto.ROCoProcOutput;
+import org.apache.bifromq.basekv.store.proto.ReplyCode;
+import org.apache.bifromq.basekv.utils.BoundaryUtil;
+import org.apache.bifromq.basekv.utils.KVRangeIdUtil;
+import org.apache.bifromq.inbox.storage.proto.GCReply;
+import org.apache.bifromq.inbox.storage.proto.InboxServiceROCoProcOutput;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class InboxStoreCleanerTest {
+ @Mock
+ private IBaseKVStoreClient inboxStoreClient;
+ @Mock
+ private ScheduledExecutorService jobScheduler;
+ private InboxStoreCleaner cleaner;
+ private AutoCloseable openMocks;
+ private ManualClock manualClock;
+ private SimpleMeterRegistry meterRegistry;
+
+ @BeforeMethod
+ public void setup() {
+ openMocks = MockitoAnnotations.openMocks(this);
+ manualClock = new ManualClock(Instant.EPOCH);
+ cleaner = new InboxStoreCleaner(inboxStoreClient, Duration.ofMillis(100), Duration.ofHours(24), jobScheduler,
+ manualClock);
+ doAnswer(invocation -> {
+ Runnable task = invocation.getArgument(0);
+ task.run();
+ return null;
+ }).when(jobScheduler).execute(any(Runnable.class));
+ meterRegistry = new SimpleMeterRegistry();
+ Metrics.globalRegistry.add(meterRegistry);
+ }
+
+ @AfterMethod
+ public void tearDown() throws Exception {
+ // cleanup metrics registry
+ Metrics.globalRegistry.getMeters().forEach(Metrics.globalRegistry::remove);
+ Metrics.globalRegistry.remove(meterRegistry);
+ openMocks.close();
+ }
+
+ @Test
+ public void testStartSchedulesRecurringTask() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenReturn(mockFuture);
+
+ cleaner.start("store1");
+
+ verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
+ }
+
+ @Test
+ public void testGCOperationExecuted() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(inv -> mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder().setGc(GCReply.getDefaultInstance())
+ .build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler, times(1)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getValue().run();
+
+ verify(inboxStoreClient).query(eq("store1"), any(KVRangeRORequest.class));
+ verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
+ }
+
+ @Test
+ public void testStopPreventsFurtherExecution() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenReturn(mockFuture);
+
+ cleaner.start("store1");
+ cleaner.stop().join();
+
+ verify(mockFuture).cancel(true);
+ verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
+ }
+
+ @Test
+ public void testNoGcForNonLeaderRanges() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenReturn(mockFuture);
+
+ KVRangeSetting nonLeaderRange = new KVRangeSetting("inbox.store", "store2", new HashMap<>() {
+ {
+ put("store2", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, nonLeaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler, times(1)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getValue().run();
+
+ verify(inboxStoreClient, never()).query(any(), any());
+ }
+
+ @Test
+ public void testLowHitGrowthThenShrink() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(inv -> mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ AtomicInteger callCount = new AtomicInteger();
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenAnswer(inv -> {
+ int c = callCount.incrementAndGet();
+ GCReply reply;
+ if (c <= 3) {
+ reply = GCReply.newBuilder().setInspectedCount(512).setRemoveSuccess(0).setWrapped(true).build();
+ } else if (c == 4) {
+ reply = GCReply.newBuilder().setInspectedCount(512).setRemoveSuccess(512).setWrapped(false)
+ .build();
+ } else {
+ reply = GCReply.newBuilder().setInspectedCount(1).setRemoveSuccess(0).setWrapped(false).build();
+ }
+ return CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder().setGc(reply).build())
+ .build())
+ .build());
+ });
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler, times(1)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getValue().run();
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(2)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getAllValues().get(1).run();
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(3)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getAllValues().get(2).run();
+ manualClock.advance(Duration.ofHours(1));
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(3)).query(eq("store1"), any(KVRangeRORequest.class));
+
+ verify(jobScheduler, times(4)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getAllValues().get(3).run();
+ manualClock.advance(Duration.ofHours(1));
+ verify(inboxStoreClient, times(4)).query(eq("store1"), reqCaptor.capture());
+ List<KVRangeRORequest> reqs = reqCaptor.getAllValues();
+ ArgumentCaptor<KVRangeRORequest> lastReqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(4)).query(eq("store1"), lastReqCaptor.capture());
+
+ verify(jobScheduler, times(5)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getAllValues().get(4).run();
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor5 = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(5)).query(eq("store1"), reqCaptor5.capture());
+ }
+
+ @Test
+ public void testNextStartKeyPropagation() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ when(jobScheduler.schedule(any(Runnable.class), anyLong(), any())).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ AtomicInteger count = new AtomicInteger();
+ ByteString nextKey = ByteString.copyFromUtf8("next");
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenAnswer(inv -> {
+ int c = count.incrementAndGet();
+ GCReply reply;
+ if (c == 1) {
+ reply = GCReply.newBuilder().setInspectedCount(1).setRemoveSuccess(0).setWrapped(false)
+ .setNextStartKey(nextKey).build();
+ } else {
+ reply = GCReply.getDefaultInstance();
+ }
+ return CompletableFuture.completedFuture(KVRangeROReply.newBuilder().setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder().setGc(reply).build()).build())
+ .build());
+ });
+
+ cleaner.start("store1");
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(jobScheduler, times(1)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getValue().run();
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(2)).schedule(taskCaptor.capture(), anyLong(), any());
+ taskCaptor.getAllValues().get(1).run();
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(2)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest secondReq = reqCaptor.getAllValues().get(1);
+ ByteString startKey = secondReq.getRoCoProc().getInboxService().getGc().getStartKey();
+ assertEquals(nextKey, startKey);
+ }
+
+ @Test
+ public void testRangeGaugesRegisteredAndRemovedOnLeadershipChange() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ when(jobScheduler.schedule(taskCaptor.capture(), anyLong(), any())).thenReturn(mockFuture);
+
+ var rangeId = KVRangeIdUtil.generate();
+ String rangeIdStr = KVRangeIdUtil.toString(rangeId);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(rangeId).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router1 = new TreeMap<>(BoundaryUtil::compare);
+ router1.put(FULL_BOUNDARY, leaderRange);
+
+ KVRangeSetting otherLeaderRange = new KVRangeSetting("inbox.store", "store2", new HashMap<>() {
+ {
+ put("store2", KVRangeDescriptor.newBuilder().setId(rangeId).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router2 = new TreeMap<>(BoundaryUtil::compare);
+ router2.put(FULL_BOUNDARY, otherLeaderRange);
+
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router1, router2);
+
+ // reply ok to avoid exceptions
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder()
+ .setGc(GCReply.getDefaultInstance()).build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+
+ assertEquals(taskCaptor.getAllValues().size(), 1);
+ taskCaptor.getAllValues().get(0).run();
+
+ assertNotNull(meterRegistry.find("inbox.gc.interval.ms")
+ .tag("storeId", "store1")
+ .tag("rangeId", rangeIdStr)
+ .gauge());
+ assertNotNull(meterRegistry.find("inbox.gc.step")
+ .tag("storeId", "store1")
+ .tag("rangeId", rangeIdStr)
+ .gauge());
+
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(1).run();
+
+ assertNull(meterRegistry.find("inbox.gc.interval.ms")
+ .tag("storeId", "store1")
+ .tag("rangeId", rangeIdStr)
+ .gauge());
+ assertNull(meterRegistry.find("inbox.gc.step")
+ .tag("storeId", "store1")
+ .tag("rangeId", rangeIdStr)
+ .gauge());
+ }
+
+ @Test
+ public void testGaugesReflectIntervalAndStepChanges() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ when(jobScheduler.schedule(taskCaptor.capture(), anyLong(), any())).thenReturn(mockFuture);
+
+ var rangeId = KVRangeIdUtil.generate();
+ String rangeIdStr = KVRangeIdUtil.toString(rangeId);
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(rangeId).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ AtomicInteger callCount = new AtomicInteger();
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenAnswer(inv -> {
+ int c = callCount.incrementAndGet();
+ GCReply reply;
+ if (c == 1) {
+ reply = GCReply.newBuilder().setInspectedCount(100).setRemoveSuccess(0).setWrapped(true).build();
+ } else if (c == 2) {
+ reply = GCReply.newBuilder().setInspectedCount(512).setRemoveSuccess(0).setWrapped(false).build();
+ } else if (c == 3) {
+ reply = GCReply.newBuilder().setInspectedCount(512).setRemoveSuccess(0).setWrapped(true).build();
+ } else {
+ reply = GCReply.newBuilder().setInspectedCount(512).setRemoveSuccess(0).setWrapped(false).build();
+ }
+ return CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder().setGc(reply).build())
+ .build())
+ .build());
+ });
+
+ cleaner.start("store1");
+
+ taskCaptor.getAllValues().get(0).run();
+
+ assertNotNull(meterRegistry.find("inbox.gc.interval.ms").tag("storeId", "store1").tag("rangeId", rangeIdStr)
+ .gauge());
+ assertEquals(meterRegistry.find("inbox.gc.interval.ms")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr)
+ .gauge().value(),
+ 100.0, 0.01);
+ assertEquals(meterRegistry.find("inbox.gc.step").tag("storeId", "store1").tag("rangeId", rangeIdStr)
+ .gauge().value(), 1.0, 0.01);
+
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(1).run();
+
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(3)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(2).run();
+
+ manualClock.advance(Duration.ofHours(1));
+ verify(jobScheduler, times(4)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(3).run();
+
+ assertEquals(meterRegistry.find("inbox.gc.step")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr)
+ .gauge().value(),
+ 2.0, 0.01);
+ assertEquals(meterRegistry.find("inbox.gc.interval.ms")
+ .tag("storeId", "store1").tag("rangeId", rangeIdStr)
+ .gauge().value(),
+ 150.0, 0.01);
+ }
+
+ @Test
+ public void testFirstSweepSprintQuotaAndIntervalThenSwitchOnWrapped() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ when(jobScheduler.schedule(taskCaptor.capture(), anyLong(), any())).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ AtomicInteger callCount = new AtomicInteger();
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenAnswer(inv -> {
+ int c = callCount.incrementAndGet();
+ GCReply reply;
+ if (c == 1) {
+ reply = GCReply.newBuilder().setInspectedCount(100).setRemoveSuccess(0).setWrapped(false).build();
+ } else if (c == 2) {
+ reply = GCReply.newBuilder().setInspectedCount(100).setRemoveSuccess(0).setWrapped(true).build();
+ } else {
+ reply = GCReply.newBuilder().setInspectedCount(1).setRemoveSuccess(0).setWrapped(false).build();
+ }
+ return CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder().setGc(reply).build())
+ .build())
+ .build());
+ });
+
+ cleaner.start("store1");
+ verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(0).run();
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(1)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest firstReq = reqCaptor.getValue();
+ assertEquals(firstReq.getRoCoProc().getInboxService().getGc().getScanQuota(), 50_000);
+
+ verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
+ manualClock.advance(Duration.ofSeconds(5));
+ taskCaptor.getAllValues().get(1).run();
+
+ verify(inboxStoreClient, times(2)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest secondReq = reqCaptor.getAllValues().get(1);
+ assertEquals(secondReq.getRoCoProc().getInboxService().getGc().getScanQuota(), 50_000);
+
+ final int[] runIdx = {2};
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
+ if (taskCaptor.getAllValues().size() > runIdx[0]) {
+ manualClock.advance(Duration.ofMillis(100));
+ taskCaptor.getAllValues().get(runIdx[0]).run();
+ runIdx[0]++;
+ }
+ verify(inboxStoreClient, atLeast(3)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest lastReq = reqCaptor.getAllValues().get(reqCaptor.getAllValues().size() - 1);
+ assertEquals(lastReq.getRoCoProc().getInboxService().getGc().getScanQuota(), 512);
+ });
+ }
+
+ @Test
+ public void testSprintSurvivesFailureAndKeepsLargeQuota() {
+ ScheduledFuture mockFuture = mock(ScheduledFuture.class);
+ ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
+ when(jobScheduler.schedule(taskCaptor.capture(), anyLong(), any())).thenReturn(mockFuture);
+
+ KVRangeSetting leaderRange = new KVRangeSetting("inbox.store", "store1", new HashMap<>() {
+ {
+ put("store1", KVRangeDescriptor.newBuilder().setId(KVRangeIdUtil.generate()).setVer(1).build());
+ }
+ });
+ NavigableMap<Boundary, KVRangeSetting> router = new TreeMap<>(BoundaryUtil::compare);
+ router.put(FULL_BOUNDARY, leaderRange);
+ when(inboxStoreClient.latestEffectiveRouter()).thenReturn(router);
+
+ when(inboxStoreClient.query(eq("store1"), any(KVRangeRORequest.class)))
+ .thenReturn(CompletableFuture.failedFuture(new RuntimeException("io error")))
+ .thenReturn(CompletableFuture.completedFuture(KVRangeROReply.newBuilder()
+ .setCode(ReplyCode.Ok)
+ .setRoCoProcResult(ROCoProcOutput.newBuilder()
+ .setInboxService(InboxServiceROCoProcOutput.newBuilder()
+ .setGc(GCReply.newBuilder().setInspectedCount(1).setRemoveSuccess(0).setWrapped(false).build())
+ .build())
+ .build())
+ .build()));
+
+ cleaner.start("store1");
+ verify(jobScheduler, times(1)).schedule(any(Runnable.class), anyLong(), any());
+ taskCaptor.getAllValues().get(0).run();
+
+ verify(jobScheduler, times(2)).schedule(any(Runnable.class), anyLong(), any());
+ manualClock.advance(Duration.ofSeconds(5));
+ taskCaptor.getAllValues().get(1).run();
+
+ ArgumentCaptor<KVRangeRORequest> reqCaptor = ArgumentCaptor.forClass(KVRangeRORequest.class);
+ verify(inboxStoreClient, times(2)).query(eq("store1"), reqCaptor.capture());
+ KVRangeRORequest secondReq = reqCaptor.getAllValues().get(1);
+ assertEquals(secondReq.getRoCoProc().getInboxService().getGc().getScanQuota(), 50_000);
+ }
+
+ static class ManualClock extends Clock {
+ private final ZoneId zone = ZoneOffset.UTC;
+ private Instant now;
+
+ ManualClock(Instant start) {
+ this.now = start;
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return zone;
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return now;
+ }
+
+ void advance(Duration d) {
+ now = now.plus(d);
+ }
+ }
+}
diff --git a/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreTest.java b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreTest.java
index a2dc717ce..7dea34a70 100644
--- a/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreTest.java
+++ b/bifromq-inbox/bifromq-inbox-store/src/test/java/org/apache/bifromq/inbox/store/InboxStoreTest.java
@@ -238,7 +238,8 @@ abstract class InboxStoreTest {
.tickerThreads(tickerThreads)
.bgTaskExecutor(bgTaskExecutor)
.detachTimeout(Duration.ofSeconds(1))
- .gcInterval(Duration.ofSeconds(1))
+ .minGCInterval(Duration.ofSeconds(1))
+ .maxGCInterval(Duration.ofSeconds(2))
.bootstrapDelay(Duration.ofSeconds(1))
.build();
rpcServer = rpcServerBuilder.build();
diff --git a/bifromq-metrics/src/main/java/org/apache/bifromq/metrics/TenantMetric.java b/bifromq-metrics/src/main/java/org/apache/bifromq/metrics/TenantMetric.java
index 2c6f7d7ee..cd4d88fed 100644
--- a/bifromq-metrics/src/main/java/org/apache/bifromq/metrics/TenantMetric.java
+++ b/bifromq-metrics/src/main/java/org/apache/bifromq/metrics/TenantMetric.java
@@ -61,6 +61,7 @@ public enum TenantMetric {
MqttConfirmingMessages("mqtt.ex.confirming", Meter.Type.DISTRIBUTION_SUMMARY),
MqttResendBytes("mqtt.ex.resend.bytes", Meter.Type.DISTRIBUTION_SUMMARY),
MqttDeDupBytes("mqtt.ex.dedup.bytes", Meter.Type.DISTRIBUTION_SUMMARY),
+ MqttStalledCount("mqtt.ex.stalled.count", Meter.Type.COUNTER),
// subscription related metrics
MqttRouteSpaceGauge("mqtt.route.space.gauge", Meter.Type.GAUGE),
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/DedupCache.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/DedupCache.java
new file mode 100644
index 000000000..74c5017a7
--- /dev/null
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/DedupCache.java
@@ -0,0 +1,159 @@
+/*
+ * 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.bifromq.mqtt.handler;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Interner;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.LongAdder;
+
+/**
+ * Per-channel and per-topic timestamp deduplication cache.
+ */
+public class DedupCache {
+ private static final Interner<String> TOPIC_INTERNER = Interner.newWeakInterner();
+ private final Cache<String, ChannelTopicCache> channelTopicCaches;
+ private final long expireAfterAccessMillis;
+ private final long maxTopicsPerChannel;
+ private final LongAdder totalTopics = new LongAdder();
+ private final LongAdder channelSizeEvicted = new LongAdder();
+ private final LongAdder topicSizeEvicted = new LongAdder();
+ private final LongAdder channelExpiredEvicted = new LongAdder();
+ private final LongAdder topicExpiredEvicted = new LongAdder();
+
+ /**
+ * Create a dedup cache with bounded capacity.
+ *
+ * @param expireAfterAccessMillis expire millis after access
+ * @param maxChannels max cached channels
+ * @param maxTopicsPerChannel max cached topics per channel
+ */
+ public DedupCache(long expireAfterAccessMillis, long maxChannels, long maxTopicsPerChannel) {
+ this.expireAfterAccessMillis = expireAfterAccessMillis;
+ this.maxTopicsPerChannel = maxTopicsPerChannel;
+ this.channelTopicCaches = Caffeine.newBuilder()
+ .expireAfterAccess(expireAfterAccessMillis, TimeUnit.MILLISECONDS)
+ .maximumSize(maxChannels)
+ .removalListener((String key, ChannelTopicCache channelTopicCache, RemovalCause cause) -> {
+ long remaining = channelTopicCache.count.sum();
+ if (remaining > 0) {
+ totalTopics.add(-remaining);
+ }
+ if (cause == RemovalCause.SIZE) {
+ channelSizeEvicted.increment();
+ } else if (cause == RemovalCause.EXPIRED) {
+ channelExpiredEvicted.increment();
+ }
+ })
+ .build();
+ }
+
+ /**
+ * Check if duplicate under the given publisher channel and topic, update last timestamp if not duplicate.
+ * Return true if duplicate, otherwise false.
+ *
+ * @param channelId the channel id of publisher client
+ * @param topic the topic
+ * @param timestamp the inbound timestamp of message
+ */
+ public boolean isDuplicate(String channelId, String topic, long timestamp) {
+ String normalizedTopic = TOPIC_INTERNER.intern(topic);
+ ChannelTopicCache perChannel = channelTopicCaches.get(channelId, k -> new ChannelTopicCache());
+ AtomicReference<Long> lastRef = perChannel.cache.get(normalizedTopic, k -> {
+ perChannel.count.increment();
+ totalTopics.increment();
+ return new AtomicReference<>(0L);
+ });
+ Long last = lastRef.get();
+ if (last >= timestamp) {
+ return true;
+ }
+ lastRef.set(timestamp);
+ return false;
+ }
+
+ /**
+ * Estimated number of cached channels.
+ */
+ public long estimatedChannels() {
+ return channelTopicCaches.estimatedSize();
+ }
+
+ /**
+ * Total cached topic entries across all channels.
+ */
+ public long totalCachedTopics() {
+ return totalTopics.sum();
+ }
+
+ /**
+ * Evicted channels due to over max channels.
+ */
+ public long channelEvictedBySize() {
+ return channelSizeEvicted.sum();
+ }
+
+ /**
+ * Evicted topics due to over max topics per channels.
+ */
+ public long topicEvictedBySize() {
+ return topicSizeEvicted.sum();
+ }
+
+ /**
+ * Evicted channels due to expiry.
+ */
+ public long channelEvictedByExpired() {
+ return channelExpiredEvicted.sum();
+ }
+
+ /**
+ * Evicted topics due to expiry.
+ */
+ public long topicEvictedByExpired() {
+ return topicExpiredEvicted.sum();
+ }
+
+ private final class ChannelTopicCache {
+ final Cache<String, AtomicReference<Long>> cache;
+ final LongAdder count = new LongAdder();
+
+ ChannelTopicCache() {
+ this.cache = Caffeine.newBuilder()
+ .expireAfterAccess(expireAfterAccessMillis, TimeUnit.MILLISECONDS)
+ .maximumSize(maxTopicsPerChannel)
+ .removalListener((String key, AtomicReference<Long> value, RemovalCause cause) -> {
+ Objects.requireNonNull(cause);
+ count.decrement();
+ totalTopics.decrement();
+ if (cause == RemovalCause.SIZE) {
+ topicSizeEvicted.increment();
+ } else if (cause == RemovalCause.EXPIRED) {
+ topicExpiredEvicted.increment();
+ }
+ })
+ .build();
+ }
+ }
+}
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTPersistentSessionHandler.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTPersistentSessionHandler.java
index a5d0e3b61..01e715828 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTPersistentSessionHandler.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTPersistentSessionHandler.java
@@ -39,8 +39,6 @@ import static org.apache.bifromq.plugin.resourcethrottler.TenantResourceType.Tot
import static org.apache.bifromq.plugin.resourcethrottler.TenantResourceType.TotalPersistentUnsubscribePerSecond;
import static org.apache.bifromq.type.QoS.AT_LEAST_ONCE;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
import io.micrometer.core.instrument.Timer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
@@ -53,7 +51,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.bifromq.base.util.AsyncRetry;
import org.apache.bifromq.basehlc.HLC;
@@ -76,6 +73,8 @@ import org.apache.bifromq.plugin.eventcollector.mqttbroker.clientdisconnect.ByCl
import org.apache.bifromq.retain.rpc.proto.MatchReply;
import org.apache.bifromq.retain.rpc.proto.MatchRequest;
import org.apache.bifromq.sysprops.props.DataPlaneMaxBurstLatencyMillis;
+import org.apache.bifromq.sysprops.props.MaxActiveDedupChannels;
+import org.apache.bifromq.sysprops.props.MaxActiveDedupTopicsPerChannel;
import org.apache.bifromq.type.ClientInfo;
import org.apache.bifromq.type.MatchInfo;
import org.apache.bifromq.type.Message;
@@ -92,12 +91,16 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
private final InboxVersion inboxVersion;
private final NavigableMap<Long, StagingMessage> stagingBuffer = new TreeMap<>();
private final IInboxClient inboxClient;
- private final Cache<String, AtomicReference<Long>> qoS0TimestampsByMQTTPublisher = Caffeine.newBuilder()
- .expireAfterAccess(2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(), TimeUnit.MILLISECONDS)
- .build();
- private final Cache<String, AtomicReference<Long>> qoS12TimestampsByMQTTPublisher = Caffeine.newBuilder()
- .expireAfterAccess(2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(), TimeUnit.MILLISECONDS)
- .build();
+ private final DedupCache qoS0DedupCache = new DedupCache(
+ 2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(),
+ MaxActiveDedupChannels.INSTANCE.get(),
+ MaxActiveDedupTopicsPerChannel.INSTANCE.get()
+ );
+ private final DedupCache qoS12DedupCache = new DedupCache(
+ 2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(),
+ MaxActiveDedupChannels.INSTANCE.get(),
+ MaxActiveDedupTopicsPerChannel.INSTANCE.get()
+ );
private boolean qos0Confirming = false;
private boolean inboxConfirming = false;
private long nextSendSeq = 0;
@@ -107,7 +110,6 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
private State state = State.INIT;
private ScheduledFuture<?> confirmTimeout;
private ScheduledFuture<?> hintTimeout;
- private int currentHint = 1;
protected MQTTPersistentSessionHandler(TenantSettings settings,
ITenantMeter tenantMeter,
@@ -151,9 +153,7 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
@Override
public void doTearDown(ChannelHandlerContext ctx) {
- if (hintTimeout != null && !hintTimeout.isCancelled()) {
- hintTimeout.cancel(false);
- }
+ cancelScheduledHint();
if (inboxReader != null) {
inboxReader.close();
}
@@ -385,21 +385,27 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
inboxReader = inboxClient.openInboxReader(clientInfo().getTenantId(), userSessionId,
inboxVersion.getIncarnation());
inboxReader.fetch(this::consume);
- currentHint = clientReceiveQuota();
- scheduleHintTimeout();
- inboxReader.hint(currentHint);
+ inboxReader.hint(clientReceiveQuota());
// resume channel read after inbox being setup
onInitialized();
resumeChannelRead();
}
private void scheduleHintTimeout() {
+ cancelScheduledHint();
hintTimeout = ctx.executor().schedule(() -> {
- inboxReader.hint(currentHint);
- scheduleHintTimeout();
+ inboxReader.hint(clientReceiveQuota());
+ hintTimeout = null;
}, ThreadLocalRandom.current().nextLong(15, 45), TimeUnit.SECONDS);
}
+ private void cancelScheduledHint() {
+ if (hintTimeout != null && !hintTimeout.isDone()) {
+ hintTimeout.cancel(true);
+ hintTimeout = null;
+ }
+ }
+
private void scheduleConfirmTimeout(long upToSeq) {
confirmTimeout = ctx.executor().schedule(() -> {
if (upToSeq < inboxConfirmedUpToSeq) {
@@ -462,8 +468,7 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
}
}
confirmedMsgs.clear();
- currentHint = clientReceiveQuota();
- inboxReader.hint(currentHint);
+ inboxReader.hint(clientReceiveQuota());
ctx.executor().execute(this::drainStaging);
}
@@ -491,8 +496,7 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
if (upToSeq < inboxConfirmedUpToSeq) {
confirmSendBuffer();
} else {
- currentHint = clientReceiveQuota();
- inboxReader.hint(currentHint);
+ inboxReader.hint(clientReceiveQuota());
}
}
case NO_INBOX, CONFLICT ->
@@ -509,9 +513,7 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
if (upToSeq < inboxConfirmedUpToSeq) {
confirmSendBuffer();
} else {
- currentHint = clientReceiveQuota();
- inboxReader.hint(currentHint);
- scheduleHintTimeout();
+ inboxReader.hint(clientReceiveQuota());
}
}
default -> {
@@ -523,11 +525,9 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
private void consume(Fetched fetched) {
ctx.executor().execute(() -> {
- if (hintTimeout != null && !hintTimeout.isCancelled()) {
- hintTimeout.cancel(false);
- }
switch (fetched.getResult()) {
case OK -> {
+ cancelScheduledHint();
// deal with qos0
if (fetched.getQos0MsgCount() > 0) {
fetched.getQos0MsgList().forEach(this::pubQoS0Message);
@@ -544,15 +544,8 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
}
}
}
- case BACK_PRESSURE_REJECTED -> {
- currentHint = clientReceiveQuota();
- scheduleHintTimeout();
- }
- case TRY_LATER -> {
- currentHint = clientReceiveQuota();
- scheduleHintTimeout();
- inboxReader.hint(currentHint);
- }
+ case BACK_PRESSURE_REJECTED -> scheduleHintTimeout();
+ case TRY_LATER -> inboxReader.hint(clientReceiveQuota());
case NO_INBOX, ERROR ->
handleProtocolResponse(helper().onInboxTransientError(fetched.getResult().name()));
default -> {
@@ -563,8 +556,8 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
}
private void pubQoS0Message(InboxMessage inboxMsg) {
- boolean isDup = isDuplicateMessage(inboxMsg.getMsg().getPublisher(), inboxMsg.getMsg().getMessage(),
- qoS0TimestampsByMQTTPublisher);
+ boolean isDup = isDuplicateMessage(inboxMsg.getMsg().getTopic(),
+ inboxMsg.getMsg().getPublisher(), inboxMsg.getMsg().getMessage(), qoS0DedupCache);
inboxMsg.getMatchedTopicFilterMap()
.forEach((topicFilter, option) -> pubQoS0Message(topicFilter, option, inboxMsg.getMsg(), isDup));
}
@@ -584,8 +577,8 @@ public abstract class MQTTPersistentSessionHandler extends MQTTSessionHandler im
}
private void pubBufferedMessage(InboxMessage inboxMsg, boolean batchEnd) {
- boolean isDup = isDuplicateMessage(inboxMsg.getMsg().getPublisher(), inboxMsg.getMsg().getMessage(),
- qoS12TimestampsByMQTTPublisher);
+ boolean isDup = isDuplicateMessage(inboxMsg.getMsg().getTopic(),
+ inboxMsg.getMsg().getPublisher(), inboxMsg.getMsg().getMessage(), qoS12DedupCache);
int i = 0;
for (Map.Entry<String, TopicFilterOption> entry : inboxMsg.getMatchedTopicFilterMap().entrySet()) {
String topicFilter = entry.getKey();
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTSessionHandler.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTSessionHandler.java
index 8f150b437..02f3ece33 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTSessionHandler.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTSessionHandler.java
@@ -37,6 +37,7 @@ import static org.apache.bifromq.metrics.TenantMetric.MqttQoS2ExternalLatency;
import static org.apache.bifromq.metrics.TenantMetric.MqttQoS2IngressBytes;
import static org.apache.bifromq.metrics.TenantMetric.MqttResendBytes;
import static org.apache.bifromq.metrics.TenantMetric.MqttSendingQuota;
+import static org.apache.bifromq.metrics.TenantMetric.MqttStalledCount;
import static org.apache.bifromq.mqtt.handler.IMQTTProtocolHelper.SubResult.EXCEED_LIMIT;
import static org.apache.bifromq.mqtt.handler.MQTTSessionIdUtil.userSessionId;
import static org.apache.bifromq.mqtt.handler.v5.MQTT5MessageUtils.messageExpiryInterval;
@@ -63,7 +64,6 @@ import static org.apache.bifromq.util.TopicUtil.isSharedSubscription;
import static org.apache.bifromq.util.TopicUtil.isValidTopicFilter;
import static org.apache.bifromq.util.TopicUtil.isWildcardTopicFilter;
-import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.collect.Sets;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
@@ -88,7 +88,6 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.bifromq.base.util.FutureTracker;
@@ -112,6 +111,7 @@ import org.apache.bifromq.plugin.eventcollector.Event;
import org.apache.bifromq.plugin.eventcollector.IEventCollector;
import org.apache.bifromq.plugin.eventcollector.OutOfTenantResource;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.PingReq;
+import org.apache.bifromq.plugin.eventcollector.mqttbroker.SubStalled;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.accessctrl.PubActionDisallow;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.accessctrl.SubActionDisallow;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.accessctrl.UnsubActionDisallow;
@@ -199,6 +199,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
private long lastActiveAtNanos;
private ScheduledFuture<?> resendTask;
private int receivingCount = 0;
+ private ScheduledFuture<?> stallCheckTask;
protected MQTTSessionHandler(TenantSettings settings,
ITenantMeter tenantMeter,
@@ -404,6 +405,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
if (noDelayLWT != null) {
addBgTask(pubWillMessage(noDelayLWT));
}
+ cancelStallTask();
Sets.newHashSet(fgTasks).forEach(t -> t.cancel(true));
doTearDown(ctx);
sessionCtx.localSessionRegistry.remove(channelId(), this);
@@ -426,6 +428,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
super.exceptionCaught(ctx, cause);
log.debug("ctx: {}, cause:", ctx, cause);
+ cancelStallTask();
// if disconnection is caused purely by channel error
handleProtocolResponse(
ProtocolResponse.goAwayNow(getLocal(ClientChannelError.class).clientInfo(clientInfo).cause(cause)));
@@ -433,7 +436,9 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
+ super.channelWritabilityChanged(ctx);
if (ctx.channel().isWritable()) {
+ cancelStallTask();
if (!unconfirmedPacketIds.isEmpty()) {
// resend immediately when channel becomes writable
resend();
@@ -442,6 +447,11 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
if (resendTask != null) {
resendTask.cancel(false);
}
+ if (!unconfirmedPacketIds.isEmpty() && stallCheckTask == null) {
+ final io.netty.channel.Channel ch = ctx.channel();
+ stallCheckTask = ctx.executor().schedule(() -> fireStallIfStillUnwritable(ch),
+ stallTimeoutSeconds(), TimeUnit.SECONDS);
+ }
}
}
@@ -824,6 +834,30 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
}
}
+ private int stallTimeoutSeconds() {
+ return settings.maxResendTimes * settings.resendTimeoutSeconds;
+ }
+
+ private void cancelStallTask() {
+ if (stallCheckTask != null) {
+ stallCheckTask.cancel(false);
+ stallCheckTask = null;
+ }
+ }
+
+ private void fireStallIfStillUnwritable(io.netty.channel.Channel ch) {
+ if (!ch.isWritable() && !unconfirmedPacketIds.isEmpty()) {
+ eventCollector.report(getLocal(SubStalled.class)
+ .clientInfo(clientInfo)
+ .bytesBeforeWritable(ch.bytesBeforeWritable())
+ .unconfirmedCount(unconfirmedPacketIds.size())
+ .writeBufferLowWaterMark(ch.config().getWriteBufferLowWaterMark())
+ .writeBufferHighWaterMark(ch.config().getWriteBufferHighWaterMark()));
+ tenantMeter.recordCount(MqttStalledCount);
+ }
+ stallCheckTask = null;
+ }
+
protected int clientReceiveMaximum() {
return helper().clientReceiveMaximum();
}
@@ -853,6 +887,9 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
} else {
log.trace("No msg to confirm: sessionId={}, packetId={}", userSessionId, packetId);
}
+ if (unconfirmedPacketIds.isEmpty()) {
+ cancelStallTask();
+ }
return msg;
}
@@ -977,7 +1014,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
}
return;
}
- if (messageExpiryInterval(pubMsg.variableHeader().properties()).orElse(Integer.MAX_VALUE) < 0) {
+ if (messageExpiryInterval(pubMsg.variableHeader().properties()).orElse(Integer.MAX_VALUE) <= 0) {
// If the Message Expiry Interval has passed and the Server has not managed to start onward delivery
// to a matching subscriber, then it MUST delete the copy of the message for that subscriber [MQTT-3.3.2-5]
if (settings.debugMode) {
@@ -1118,7 +1155,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
ctx.executor().execute(() -> confirm(packetId, false));
return;
}
- if (messageExpiryInterval(pubMsg.variableHeader().properties()).orElse(Integer.MAX_VALUE) < 0) {
+ if (messageExpiryInterval(pubMsg.variableHeader().properties()).orElse(Integer.MAX_VALUE) <= 0) {
// If the Message Expiry Interval has passed and the Server has not managed to start onward delivery
// to a matching subscriber, then it MUST delete the copy of the message for that subscriber [MQTT-3.3.2-5]
if (settings.debugMode) {
@@ -1181,7 +1218,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
} else {
receiveQuota.onErrorSignal(sessionCtx.nanoTime());
if (settings.debugMode) {
- String detail = f.cause() == null ? "unknown" : f.cause().getMessage();
+ String detail = getPushErrorDetail(f.cause());
switch (msg.qos()) {
case AT_LEAST_ONCE -> eventCollector.report(getLocal(QoS1PushError.class)
.detail(detail)
@@ -1210,6 +1247,16 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
});
}
+ private String getPushErrorDetail(Throwable cause) {
+ if (cause == null) {
+ return "unknown";
+ }
+ if (cause.getMessage() != null) {
+ return cause.getMessage();
+ }
+ return cause.getClass().getSimpleName();
+ }
+
private void reportDropConfirmableMsgEvent(RoutedMessage msg, DropReason reason) {
switch (msg.qos()) {
case AT_LEAST_ONCE -> eventCollector.report(getLocal(QoS1Dropped.class)
@@ -1574,8 +1621,10 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
}
}
- protected final boolean isDuplicateMessage(ClientInfo publisher, Message message,
- Cache<String, AtomicReference<Long>> latestMsgTsByPublisher) {
+ protected final boolean isDuplicateMessage(String topic,
+ ClientInfo publisher,
+ Message message,
+ DedupCache dedupCache) {
if (message.getIsRetained()) {
return false;
}
@@ -1584,12 +1633,7 @@ public abstract class MQTTSessionHandler extends MQTTMessageHandler implements I
// don't deduplicate message published from HTTP API
return false;
}
- AtomicReference<Long> lastPubRef = latestMsgTsByPublisher.get(mqttPublisherKey, k -> new AtomicReference<>(0L));
- if (lastPubRef.get() >= message.getTimestamp()) {
- return true;
- }
- lastPubRef.set(message.getTimestamp());
- return false;
+ return dedupCache.isDuplicate(mqttPublisherKey, topic, message.getTimestamp());
}
private CompletableFuture<Void> doPubLastWill(LWT willMessage) {
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTTransientSessionHandler.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTTransientSessionHandler.java
index 9362f074b..ba5c951ef 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTTransientSessionHandler.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/MQTTTransientSessionHandler.java
@@ -38,8 +38,6 @@ import static org.apache.bifromq.plugin.resourcethrottler.TenantResourceType.Tot
import static org.apache.bifromq.plugin.resourcethrottler.TenantResourceType.TotalTransientSubscriptions;
import static org.apache.bifromq.plugin.resourcethrottler.TenantResourceType.TotalTransientUnsubscribePerSecond;
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.collect.Sets;
import io.micrometer.core.instrument.Timer;
import io.netty.channel.ChannelHandlerContext;
@@ -59,7 +57,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.bifromq.basehlc.HLC;
import org.apache.bifromq.dist.client.MatchResult;
@@ -80,6 +77,8 @@ import org.apache.bifromq.plugin.eventcollector.session.MQTTSessionStop;
import org.apache.bifromq.retain.rpc.proto.MatchReply;
import org.apache.bifromq.retain.rpc.proto.MatchRequest;
import org.apache.bifromq.sysprops.props.DataPlaneMaxBurstLatencyMillis;
+import org.apache.bifromq.sysprops.props.MaxActiveDedupChannels;
+import org.apache.bifromq.sysprops.props.MaxActiveDedupTopicsPerChannel;
import org.apache.bifromq.type.ClientInfo;
import org.apache.bifromq.type.InboxState;
import org.apache.bifromq.type.LastWillInfo;
@@ -95,12 +94,11 @@ public abstract class MQTTTransientSessionHandler extends MQTTSessionHandler imp
// the topicFilters could be accessed concurrently
private final Map<String, TopicFilterOption> topicFilters = new ConcurrentHashMap<>();
private final NavigableMap<Long, RoutedMessage> inbox = new TreeMap<>();
- private final Cache<String, AtomicReference<Long>> latestMsgTsByMQTTPublisher = Caffeine.newBuilder()
- // we simply use 2 times of the burst latency as the expiration time
- // which is a rough estimation of stabilizing time of internal resource scheduling
- // during which the internal retry mechanism takes effect.
- .expireAfterAccess(2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(), TimeUnit.MILLISECONDS)
- .build();
+ private final DedupCache dedupCache = new DedupCache(
+ 2 * DataPlaneMaxBurstLatencyMillis.INSTANCE.get(),
+ MaxActiveDedupChannels.INSTANCE.get(),
+ MaxActiveDedupTopicsPerChannel.INSTANCE.get()
+ );
private long nextSendSeq = 0;
private long msgSeqNo = 0;
private AtomicLong subNumGauge;
@@ -381,7 +379,7 @@ public abstract class MQTTTransientSessionHandler extends MQTTSessionHandler imp
for (TopicFilterAndPermission tfp : topicFilterAndPermissions) {
RoutedMessage subMsg = new RoutedMessage(topic, message, publisher, tfp.topicFilter, tfp.option, now,
tfp.permissionCheckFuture.join().hasGranted(),
- isDuplicateMessage(publisher, message, latestMsgTsByMQTTPublisher));
+ isDuplicateMessage(topic, publisher, message, dedupCache));
logInternalLatency(subMsg);
if (subMsg.qos() == QoS.AT_MOST_ONCE) {
sendQoS0SubMessage(subMsg);
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5MessageBuilders.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5MessageBuilders.java
index 972cf051d..7b591c76c 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5MessageBuilders.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5MessageBuilders.java
@@ -40,7 +40,6 @@ import io.netty.handler.codec.mqtt.MqttSubAckMessage;
import io.netty.handler.codec.mqtt.MqttSubAckPayload;
import io.netty.handler.codec.mqtt.MqttUnsubAckMessage;
import io.netty.handler.codec.mqtt.MqttUnsubAckPayload;
-import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.apache.bifromq.basehlc.HLC;
@@ -418,12 +417,17 @@ public class MQTT5MessageBuilders {
}
extraUserProps.forEach(userProp -> propsBuilder.addUserProperty(userProp.key(), userProp.value()));
if (message.message().getExpiryInterval() < Integer.MAX_VALUE) {
- // If absent, the Application Message does not expire
- int leftDelayInterval = (int) Duration.ofMillis(
- Duration.ofSeconds(message.message().getExpiryInterval()).toMillis()
- - (HLC.INST.getPhysical() - HLC.INST.getPhysical(message.message().getTimestamp())))
- .toSeconds();
- propsBuilder.addMessageExpiryInterval(leftDelayInterval);
+ long nowMs = HLC.INST.getPhysical();
+ long msgMs = HLC.INST.getPhysical(message.message().getTimestamp());
+ long elapsedMs = nowMs - msgMs;
+ long totalMs = message.message().getExpiryInterval() * 1000L;
+ long leftMs = totalMs - elapsedMs;
+ if (leftMs > 0) {
+ int leftSec = (int) Math.max(1L, (long) Math.ceil(leftMs / 1000.0));
+ propsBuilder.addMessageExpiryInterval(leftSec);
+ } else {
+ propsBuilder.addMessageExpiryInterval(0);
+ }
}
MqttFixedHeader mqttFixedHeader =
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5ProtocolHelper.java b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5ProtocolHelper.java
index ee68dad27..830671bf5 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5ProtocolHelper.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/main/java/org/apache/bifromq/mqtt/handler/v5/MQTT5ProtocolHelper.java
@@ -524,10 +524,10 @@ public class MQTT5ProtocolHelper implements IMQTTProtocolHelper {
}
String topic = message.variableHeader().topicName();
MqttProperties mqttProperties = message.variableHeader().properties();
- if (messageExpiryInterval(mqttProperties).orElse(Integer.MAX_VALUE) == 0) {
+ if (messageExpiryInterval(mqttProperties).orElse(Integer.MAX_VALUE) < 0) {
return farewell(MQTT5MessageBuilders.disconnect().reasonCode(MQTT5DisconnectReasonCode.ProtocolError)
- .reasonString("MessageExpiryInterval must be positive integer").build(),
- getLocal(ProtocolViolation.class).statement("MessageExpiryInterval must be positive integer")
+ .reasonString("MessageExpiryInterval must be non-negative integer").build(),
+ getLocal(ProtocolViolation.class).statement("MessageExpiryInterval must be non-negative integer")
.clientInfo(clientInfo));
}
if (subscriptionIdentifier(mqttProperties).isPresent()) {
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/DedupCacheTest.java b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/DedupCacheTest.java
new file mode 100644
index 000000000..9b13534aa
--- /dev/null
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/DedupCacheTest.java
@@ -0,0 +1,169 @@
+/*
+ * 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.bifromq.mqtt.handler;
+
+import static org.awaitility.Awaitility.await;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+
+import java.lang.ref.WeakReference;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import org.testng.annotations.Test;
+
+public class DedupCacheTest {
+ private static final long EXPIRE_MS = 50;
+
+ @Test
+ public void testSameChannelSameTopic() {
+ DedupCache cache = new DedupCache(EXPIRE_MS, 32, 32);
+ String ch = "ch-1";
+ String topic = "sensor/temperature";
+ assertFalse(cache.isDuplicate(ch, topic, 100));
+ assertTrue(cache.isDuplicate(ch, topic, 100));
+ assertTrue(cache.isDuplicate(ch, topic, 99));
+ assertFalse(cache.isDuplicate(ch, topic, 101));
+ }
+
+ @Test
+ public void testSameChannelCrossTopicOutOfOrder() {
+ DedupCache cache = new DedupCache(EXPIRE_MS, 32, 32);
+ String ch = "ch-1";
+ assertFalse(cache.isDuplicate(ch, "A", 200));
+ assertFalse(cache.isDuplicate(ch, "B", 100));
+ }
+
+ @Test
+ public void testDifferentChannelSameTopicIndependent() {
+ DedupCache cache = new DedupCache(EXPIRE_MS, 32, 32);
+ String t = new String("topic/x");
+ assertFalse(cache.isDuplicate("ch-1", t, 100));
+ assertFalse(cache.isDuplicate("ch-2", new String("topic/x"), 50));
+ assertTrue(cache.isDuplicate("ch-1", "topic/x", 100));
+ assertFalse(cache.isDuplicate("ch-2", "topic/x", 60));
+ }
+
+ @Test
+ public void testExpireAfterAccess() throws Exception {
+ DedupCache cache = new DedupCache(20, 32, 32);
+ String ch = "ch-1";
+ String topic = "expire/topic";
+ assertFalse(cache.isDuplicate(ch, topic, 100));
+ Thread.sleep(30);
+ // entry may expire, old timestamp should not cause duplicate
+ assertFalse(cache.isDuplicate(ch, topic, 90));
+ assertTrue(cache.channelEvictedByExpired() >= 0);
+ }
+
+ @Test
+ public void testInnerEvictionBySize() {
+ DedupCache cache = new DedupCache(EXPIRE_MS, 4, 2);
+ String ch = "ch-1";
+ assertFalse(cache.isDuplicate(ch, "t1", 1));
+ assertFalse(cache.isDuplicate(ch, "t2", 2));
+ long before = cache.topicEvictedBySize();
+ assertFalse(cache.isDuplicate(ch, "t3", 3));
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ assertTrue(cache.topicEvictedBySize() >= before)
+ );
+ }
+
+ @Test
+ public void testOuterEvictionBySize() {
+ DedupCache cache = new DedupCache(EXPIRE_MS, 1, 8);
+ assertFalse(cache.isDuplicate("c1", "t", 1));
+ long before = cache.channelEvictedBySize();
+ assertFalse(cache.isDuplicate("c2", "t", 1));
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
+ assertTrue(cache.channelEvictedBySize() >= before);
+ assertEquals(cache.estimatedChannels(), 1);
+ });
+ }
+
+ @Test
+ public void testTotalCachedTopicsCounting() {
+ DedupCache cache = new DedupCache(1000, 16, 16);
+ assertEquals(cache.totalCachedTopics(), 0);
+ assertFalse(cache.isDuplicate("c1", "t1", 1));
+ assertEquals(cache.totalCachedTopics(), 1);
+ assertTrue(cache.isDuplicate("c1", "t1", 1));
+ assertEquals(cache.totalCachedTopics(), 1);
+ assertFalse(cache.isDuplicate("c1", "t2", 2));
+ assertEquals(cache.totalCachedTopics(), 2);
+ assertFalse(cache.isDuplicate("c2", "t1", 3));
+ assertEquals(cache.totalCachedTopics(), 3);
+ }
+
+ @Test
+ public void testTotalCachedTopicsInnerEvictionKeepsBound() {
+ DedupCache cache = new DedupCache(1000, 2, 2);
+ assertFalse(cache.isDuplicate("c1", "t1", 1));
+ assertFalse(cache.isDuplicate("c1", "t2", 2));
+ assertEquals(cache.totalCachedTopics(), 2);
+ assertFalse(cache.isDuplicate("c1", "t3", 3));
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ assertEquals(cache.totalCachedTopics(), 2)
+ );
+ }
+
+ @Test
+ public void testTotalCachedTopicsOuterEvictionKeepsBound() {
+ DedupCache cache = new DedupCache(1000, 1, 8);
+ assertFalse(cache.isDuplicate("c1", "t1", 1));
+ assertEquals(cache.totalCachedTopics(), 1);
+ assertFalse(cache.isDuplicate("c2", "t1", 2));
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ assertEquals(cache.totalCachedTopics(), 1)
+ );
+ }
+
+ @Test
+ public void testInternedTopicsAreGCedAfterEviction() {
+ DedupCache cache = new DedupCache(30, 4, 8);
+ String ch = "c-gc";
+ List<WeakReference<String>> refs = new ArrayList<>();
+
+ for (int i = 0; i < 40; i++) {
+ String topic = new String("gc/topic-" + i);
+ refs.add(new WeakReference<>(topic));
+ assertFalse(cache.isDuplicate(ch, topic, i + 1));
+ topic = null;
+ }
+
+ try {
+ Thread.sleep(60);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ for (int i = 0; i < 200; i++) {
+ cache.isDuplicate(ch, "hot/" + (i % 16), 1000 + i);
+ }
+
+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ System.gc();
+ for (WeakReference<String> wr : refs) {
+ assertNull(wr.get());
+ }
+ });
+ }
+}
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/MQTTSessionStallEventTest.java b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/MQTTSessionStallEventTest.java
new file mode 100644
index 000000000..9330921c8
--- /dev/null
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/MQTTSessionStallEventTest.java
@@ -0,0 +1,212 @@
+/*
+ * 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.bifromq.mqtt.handler;
+
+import static org.apache.bifromq.mqtt.handler.MQTTSessionIdUtil.userSessionId;
+import static org.apache.bifromq.plugin.settingprovider.Setting.MaxResendTimes;
+import static org.apache.bifromq.plugin.settingprovider.Setting.ResendTimeoutSeconds;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.mqtt.MqttDecoder;
+import io.netty.handler.traffic.ChannelTrafficShapingHandler;
+import io.netty.util.concurrent.EventExecutor;
+import java.lang.reflect.Method;
+import java.net.InetSocketAddress;
+import java.util.concurrent.TimeUnit;
+import lombok.SneakyThrows;
+import org.apache.bifromq.inbox.storage.proto.InboxVersion;
+import org.apache.bifromq.metrics.TenantMetric;
+import org.apache.bifromq.mqtt.handler.v3.MQTT3PersistentSessionHandler;
+import org.apache.bifromq.plugin.eventcollector.Event;
+import org.apache.bifromq.plugin.eventcollector.EventType;
+import org.apache.bifromq.type.QoS;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class MQTTSessionStallEventTest extends BaseSessionHandlerTest {
+
+ private MQTT3PersistentSessionHandler handler;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setup(Method method) {
+ super.setup(method);
+ // shrink stall timeout to 1s for fast tests
+ when(settingProvider.provide(eq(MaxResendTimes), anyString())).thenReturn(1);
+ when(settingProvider.provide(eq(ResendTimeoutSeconds), anyString())).thenReturn(1);
+
+ ChannelDuplexHandler sessionHandlerAdder = buildChannelHandler();
+ mockInboxReader();
+ channel = new EmbeddedChannel(true, true, new ChannelInitializer<>() {
+ @Override
+ protected void initChannel(Channel ch) {
+ ch.attr(ChannelAttrs.MQTT_SESSION_CTX).set(sessionContext);
+ ch.attr(ChannelAttrs.PEER_ADDR).set(new InetSocketAddress(remoteIp, remotePort));
+ ChannelPipeline pipeline = ch.pipeline();
+ pipeline.addLast(new ChannelTrafficShapingHandler(512 * 1024, 512 * 1024));
+ pipeline.addLast(MqttDecoder.class.getName(), new MqttDecoder(256 * 1024));
+ pipeline.addLast(sessionHandlerAdder);
+ }
+ });
+ handler = (MQTT3PersistentSessionHandler) channel.pipeline().last();
+ }
+
+ @SneakyThrows
+ @AfterMethod(alwaysRun = true)
+ public void tearDown(Method method) {
+ channel.close();
+ super.tearDown(method);
+ }
+
+ @Override
+ protected ChannelDuplexHandler buildChannelHandler() {
+ return new ChannelDuplexHandler() {
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ super.channelActive(ctx);
+ ctx.pipeline().addLast(MQTT3PersistentSessionHandler.builder()
+ .settings(new TenantSettings(tenantId, settingProvider))
+ .tenantMeter(tenantMeter)
+ .inboxVersion(InboxVersion.newBuilder().setMod(0).setIncarnation(0).build())
+ .oomCondition(oomCondition)
+ .userSessionId(userSessionId(clientInfo))
+ .keepAliveTimeSeconds(120)
+ .clientInfo(clientInfo)
+ .noDelayLWT(null)
+ .ctx(ctx)
+ .build());
+ ctx.pipeline().remove(this);
+ }
+ };
+ }
+
+ @Test
+ public void scheduleAndCancelOnWritable() {
+ // prepare inflight by feeding one qos1 message
+ mockCheckPermission(true);
+ inboxFetchConsumer.accept(fetch(1, 128, QoS.AT_LEAST_ONCE));
+ channel.runPendingTasks();
+
+ reset(eventCollector);
+ // simulate unwritable via a mocked ctx: schedule stall task
+ ChannelHandlerContext mockCtx = mock(ChannelHandlerContext.class);
+ when(mockCtx.channel()).thenReturn(channel);
+ EventExecutor executor = channel.eventLoop();
+ when(mockCtx.executor()).thenReturn(executor);
+
+ // first as false -> schedule stall check
+ // we mock isWritable by delegating to a wrapper Channel returning false only for this call
+ Channel fakeCh = Mockito.mock(Channel.class);
+ when(fakeCh.isWritable()).thenReturn(false);
+ when(fakeCh.eventLoop()).thenReturn(channel.eventLoop());
+ when(fakeCh.pipeline()).thenReturn(channel.pipeline());
+ when(fakeCh.bytesBeforeUnwritable()).thenReturn(0L);
+ when(fakeCh.bytesBeforeWritable()).thenReturn(0L);
+ when(fakeCh.config()).thenReturn(channel.config());
+ when(mockCtx.channel()).thenReturn(fakeCh);
+ handler.channelWritabilityChanged(mockCtx);
+
+ // then as true -> cancel
+ when(mockCtx.channel()).thenReturn(channel); // back to real channel which is writable
+ handler.channelWritabilityChanged(mockCtx);
+
+ // advance time beyond 1s, scheduled stall should have been canceled, so no event
+ channel.advanceTimeBy(2, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+
+ verify(eventCollector, times(0)).report(any(Event.class));
+ }
+
+ @Test
+ public void fireOnceOnTimeoutWhenStillUnwritable() {
+ mockCheckPermission(true);
+ inboxFetchConsumer.accept(fetch(1, 128, QoS.AT_LEAST_ONCE));
+ channel.runPendingTasks();
+
+ // reset any previous events
+ reset(eventCollector);
+ // schedule using a fake ctx whose channel reports unwritable
+ ChannelHandlerContext mockCtx = mock(ChannelHandlerContext.class);
+ Channel fakeCh = Mockito.mock(Channel.class);
+ when(fakeCh.isWritable()).thenReturn(false);
+ when(fakeCh.eventLoop()).thenReturn(channel.eventLoop());
+ when(fakeCh.pipeline()).thenReturn(channel.pipeline());
+ when(fakeCh.bytesBeforeUnwritable()).thenReturn(0L);
+ when(fakeCh.bytesBeforeWritable()).thenReturn(0L);
+ when(fakeCh.config()).thenReturn(channel.config());
+ when(mockCtx.channel()).thenReturn(fakeCh);
+ when(mockCtx.executor()).thenReturn(channel.eventLoop());
+ handler.channelWritabilityChanged(mockCtx);
+
+ // keep unwritable at fire time by keeping fakeCh on schedule
+ channel.advanceTimeBy(2, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+
+ ArgumentCaptor<Event> captor = ArgumentCaptor.forClass(Event.class);
+ verify(eventCollector, times(1)).report(captor.capture());
+ assert captor.getValue().type() == EventType.SUB_STALLED;
+ verify(tenantMeter, times(1)).recordCount(TenantMetric.MqttStalledCount);
+ }
+
+ @Test
+ public void cancelOnChannelInactive() {
+ mockCheckPermission(true);
+ inboxFetchConsumer.accept(fetch(1, 128, QoS.AT_LEAST_ONCE));
+ channel.runPendingTasks();
+
+ reset(eventCollector);
+ mockSessionReg();
+
+ ChannelHandlerContext mockCtx = mock(ChannelHandlerContext.class);
+ Channel fakeCh = Mockito.mock(Channel.class);
+ when(fakeCh.isWritable()).thenReturn(false);
+ when(fakeCh.eventLoop()).thenReturn(channel.eventLoop());
+ when(fakeCh.pipeline()).thenReturn(channel.pipeline());
+ when(fakeCh.bytesBeforeUnwritable()).thenReturn(0L);
+ when(fakeCh.bytesBeforeWritable()).thenReturn(0L);
+ when(fakeCh.config()).thenReturn(channel.config());
+ when(mockCtx.channel()).thenReturn(fakeCh);
+ when(mockCtx.executor()).thenReturn(channel.eventLoop());
+ handler.channelWritabilityChanged(mockCtx);
+
+ channel.close();
+
+ channel.advanceTimeBy(2, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+
+ verify(eventCollector, times(0)).report(Mockito.argThat(e -> e.type() == EventType.SUB_STALLED));
+ verify(tenantMeter, times(0)).recordCount(TenantMetric.MqttStalledCount);
+ }
+}
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v3/MQTT3PersistentSessionHandlerTest.java b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v3/MQTT3PersistentSessionHandlerTest.java
index 4fe843642..806fa2aa4 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v3/MQTT3PersistentSessionHandlerTest.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v3/MQTT3PersistentSessionHandlerTest.java
@@ -282,6 +282,48 @@ public class MQTT3PersistentSessionHandlerTest extends BaseSessionHandlerTest {
assertEquals(fetchHints.size(), 1);
}
+ @Test
+ public void tryLaterImmediateOnly() {
+ fetchHints.clear();
+ inboxFetchConsumer.accept(Fetched.newBuilder().setResult(Result.TRY_LATER).build());
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 1);
+ channel.advanceTimeBy(60, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 1);
+ }
+
+ @Test
+ public void backPressureSchedulesOneShotHint() {
+ fetchHints.clear();
+ inboxFetchConsumer.accept(Fetched.newBuilder().setResult(Result.BACK_PRESSURE_REJECTED).build());
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 0);
+ channel.advanceTimeBy(60, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 1);
+ channel.advanceTimeBy(60, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 1);
+ }
+
+ @Test
+ public void okCancelsScheduledHint() {
+ fetchHints.clear();
+ inboxFetchConsumer.accept(Fetched.newBuilder().setResult(Result.BACK_PRESSURE_REJECTED).build());
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 0);
+ inboxFetchConsumer.accept(Fetched.newBuilder().setResult(Result.OK).build());
+ channel.runPendingTasks();
+ channel.advanceTimeBy(60, TimeUnit.SECONDS);
+ channel.runScheduledPendingTasks();
+ channel.runPendingTasks();
+ assertEquals(fetchHints.size(), 0);
+ }
+
@Test
public void qoS0PubAuthFailed() {
// not by pass
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v5/PersistentSessionHandlerTest.java b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v5/PersistentSessionHandlerTest.java
index ec891a51d..598c70876 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v5/PersistentSessionHandlerTest.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/handler/v5/PersistentSessionHandlerTest.java
@@ -19,7 +19,7 @@
package org.apache.bifromq.mqtt.handler.v5;
-
+import static io.netty.handler.codec.mqtt.MqttMessageType.PUBREL;
import static org.apache.bifromq.inbox.rpc.proto.UnsubReply.Code.ERROR;
import static org.apache.bifromq.inbox.rpc.proto.UnsubReply.Code.OK;
import static org.apache.bifromq.mqtt.handler.MQTTSessionIdUtil.userSessionId;
@@ -32,13 +32,21 @@ import static org.apache.bifromq.plugin.eventcollector.EventType.QOS1_DROPPED;
import static org.apache.bifromq.plugin.eventcollector.EventType.QOS1_PUSHED;
import static org.apache.bifromq.plugin.eventcollector.EventType.QOS2_CONFIRMED;
import static org.apache.bifromq.plugin.eventcollector.EventType.QOS2_DROPPED;
+import static org.apache.bifromq.plugin.eventcollector.EventType.QOS2_PUSHED;
+import static org.apache.bifromq.plugin.eventcollector.EventType.QOS2_RECEIVED;
import static org.apache.bifromq.plugin.eventcollector.EventType.RETAIN_MSG_MATCHED;
import static org.apache.bifromq.plugin.eventcollector.EventType.SUB_ACKED;
import static org.apache.bifromq.plugin.eventcollector.EventType.UNSUB_ACKED;
+import static org.apache.bifromq.type.MQTTClientInfoConstants.MQTT_CHANNEL_ID_KEY;
+import static org.apache.bifromq.type.MQTTClientInfoConstants.MQTT_TYPE_VALUE;
import static org.apache.bifromq.type.QoS.AT_LEAST_ONCE;
import static org.apache.bifromq.type.QoS.EXACTLY_ONCE;
+import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -47,6 +55,7 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
+import com.google.protobuf.ByteString;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
@@ -56,6 +65,7 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageBuilders;
+import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttReasonCodeAndPropertiesVariableHeader;
import io.netty.handler.codec.mqtt.MqttSubAckMessage;
@@ -65,24 +75,34 @@ import io.netty.handler.codec.mqtt.MqttVersion;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
+import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
+import org.apache.bifromq.basehlc.HLC;
import org.apache.bifromq.inbox.rpc.proto.CommitReply;
import org.apache.bifromq.inbox.rpc.proto.CommitRequest;
import org.apache.bifromq.inbox.rpc.proto.UnsubReply;
import org.apache.bifromq.inbox.storage.proto.Fetched;
import org.apache.bifromq.inbox.storage.proto.Fetched.Result;
+import org.apache.bifromq.inbox.storage.proto.InboxMessage;
import org.apache.bifromq.inbox.storage.proto.InboxVersion;
import org.apache.bifromq.mqtt.handler.BaseSessionHandlerTest;
import org.apache.bifromq.mqtt.handler.ChannelAttrs;
import org.apache.bifromq.mqtt.handler.TenantSettings;
import org.apache.bifromq.mqtt.handler.v5.reason.MQTT5DisconnectReasonCode;
import org.apache.bifromq.mqtt.utils.MQTTMessageUtils;
+import org.apache.bifromq.plugin.eventcollector.mqttbroker.pushhandling.DropReason;
+import org.apache.bifromq.plugin.eventcollector.mqttbroker.pushhandling.QoS0Dropped;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.pushhandling.QoS1Confirmed;
+import org.apache.bifromq.plugin.eventcollector.mqttbroker.pushhandling.QoS1Dropped;
import org.apache.bifromq.plugin.eventcollector.mqttbroker.pushhandling.QoS2Confirmed;
+import org.apache.bifromq.type.ClientInfo;
+import org.apache.bifromq.type.Message;
import org.apache.bifromq.type.QoS;
+import org.apache.bifromq.type.TopicFilterOption;
+import org.apache.bifromq.type.TopicMessage;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -364,30 +384,30 @@ public class PersistentSessionHandlerTest extends BaseSessionHandlerTest {
verify(inboxClient, times(messageCount)).unsub(any());
}
-// @Test
-// public void qoS2PubAndRel() {
-// mockCheckPermission(true);
-// mockInboxCommit(CommitReply.Code.OK);
-// int messageCount = 2;
-// inboxFetchConsumer.accept(fetch(messageCount, 128, EXACTLY_ONCE));
-// channel.runPendingTasks();
-// // s2c pub received and rec
-// for (int i = 0; i < messageCount; i++) {
-// MqttPublishMessage message = channel.readOutbound();
-// assertEquals(message.fixedHeader().qosLevel().value(), QoS.EXACTLY_ONCE_VALUE);
-// assertEquals(message.variableHeader().topicName(), topic);
-// channel.writeInbound(MQTTMessageUtils.publishRecMessage(message.variableHeader().packetId()));
-// }
-// // pubRel received and comp
-// for (int i = 0; i < messageCount; i++) {
-// MqttMessage message = channel.readOutbound();
-// assertEquals(message.fixedHeader().messageType(), PUBREL);
-// channel.writeInbound(MQTTMessageUtils.publishCompMessage(
-// ((MqttMessageIdVariableHeader) message.variableHeader()).messageId()));
-// }
-// verifyEvent(QOS2_PUSHED, QOS2_PUSHED, QOS2_RECEIVED, QOS2_RECEIVED, QOS2_CONFIRMED, QOS2_CONFIRMED);
-// verify(inboxClient, times(2)).commit(argThat(CommitRequest::hasSendBufferUpToSeq));
-// }
+ @Test
+ public void qoS2PubAndRel() {
+ mockCheckPermission(true);
+ mockInboxCommit(CommitReply.Code.OK);
+ int messageCount = 2;
+ inboxFetchConsumer.accept(fetch(messageCount, 128, EXACTLY_ONCE));
+ channel.runPendingTasks();
+ // s2c pub received and rec
+ for (int i = 0; i < messageCount; i++) {
+ MqttPublishMessage message = channel.readOutbound();
+ assertEquals(message.fixedHeader().qosLevel().value(), QoS.EXACTLY_ONCE_VALUE);
+ assertEquals(message.variableHeader().topicName(), topic);
+ channel.writeInbound(MQTTMessageUtils.publishMQTT5RecMessage(message.variableHeader().packetId()));
+ }
+ // pubRel received and comp
+ for (int i = 0; i < messageCount; i++) {
+ MqttMessage message = channel.readOutbound();
+ assertEquals(message.fixedHeader().messageType(), PUBREL);
+ channel.writeInbound(MQTTMessageUtils.publishCompMessage(
+ ((MqttMessageIdVariableHeader) message.variableHeader()).messageId()));
+ }
+ verifyEvent(QOS2_PUSHED, QOS2_PUSHED, QOS2_RECEIVED, QOS2_RECEIVED, QOS2_CONFIRMED, QOS2_CONFIRMED);
+ verify(inboxClient, times(1)).commit(argThat(CommitRequest::hasSendBufferUpToSeq));
+ }
@Test
public void qoS2PubAuthFailed() {
@@ -436,4 +456,153 @@ public class PersistentSessionHandlerTest extends BaseSessionHandlerTest {
channel.runPendingTasks();
verifyEvent(INBOX_TRANSIENT_ERROR);
}
+
+ @Test
+ public void qoS0DuplicateIsDropped() {
+ reset(eventCollector);
+ mockInboxCommit(CommitReply.Code.OK);
+ mockCheckPermission(true);
+ // build two qos0 messages with same topic and same channel, second is duplicate by timestamp
+ Fetched.Builder builder = Fetched.newBuilder();
+ byte[] bytes = new byte[8];
+ ClientInfo publisher = ClientInfo.newBuilder().setType(MQTT_TYPE_VALUE)
+ .putMetadata(MQTT_CHANNEL_ID_KEY, "dup-chan").build();
+
+ long now = HLC.INST.get();
+ TopicMessage m1 = TopicMessage.newBuilder()
+ .setTopic(topic)
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(1)
+ .setPubQoS(QoS.AT_MOST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(5000)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ TopicMessage m2dup = TopicMessage.newBuilder()
+ .setTopic(topic)
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(2)
+ .setPubQoS(QoS.AT_MOST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(5000)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ InboxMessage im1 = InboxMessage.newBuilder().setSeq(0)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_MOST_ONCE).build())
+ .setMsg(m1).build();
+ InboxMessage im2 = InboxMessage.newBuilder().setSeq(1)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_MOST_ONCE).build())
+ .setMsg(m2dup).build();
+ builder.addQos0Msg(im1).addQos0Msg(im2);
+ inboxFetchConsumer.accept(builder.build());
+ channel.runPendingTasks();
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ verify(eventCollector, atLeast(2)).report(any())
+ );
+ verify(eventCollector, atLeast(1)).report(argThat(e ->
+ e.type() == QOS0_DROPPED && ((QoS0Dropped) e).reason() == DropReason.Duplicated));
+ verify(eventCollector, atLeast(1)).report(argThat(e -> e.type() == QOS0_PUSHED));
+ }
+
+ @Test
+ public void qoS1DuplicateIsDropped() {
+ reset(eventCollector);
+ mockInboxCommit(CommitReply.Code.OK);
+ mockCheckPermission(true);
+ Fetched.Builder builder = Fetched.newBuilder();
+ byte[] bytes = new byte[8];
+ ClientInfo publisher = ClientInfo.newBuilder().setType(MQTT_TYPE_VALUE)
+ .putMetadata(MQTT_CHANNEL_ID_KEY, "dup-chan").build();
+ long now = HLC.INST.get();
+ TopicMessage m1 = TopicMessage.newBuilder()
+ .setTopic(topic)
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(1)
+ .setPubQoS(QoS.AT_LEAST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(120)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ TopicMessage m2dup = TopicMessage.newBuilder()
+ .setTopic(topic)
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(2)
+ .setPubQoS(QoS.AT_LEAST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(120)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ InboxMessage im1 = InboxMessage.newBuilder().setSeq(0)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_LEAST_ONCE).build())
+ .setMsg(m1).build();
+ InboxMessage im2 = InboxMessage.newBuilder().setSeq(1)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_LEAST_ONCE).build())
+ .setMsg(m2dup).build();
+ builder.addSendBufferMsg(im1).addSendBufferMsg(im2);
+ inboxFetchConsumer.accept(builder.build());
+ channel.runPendingTasks();
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ verify(eventCollector, atLeast(2)).report(any())
+ );
+ verify(eventCollector, atLeast(1)).report(argThat(e ->
+ e.type() == QOS1_DROPPED && ((QoS1Dropped) e).reason() == DropReason.Duplicated));
+ verify(eventCollector, atLeast(1)).report(argThat(e ->
+ e.type() == QOS1_PUSHED));
+ }
+
+ @Test
+ public void crossTopicOutOfOrderNotDropped() {
+ reset(eventCollector);
+ mockInboxCommit(CommitReply.Code.OK);
+ mockCheckPermission(true);
+ Fetched.Builder builder = Fetched.newBuilder();
+ byte[] bytes = new byte[8];
+ ClientInfo publisher = ClientInfo.newBuilder().setType(MQTT_TYPE_VALUE)
+ .putMetadata(MQTT_CHANNEL_ID_KEY, "same-chan").build();
+ long now = HLC.INST.get();
+ TopicMessage a = TopicMessage.newBuilder()
+ .setTopic("topic/a")
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(1)
+ .setPubQoS(QoS.AT_MOST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(120)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ TopicMessage b = TopicMessage.newBuilder()
+ .setTopic("topic/b")
+ .setPublisher(publisher)
+ .setMessage(Message.newBuilder()
+ .setMessageId(2)
+ .setPubQoS(QoS.AT_MOST_ONCE)
+ .setTimestamp(now)
+ .setExpiryInterval(120)
+ .setPayload(ByteString.copyFrom(bytes))
+ .build())
+ .build();
+ InboxMessage im1 = InboxMessage.newBuilder().setSeq(0)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_MOST_ONCE).build())
+ .setMsg(a).build();
+ InboxMessage im2 = InboxMessage.newBuilder().setSeq(1)
+ .putMatchedTopicFilter(topicFilter, TopicFilterOption.newBuilder().setQos(QoS.AT_MOST_ONCE).build())
+ .setMsg(b).build();
+ builder.addQos0Msg(im1).addQos0Msg(im2);
+ inboxFetchConsumer.accept(builder.build());
+ channel.runPendingTasks();
+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
+ verify(eventCollector, atLeast(1)).report(any())
+ );
+ verify(eventCollector, never()).report(argThat(e ->
+ e.type() == QOS0_DROPPED && ((QoS0Dropped) e).reason() == DropReason.Duplicated));
+ }
}
diff --git a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/integration/v3/MQTTLastWillTest.java b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/integration/v3/MQTTLastWillTest.java
index ab9955640..4e419fdf7 100644
--- a/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/integration/v3/MQTTLastWillTest.java
+++ b/bifromq-mqtt/bifromq-mqtt-server/src/test/java/org/apache/bifromq/mqtt/integration/v3/MQTTLastWillTest.java
@@ -215,12 +215,19 @@ public class MQTTLastWillTest extends MQTTTest {
kill(deviceKey, "lwtPubclient").join();
- topicSub.awaitCount(2);
- MqttMsg msg = topicSub.values().get(topicSub.values().size() - 1);
- assertEquals(msg.topic, willTopic);
- assertEquals(msg.qos, 2);
- assertEquals(msg.payload, willPayload);
- assertFalse(msg.isRetain);
+ // Wait until the last observed message is the will message
+ await().until(() -> {
+ try {
+ MqttMsg last = topicSub.values().get(topicSub.values().size() - 1);
+ assertEquals(last.topic, willTopic);
+ assertEquals(last.qos, 2);
+ assertEquals(last.payload, willPayload);
+ assertFalse(last.isRetain);
+ return true;
+ } catch (Throwable e) {
+ return false; // keep waiting until the will message arrives
+ }
+ });
}
@Test(groups = "integration")
diff --git a/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/EventType.java b/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/EventType.java
index f61424921..f7fc83c44 100644
--- a/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/EventType.java
+++ b/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/EventType.java
@@ -94,6 +94,7 @@ public enum EventType {
SUB_ACTION_DISALLOW,
UNSUB_ACTION_DISALLOW,
ACCESS_CONTROL_ERROR,
+ SUB_STALLED,
SUB_ACKED,
UNSUB_ACKED,
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java b/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/mqttbroker/SubStalled.java
similarity index 52%
copy from base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
copy to bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/mqttbroker/SubStalled.java
index 800fd4d8a..a81f074af 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
+++ b/bifromq-plugin/bifromq-plugin-event-collector/src/main/java/org/apache/bifromq/plugin/eventcollector/mqttbroker/SubStalled.java
@@ -17,24 +17,30 @@
* under the License.
*/
-package org.apache.bifromq.basekv.raft.exception;
+package org.apache.bifromq.plugin.eventcollector.mqttbroker;
-public class CompactionException extends RuntimeException {
- public static StaleSnapshotException staleSnapshot() {
- return new StaleSnapshotException();
- }
+import static org.apache.bifromq.plugin.eventcollector.EventType.SUB_STALLED;
- public CompactionException(String message, Throwable cause) {
- super(message, cause);
- }
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.apache.bifromq.plugin.eventcollector.ClientEvent;
+import org.apache.bifromq.plugin.eventcollector.EventType;
- private CompactionException(String message) {
- super(message);
- }
+@Getter
+@Setter
+@Accessors(fluent = true, chain = true)
+@ToString(callSuper = true)
+public final class SubStalled extends ClientEvent<SubStalled> {
+ private long bytesBeforeWritable;
+ private int unconfirmedCount;
+ private int writeBufferLowWaterMark;
+ private int writeBufferHighWaterMark;
- public static class StaleSnapshotException extends CompactionException {
- private StaleSnapshotException() {
- super("Stale Snapshot");
- }
+ @Override
+ public EventType type() {
+ return SUB_STALLED;
}
}
+
diff --git a/bifromq-session-dict/bifromq-session-dict-client/src/main/java/org/apache/bifromq/sessiondict/client/SessionDictClient.java b/bifromq-session-dict/bifromq-session-dict-client/src/main/java/org/apache/bifromq/sessiondict/client/SessionDictClient.java
index 62bd13989..9bf97977c 100644
--- a/bifromq-session-dict/bifromq-session-dict-client/src/main/java/org/apache/bifromq/sessiondict/client/SessionDictClient.java
+++ b/bifromq-session-dict/bifromq-session-dict-client/src/main/java/org/apache/bifromq/sessiondict/client/SessionDictClient.java
@@ -137,7 +137,7 @@ final class SessionDictClient implements ISessionDictClient {
}
})
.exceptionally(e -> {
- log.debug("Kill all failed", e);
+ log.debug("Failed to handle KillAllRequest", e);
return KillAllReply.newBuilder()
.setReqId(reqId)
.setResult(KillAllReply.Result.ERROR)
@@ -151,7 +151,7 @@ final class SessionDictClient implements ISessionDictClient {
return rpcClient.invoke(request.getTenantId(), null, request,
SessionDictServiceGrpc.getGetMethod())
.exceptionally(e -> {
- log.debug("Get failed", e);
+ log.debug("Failed to handle GetRequest", e);
return GetReply.newBuilder()
.setReqId(request.getReqId())
.setResult(GetReply.Result.ERROR)
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java b/bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupChannels.java
similarity index 57%
copy from base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
copy to bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupChannels.java
index 800fd4d8a..0363bdc7c 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
+++ b/bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupChannels.java
@@ -14,27 +14,22 @@
* "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.
+ * under the License.
*/
-package org.apache.bifromq.basekv.raft.exception;
+package org.apache.bifromq.sysprops.props;
-public class CompactionException extends RuntimeException {
- public static StaleSnapshotException staleSnapshot() {
- return new StaleSnapshotException();
- }
-
- public CompactionException(String message, Throwable cause) {
- super(message, cause);
- }
+import org.apache.bifromq.sysprops.BifroMQSysProp;
+import org.apache.bifromq.sysprops.parser.IntegerParser;
- private CompactionException(String message) {
- super(message);
- }
+/**
+ * Max active dedup channels per session, bounded to positive integer.
+ */
+public final class MaxActiveDedupChannels extends BifroMQSysProp<Integer, IntegerParser> {
+ public static final MaxActiveDedupChannels INSTANCE = new MaxActiveDedupChannels();
- public static class StaleSnapshotException extends CompactionException {
- private StaleSnapshotException() {
- super("Stale Snapshot");
- }
+ private MaxActiveDedupChannels() {
+ super("maxActiveDedupChannels", 1024, IntegerParser.POSITIVE);
}
}
+
diff --git a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java b/bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupTopicsPerChannel.java
similarity index 57%
copy from base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
copy to bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupTopicsPerChannel.java
index 800fd4d8a..e3da67e0a 100644
--- a/base-kv/base-kv-raft/src/main/java/org/apache/bifromq/basekv/raft/exception/CompactionException.java
+++ b/bifromq-sysprops/src/main/java/org/apache/bifromq/sysprops/props/MaxActiveDedupTopicsPerChannel.java
@@ -14,27 +14,22 @@
* "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.
+ * under the License.
*/
-package org.apache.bifromq.basekv.raft.exception;
+package org.apache.bifromq.sysprops.props;
-public class CompactionException extends RuntimeException {
- public static StaleSnapshotException staleSnapshot() {
- return new StaleSnapshotException();
- }
-
- public CompactionException(String message, Throwable cause) {
- super(message, cause);
- }
+import org.apache.bifromq.sysprops.BifroMQSysProp;
+import org.apache.bifromq.sysprops.parser.IntegerParser;
- private CompactionException(String message) {
- super(message);
- }
+/**
+ * Max active dedup topics per channel, bounded to positive integer.
+ */
+public final class MaxActiveDedupTopicsPerChannel extends BifroMQSysProp<Integer, IntegerParser> {
+ public static final MaxActiveDedupTopicsPerChannel INSTANCE = new MaxActiveDedupTopicsPerChannel();
- public static class StaleSnapshotException extends CompactionException {
- private StaleSnapshotException() {
- super("Stale Snapshot");
- }
+ private MaxActiveDedupTopicsPerChannel() {
+ super("maxActiveDedupTopicsPerChannel", 10, IntegerParser.POSITIVE);
}
}
+
diff --git a/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/config/model/inbox/InboxStoreConfig.java b/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/config/model/inbox/InboxStoreConfig.java
index 64078075b..e6535873a 100644
--- a/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/config/model/inbox/InboxStoreConfig.java
+++ b/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/config/model/inbox/InboxStoreConfig.java
@@ -48,7 +48,9 @@ public class InboxStoreConfig {
private int maxWALFetchSize = -1; // no limit
private int compactWALThreshold = 256 * 1024 * 1024; // size threshold in bytes
private int expireRateLimit = 1000;
- private int gcIntervalSeconds = 600;
+ private int minGCIntervalSeconds = 30; // every 30 s
+ private int maxGCIntervalSeconds = 24 * 3600; // every day
+
@JsonSetter(nulls = Nulls.SKIP)
@JsonMerge
private EngineConfig dataEngineConfig = new EngineConfig()
diff --git a/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/module/InboxServiceModule.java b/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/module/InboxServiceModule.java
index 0f36b5bd4..46f077deb 100644
--- a/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/module/InboxServiceModule.java
+++ b/build/build-bifromq-starter/src/main/java/org/apache/bifromq/starter/module/InboxServiceModule.java
@@ -120,8 +120,8 @@ public class InboxServiceModule extends AbstractModule {
.bgTaskExecutor(
injector.getInstance(Key.get(ScheduledExecutorService.class, Names.named("bgTaskScheduler"))))
.expireRateLimit(storeConfig.getExpireRateLimit())
- .gcInterval(
- Duration.ofSeconds(storeConfig.getGcIntervalSeconds()))
+ .minGCInterval(Duration.ofSeconds(storeConfig.getMinGCIntervalSeconds()))
+ .maxGCInterval(Duration.ofSeconds(storeConfig.getMaxGCIntervalSeconds()))
.bootstrapDelay(Duration.ofMillis(storeConfig.getBalanceConfig().getBootstrapDelayInMS()))
.zombieProbeDelay(Duration.ofMillis(storeConfig.getBalanceConfig().getZombieProbeDelayInMS()))
.balancerRetryDelay(Duration.ofMillis(