Browse Source

rule-engine: address review of targeted partition change broadcast

- Resolve affected tenants in PartitionChangeEvent.getAffectedTenants(),
  returning null (all tenants) for non rule engine events, empty diffs and
  shared queue changes.
- HashPartitionService adds isolated tenants whose managed status changed
  without a change of their own queue keys.
- PartitionChangeMsg: forAllTenants/forTenants factories instead of a null
  sentinel; affected tenants excluded from toString().
- Fold the AppActor log line into the existing DefaultActorService one.
- Tests: priority ordering in ActorSystemTest, AppActorTest on a real actor
  system, DefaultActorServiceTest through onTbApplicationEvent, the
  managed-status scenario in HashPartitionServiceTest.
pull/15961/head
Sergey Matvienko 2 months ago
parent
commit
65364922cf
  1. 6
      application/src/main/java/org/thingsboard/server/actors/app/AppActor.java
  2. 36
      application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java
  3. 151
      application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java
  4. 99
      application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java
  5. 36
      application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
  6. 69
      common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java
  7. 36
      common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java
  8. 56
      common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java
  9. 33
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
  10. 30
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java
  11. 88
      common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java
  12. 2
      rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java

6
application/src/main/java/org/thingsboard/server/actors/app/AppActor.java

@ -208,15 +208,13 @@ public class AppActor extends ContextAwareActor {
}
private void onPartitionChangeMsg(PartitionChangeMsg msg) {
Set<TenantId> affectedTenants = msg.getAffectedTenants();
log.info("Partition change for {}: notifying {} affected tenant(s)", msg.getServiceType(), affectedTenants == null ? "ALL" : affectedTenants.size());
if (affectedTenants == null) {
if (msg.isForAllTenants()) {
ctx.broadcastToChildren(msg, true);
} else {
ctx.broadcastToChildren(msg, new TbEntityTypeActorIdPredicate(EntityType.TENANT) {
@Override
protected boolean testEntityId(EntityId entityId) {
return super.testEntityId(entityId) && affectedTenants.contains(entityId);
return super.testEntityId(entityId) && msg.isAffected((TenantId) entityId);
}
}, true);
}

36
application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java

@ -22,7 +22,6 @@ import org.thingsboard.server.actors.stats.StatsActor;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.queue.discovery.QueueKey;
import org.thingsboard.server.queue.discovery.TbApplicationEventListener;
import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent;
import org.thingsboard.server.queue.util.AfterStartUp;
@ -30,7 +29,6 @@ import org.thingsboard.server.queue.util.AfterStartUp;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
@Service
@Slf4j
@ -123,34 +121,12 @@ public class DefaultActorService extends TbApplicationEventListener<PartitionCha
@Override
protected void onTbApplicationEvent(PartitionChangeEvent event) {
log.info("Received partition change event.");
appActor.tellWithHighPriority(new PartitionChangeMsg(event.getServiceType(), resolveAffectedTenants(event)));
}
/**
* Resolves which tenants are affected by a partition-ownership change, so the caller can
* notify only those tenant actors instead of every live one.
* <p>
* Despite its name, {@link PartitionChangeEvent#getNewPartitions()} carries only the
* <b>changed subset</b> of queue keys — including removed ones, mapped to an empty partition
* set — never the full current assignment. That invariant is what makes this method correct;
* if it ever carried the full assignment instead, every recalculation would resolve to
* "everyone".
* <p>
* Returns {@code null} when any changed queue key belongs to the shared (non-isolated) tenant
* pool (a sys-tenant-keyed queue) — that pool's tenants aren't individually tracked as queue
* keys, so they can't be enumerated, and every tenant actor must be notified. Otherwise
* returns the non-empty set of affected tenant IDs. Callers must treat {@code null} as
* "notify everyone", never as "notify nobody" — an empty set would mean the latter, but this
* method never returns one today, since it is only invoked when the diff is non-empty.
*/
static Set<TenantId> resolveAffectedTenants(PartitionChangeEvent event) {
Set<QueueKey> changedQueueKeys = event.getNewPartitions().keySet();
boolean sharedPoolChanged = changedQueueKeys.stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId());
if (sharedPoolChanged) {
return null;
}
return changedQueueKeys.stream().map(QueueKey::getTenantId).collect(Collectors.toSet());
ServiceType serviceType = event.getServiceType();
Set<TenantId> affectedTenants = event.getAffectedTenants();
log.info("Received partition change event for {}, affected tenants: {}", serviceType, affectedTenants == null ? "all" : affectedTenants.size());
appActor.tellWithHighPriority(affectedTenants == null ?
PartitionChangeMsg.forAllTenants(serviceType) :
PartitionChangeMsg.forTenants(serviceType, affectedTenants));
}
@Override

151
application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java

@ -1,92 +1,125 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* Licensed 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.
*/
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.actors.app;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.actors.AbstractTbActor;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.actors.TbActorCtx;
import org.thingsboard.server.actors.DefaultTbActorSystem;
import org.thingsboard.server.actors.TbActor;
import org.thingsboard.server.actors.TbActorCreator;
import org.thingsboard.server.actors.TbActorId;
import org.thingsboard.server.actors.TbActorRef;
import org.thingsboard.server.actors.TbActorSystem;
import org.thingsboard.server.actors.TbActorSystemSettings;
import org.thingsboard.server.actors.TbEntityActorId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.actors.TbStringActorId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.TbActorMsg;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.dao.tenant.TenantService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AppActorTest {
class AppActorTest {
AppActor appActor;
TbActorCtx ctx;
TenantId tenant1 = new TenantId(UUID.fromString("11111111-1111-1111-1111-111111111111"));
TenantId tenant2 = new TenantId(UUID.fromString("22222222-2222-2222-2222-222222222222"));
private static final String DISPATCHER = "app-actor-test-dispatcher";
@Before
public void setUp() throws Exception {
private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID());
private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID());
private ExecutorService executor;
private TbActorSystem system;
private TbActorRef appActor;
private List<TbActorMsg> tenant1Msgs;
private List<TbActorMsg> tenant2Msgs;
private List<TbActorMsg> otherChildMsgs;
@BeforeEach
void setUp() {
ActorSystemContext systemContext = mock(ActorSystemContext.class);
TenantService tenantService = mock(TenantService.class);
when(systemContext.getTenantService()).thenReturn(tenantService);
when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false);
when(systemContext.getTenantService()).thenReturn(mock(TenantService.class));
when(systemContext.getServiceInfoProvider()).thenReturn(mock(TbServiceInfoProvider.class));
when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false);
appActor = (AppActor) new AppActor.ActorCreator(systemContext).createActor();
ctx = mock(TbActorCtx.class);
appActor.init(ctx);
appActor.doProcess(new AppInitMsg());
}
executor = Executors.newSingleThreadExecutor();
system = new DefaultTbActorSystem(new TbActorSystemSettings(5, 1, 42));
system.createDispatcher(DISPATCHER, executor);
appActor = system.createRootActor(DISPATCHER, new AppActor.ActorCreator(systemContext));
appActor.tellWithHighPriority(new AppInitMsg());
@Test
public void onPartitionChangeMsgWithAffectedTenants_onlyForwardsToThoseTenants() {
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant1));
tenant1Msgs = createRecordingChild(new TbEntityActorId(tenant1));
tenant2Msgs = createRecordingChild(new TbEntityActorId(tenant2));
otherChildMsgs = createRecordingChild(new TbStringActorId("other"));
}
appActor.doProcess(msg);
@AfterEach
void tearDown() {
system.stop();
executor.shutdownNow();
}
@SuppressWarnings("unchecked")
ArgumentCaptor<Predicate<TbActorId>> filterCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true));
Predicate<TbActorId> filter = filterCaptor.getValue();
@Test
void msgForTenants_isDeliveredToAffectedTenantActorsOnly() {
PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, Set.of(tenant1));
appActor.tellWithHighPriority(msg);
// processed by the app actor after msg, so it reaches every child after msg would have
PartitionChangeMsg marker = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE);
appActor.tellWithHighPriority(marker);
assertTrue(filter.test(new TbEntityActorId(tenant1)));
assertFalse(filter.test(new TbEntityActorId(tenant2)));
assertFalse(filter.test(new TbEntityActorId(new DeviceId(UUID.randomUUID()))));
await().atMost(10, TimeUnit.SECONDS).until(() -> tenant2Msgs.contains(marker) && otherChildMsgs.contains(marker));
assertThat(tenant1Msgs).containsExactly(msg, marker);
assertThat(tenant2Msgs).containsExactly(marker);
assertThat(otherChildMsgs).containsExactly(marker);
}
@Test
public void onPartitionChangeMsgWithNullAffectedTenants_broadcastsToEveryone() {
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE);
void msgForAllTenants_isDeliveredToEveryChild() {
PartitionChangeMsg msg = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE);
appActor.tellWithHighPriority(msg);
appActor.doProcess(msg);
await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
assertThat(tenant1Msgs).containsExactly(msg);
assertThat(tenant2Msgs).containsExactly(msg);
assertThat(otherChildMsgs).containsExactly(msg);
});
}
private List<TbActorMsg> createRecordingChild(TbActorId actorId) {
List<TbActorMsg> received = new CopyOnWriteArrayList<>();
system.createChildActor(DISPATCHER, new TbActorCreator() {
@Override
public TbActorId createActorId() {
return actorId;
}
verify(ctx).broadcastToChildren(msg, true);
verify(ctx, never()).broadcastToChildren(any(), any(), anyBoolean());
@Override
public TbActor createActor() {
return new AbstractTbActor() {
@Override
public boolean process(TbActorMsg msg) {
received.add(msg);
return true;
}
};
}
}, appActor.getActorId());
return received;
}
}

99
application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java

@ -1,24 +1,16 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* Licensed 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.
*/
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.actors.service;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.actors.TbActorRef;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.queue.discovery.QueueKey;
import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent;
@ -27,38 +19,61 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DefaultActorServiceTest {
class DefaultActorServiceTest {
private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID());
private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID());
private DefaultActorService actorService;
private TbActorRef appActor;
@BeforeEach
void setUp() {
actorService = new DefaultActorService();
appActor = mock(TbActorRef.class);
ReflectionTestUtils.setField(actorService, "appActor", appActor);
}
@Test
public void resolveAffectedTenants_onlyTenantSpecificQueueKeysChanged_returnsThoseTenants() {
TenantId tenant1 = new TenantId(UUID.randomUUID());
TenantId tenant2 = new TenantId(UUID.randomUUID());
QueueKey mainQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant1);
QueueKey highPriorityQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "HighPriority", tenant1);
QueueKey mainQueueTenant2 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant2);
Map<QueueKey, Set<TopicPartitionInfo>> newPartitions = Map.of(
mainQueueTenant1, Collections.emptySet(),
highPriorityQueueTenant1, Collections.emptySet(),
mainQueueTenant2, Collections.emptySet());
PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of());
Set<TenantId> affected = DefaultActorService.resolveAffectedTenants(event);
assertEquals(Set.of(tenant1, tenant2), affected);
void isolatedTenantQueueChanged_sendsMsgForAffectedTenantsOnly() {
actorService.onTbApplicationEvent(event(ServiceType.TB_RULE_ENGINE, tenant1));
PartitionChangeMsg msg = captureMsg();
assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_RULE_ENGINE);
assertThat(msg.isForAllTenants()).isFalse();
assertThat(msg.isAffected(tenant1)).isTrue();
assertThat(msg.isAffected(tenant2)).isFalse();
}
@Test
public void resolveAffectedTenants_sysTenantQueueKeyChanged_returnsNull() {
QueueKey sharedMainQueue = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", TenantId.SYS_TENANT_ID);
Map<QueueKey, Set<TopicPartitionInfo>> newPartitions = Map.of(sharedMainQueue, Collections.emptySet());
PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of());
void sharedQueueChanged_sendsMsgForAllTenants() {
actorService.onTbApplicationEvent(event(ServiceType.TB_RULE_ENGINE, TenantId.SYS_TENANT_ID));
Set<TenantId> affected = DefaultActorService.resolveAffectedTenants(event);
assertThat(captureMsg().isForAllTenants()).isTrue();
}
assertNull(affected);
@Test
void corePartitionsChanged_sendsMsgForAllTenants() {
actorService.onTbApplicationEvent(event(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID));
PartitionChangeMsg msg = captureMsg();
assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_CORE);
assertThat(msg.isForAllTenants()).isTrue();
}
private PartitionChangeEvent event(ServiceType serviceType, TenantId tenantId) {
QueueKey queueKey = new QueueKey(serviceType, DataConstants.MAIN_QUEUE_NAME, tenantId);
return new PartitionChangeEvent(this, serviceType, Map.of(queueKey, Collections.emptySet()), Collections.emptyMap());
}
private PartitionChangeMsg captureMsg() {
ArgumentCaptor<PartitionChangeMsg> captor = ArgumentCaptor.forClass(PartitionChangeMsg.class);
verify(appActor).tellWithHighPriority(captor.capture());
return captor.getValue();
}
}

36
application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java

@ -369,6 +369,42 @@ public class HashPartitionServiceTest {
});
}
@Test
public void testPartitionChangeEvent_includesIsolatedTenantWithChangedManagedStatus() {
ServiceInfo commonRuleEngine = ServiceInfo.newBuilder()
.setServiceId("tb-rule-engine-1")
.addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name()))
.build();
TenantProfileId profileWithoutDedicatedServers = new TenantProfileId(UUID.randomUUID());
TenantProfileId profileWithDedicatedServer = new TenantProfileId(UUID.randomUUID());
ServiceInfo dedicatedRuleEngine = ServiceInfo.newBuilder()
.setServiceId("tb-rule-engine-isolated-1")
.addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name()))
.addAssignedTenantProfiles(profileWithDedicatedServer.toString())
.build();
TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
TenantId otherTenantId = TenantId.fromUUID(UUID.randomUUID());
mockRoutingInfo(tenantId, profileWithoutDedicatedServers, true);
mockRoutingInfo(otherTenantId, profileWithDedicatedServer, true);
mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3), createQueue(otherTenantId, 3)));
when(serviceInfoProvider.isService(eq(ServiceType.TB_RULE_ENGINE))).thenReturn(true);
when(serviceInfoProvider.getAssignedTenantProfiles()).thenReturn(Collections.emptySet());
HashPartitionService partitionService = createPartitionService();
partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList());
assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue();
Mockito.reset(applicationEventPublisher);
partitionService.recalculatePartitions(commonRuleEngine, List.of(dedicatedRuleEngine));
// tenantId's partitions stay on this server, but its managed status changes
assertThat(partitionService.isManagedByCurrentService(tenantId)).isFalse();
verifyPartitionChangeEvent(event -> event.getServiceType() == ServiceType.TB_RULE_ENGINE &&
event.getNewPartitions().keySet().stream().noneMatch(queueKey -> queueKey.getTenantId().equals(tenantId)) &&
Set.of(tenantId, otherTenantId).equals(event.getAffectedTenants()));
}
@Test
public void testPartitionsDistribution_sameTenantDifferentQueues() {
List<ServiceInfo> ruleEngines = new ArrayList<>();

69
common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java

@ -11,11 +11,13 @@ import org.junit.jupiter.api.Test;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.common.util.ThingsBoardThreadFactory;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.msg.TbActorMsg;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -185,29 +187,36 @@ public class ActorSystemTest {
}
@Test
public void testBroadcastToChildrenWithFilterAndPriority() throws InterruptedException {
executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass());
public void testBroadcastToChildrenWithFilterAndHighPriority() throws Exception {
executor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName(getClass().getSimpleName()));
actorSystem.createDispatcher(ROOT_DISPATCHER, executor);
TbActorId parentId = new TbEntityActorId(new DeviceId(UUID.randomUUID()));
ActorTestCtx parentTestCtx = getActorTestCtx(1);
actorSystem.createRootActor(ROOT_DISPATCHER, new TestRootActor.TestRootActorCreator(parentId, parentTestCtx));
actorSystem.createRootActor(ROOT_DISPATCHER, new RecordingActorCreator(parentId, new CopyOnWriteArrayList<>()));
TbActorId matchingChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID()));
ActorTestCtx matchingChildCtx = getActorTestCtx(1);
actorSystem.createChildActor(ROOT_DISPATCHER,
new TestRootActor.TestRootActorCreator(matchingChildId, matchingChildCtx), parentId);
List<Integer> matchingChildValues = new CopyOnWriteArrayList<>();
actorSystem.createChildActor(ROOT_DISPATCHER, new RecordingActorCreator(matchingChildId, matchingChildValues), parentId);
TbActorId otherChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID()));
ActorTestCtx otherChildCtx = getActorTestCtx(1);
actorSystem.createChildActor(ROOT_DISPATCHER,
new TestRootActor.TestRootActorCreator(otherChildId, otherChildCtx), parentId);
List<Integer> otherChildValues = new CopyOnWriteArrayList<>();
actorSystem.createChildActor(ROOT_DISPATCHER, new RecordingActorCreator(otherChildId, otherChildValues), parentId);
// block the only dispatcher thread, so that all messages are enqueued before any is processed
CountDownLatch dispatcherBlocked = new CountDownLatch(1);
executor.submit(() -> {
dispatcherBlocked.await();
return null;
});
actorSystem.tell(matchingChildId, new IntTbActorMsg(1));
actorSystem.tell(matchingChildId, new IntTbActorMsg(2));
actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(42), true);
dispatcherBlocked.countDown();
actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(7), true);
Awaitility.await().atMost(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(matchingChildValues).containsExactly(42, 1, 2));
Assertions.assertTrue(matchingChildCtx.getLatch().await(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS));
Assertions.assertEquals(7L, matchingChildCtx.getActual().get());
Assertions.assertFalse(otherChildCtx.getLatch().await(1, TimeUnit.SECONDS));
actorSystem.tell(otherChildId, new IntTbActorMsg(3));
Awaitility.await().atMost(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(otherChildValues).containsExactly(3));
}
@Test
@ -284,4 +293,32 @@ public class ActorSystemTest {
AtomicInteger invocations = new AtomicInteger();
return new ActorTestCtx(countDownLatch, invocations, i, actual);
}
private static class RecordingActorCreator implements TbActorCreator {
private final TbActorId actorId;
private final List<Integer> values;
RecordingActorCreator(TbActorId actorId, List<Integer> values) {
this.actorId = actorId;
this.values = values;
}
@Override
public TbActorId createActorId() {
return actorId;
}
@Override
public TbActor createActor() {
return new AbstractTbActor() {
@Override
public boolean process(TbActorMsg msg) {
values.add(((IntTbActorMsg) msg).getValue());
return true;
}
};
}
}
}

36
common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java

@ -2,7 +2,10 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.msg.queue;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.MsgType;
import org.thingsboard.server.common.msg.TbActorMsg;
@ -17,23 +20,34 @@ public final class PartitionChangeMsg implements TbActorMsg {
private final ServiceType serviceType;
/**
* Tenants whose partition ownership changed. Null means the shared
* (non-isolated) tenant pool itself changed, so every tenant actor must
* re-verify — shared-pool tenants aren't individually tracked as
* queueKeys, so they can't be enumerated here.
*/
@Getter(AccessLevel.NONE)
@ToString.Exclude
private final Set<TenantId> affectedTenants;
public PartitionChangeMsg(ServiceType serviceType) {
this(serviceType, null);
}
public PartitionChangeMsg(ServiceType serviceType, Set<TenantId> affectedTenants) {
private PartitionChangeMsg(ServiceType serviceType, Set<TenantId> affectedTenants) {
this.serviceType = serviceType;
this.affectedTenants = affectedTenants;
}
public static PartitionChangeMsg forAllTenants(ServiceType serviceType) {
return new PartitionChangeMsg(serviceType, null);
}
public static PartitionChangeMsg forTenants(ServiceType serviceType, Set<TenantId> affectedTenants) {
return new PartitionChangeMsg(serviceType, Set.copyOf(affectedTenants));
}
/**
* @return {@code true} if every tenant actor must receive this message
*/
public boolean isForAllTenants() {
return affectedTenants == null;
}
public boolean isAffected(TenantId tenantId) {
return affectedTenants == null || affectedTenants.contains(tenantId);
}
@Override
public MsgType getMsgType() {
return MsgType.PARTITION_CHANGE_MSG;

56
common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java

@ -1,47 +1,49 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* Licensed 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.
*/
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.msg.queue;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.MsgType;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
public class PartitionChangeMsgTest {
private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID());
private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID());
@Test
public void singleArgConstructor_defaultsAffectedTenantsToNull() {
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE);
public void forAllTenants_affectsEveryTenant() {
PartitionChangeMsg msg = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE);
assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_RULE_ENGINE);
assertThat(msg.getMsgType()).isEqualTo(MsgType.PARTITION_CHANGE_MSG);
assertThat(msg.isForAllTenants()).isTrue();
assertThat(msg.isAffected(tenant1)).isTrue();
assertThat(msg.isAffected(tenant2)).isTrue();
}
assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType());
assertNull(msg.getAffectedTenants());
assertEquals(MsgType.PARTITION_CHANGE_MSG, msg.getMsgType());
@Test
public void forTenants_affectsOnlyGivenTenants() {
Set<TenantId> tenants = new HashSet<>(Set.of(tenant1));
PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, tenants);
tenants.add(tenant2);
assertThat(msg.isForAllTenants()).isFalse();
assertThat(msg.isAffected(tenant1)).isTrue();
assertThat(msg.isAffected(tenant2)).isFalse();
}
@Test
public void twoArgConstructor_carriesAffectedTenants() {
TenantId tenant = new TenantId(UUID.randomUUID());
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant));
public void toString_doesNotListAffectedTenants() {
PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, Set.of(tenant1));
assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType());
assertEquals(Set.of(tenant), msg.getAffectedTenants());
assertThat(msg.toString()).doesNotContain(tenant1.getId().toString());
}
}

33
common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java

@ -108,6 +108,8 @@ public class HashPartitionService implements PartitionService {
private List<ServiceInfo> currentOtherServices;
private final Map<String, List<ServiceInfo>> tbTransportServicesByType = new HashMap<>();
private volatile Map<TenantProfileId, List<ServiceInfo>> responsibleServices = Collections.emptyMap();
// managed status of isolated tenants, as of the last published rule engine partition change event
private Map<TenantId, Boolean> isolatedTenantsManagedStatus = Collections.emptyMap();
private HashFunction hashFunction;
@ -538,7 +540,9 @@ public class HashPartitionService implements PartitionService {
.map(tpi -> tpi.getPartition().orElse(-1).toString()).sorted()
.collect(Collectors.joining(", ")) + "]")
.collect(Collectors.joining(System.lineSeparator())));
PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions);
Set<TenantId> managedStatusChangedTenants = ServiceType.TB_RULE_ENGINE.equals(serviceType) ?
updateIsolatedTenantsManagedStatus() : Collections.emptySet();
PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions, managedStatusChangedTenants);
try {
applicationEventPublisher.publishEvent(event);
} catch (Exception e) {
@ -546,6 +550,33 @@ public class HashPartitionService implements PartitionService {
}
}
// An isolated tenant's managed status depends on responsibleServices, which can change
// while the tenant's own queue keys stay out of the partition change event.
// Returns the isolated tenants whose managed status changed since the previous call.
private synchronized Set<TenantId> updateIsolatedTenantsManagedStatus() {
Map<TenantId, Boolean> managedStatus = new HashMap<>();
partitionSizesMap.keySet().stream()
.filter(queueKey -> queueKey.getType() == ServiceType.TB_RULE_ENGINE && !queueKey.getTenantId().isSysTenantId())
.map(QueueKey::getTenantId)
.distinct()
.forEach(tenantId -> {
try {
managedStatus.put(tenantId, isManagedByCurrentService(tenantId));
} catch (Exception e) {
log.debug("[{}] Failed to check if tenant is managed by current service", tenantId, e);
}
});
Set<TenantId> changed = managedStatus.entrySet().stream()
.filter(entry -> {
Boolean previous = isolatedTenantsManagedStatus.get(entry.getKey());
return previous != null && !previous.equals(entry.getValue());
})
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
isolatedTenantsManagedStatus = managedStatus;
return changed;
}
private Set<TopicPartitionInfo> toTpiList(QueueKey queueKey, List<Integer> partitions) {
if (partitions == null) {
return Collections.emptySet();

30
common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java

@ -5,12 +5,15 @@ package org.thingsboard.server.queue.discovery.event;
import lombok.Getter;
import lombok.ToString;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.queue.discovery.QueueKey;
import java.io.Serial;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@ -27,14 +30,41 @@ public class PartitionChangeEvent extends TbApplicationEvent {
private final Map<QueueKey, Set<TopicPartitionInfo>> newPartitions;
@Getter
private final Map<QueueKey, Set<TopicPartitionInfo>> oldPartitions;
@Getter
@ToString.Exclude
private final Set<TenantId> managedStatusChangedTenants;
public PartitionChangeEvent(Object source, ServiceType serviceType,
Map<QueueKey, Set<TopicPartitionInfo>> newPartitions,
Map<QueueKey, Set<TopicPartitionInfo>> oldPartitions) {
this(source, serviceType, newPartitions, oldPartitions, Collections.emptySet());
}
public PartitionChangeEvent(Object source, ServiceType serviceType,
Map<QueueKey, Set<TopicPartitionInfo>> newPartitions,
Map<QueueKey, Set<TopicPartitionInfo>> oldPartitions,
Set<TenantId> managedStatusChangedTenants) {
super(source);
this.serviceType = serviceType;
this.newPartitions = newPartitions;
this.oldPartitions = oldPartitions;
this.managedStatusChangedTenants = managedStatusChangedTenants;
}
/**
* Returns the tenants affected by this rule engine partition change, or {@code null} if every tenant may be affected.
* <p>
* {@code newPartitions} holds only the changed queue keys. A system tenant key stands for the shared queues,
* whose tenants can't be enumerated, so the result is {@code null}. It is also {@code null} for other service types.
*/
public Set<TenantId> getAffectedTenants() {
if (serviceType != ServiceType.TB_RULE_ENGINE || newPartitions.isEmpty() ||
newPartitions.keySet().stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId())) {
return null;
}
Set<TenantId> affectedTenants = new HashSet<>(managedStatusChangedTenants);
newPartitions.keySet().forEach(queueKey -> affectedTenants.add(queueKey.getTenantId()));
return affectedTenants;
}
public Set<TopicPartitionInfo> getCorePartitions() {

88
common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java

@ -0,0 +1,88 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.queue.discovery.event;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.queue.discovery.QueueKey;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class PartitionChangeEventTest {
private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID());
private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID());
private final TenantId tenant3 = TenantId.fromUUID(UUID.randomUUID());
@Test
void isolatedTenantQueuesChanged_returnsTheirTenants() {
PartitionChangeEvent event = ruleEngineEvent(Set.of(
queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1),
queueKey(DataConstants.HP_QUEUE_NAME, tenant1),
queueKey(DataConstants.MAIN_QUEUE_NAME, tenant2)), Collections.emptySet());
assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant2);
}
@Test
void managedStatusChangedTenantsAreIncluded() {
PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3));
assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant3);
}
@Test
void sharedQueueChanged_returnsNull() {
PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID)), Collections.emptySet());
assertThat(event.getAffectedTenants()).isNull();
}
@Test
void sharedAndIsolatedQueuesChanged_returnsNull() {
PartitionChangeEvent event = ruleEngineEvent(Set.of(
queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID),
queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3));
assertThat(event.getAffectedTenants()).isNull();
}
@Test
void noQueuesChanged_returnsNull() {
PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet(), Set.of(tenant3));
assertThat(event.getAffectedTenants()).isNull();
}
@ParameterizedTest
@EnumSource(value = ServiceType.class, names = "TB_RULE_ENGINE", mode = EnumSource.Mode.EXCLUDE)
void otherServiceType_returnsNull(ServiceType serviceType) {
QueueKey queueKey = new QueueKey(serviceType, DataConstants.MAIN_QUEUE_NAME, tenant1);
PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType,
Map.of(queueKey, Collections.emptySet()), Collections.emptyMap(), Set.of(tenant3));
assertThat(event.getAffectedTenants()).isNull();
}
private PartitionChangeEvent ruleEngineEvent(Set<QueueKey> changedQueueKeys, Set<TenantId> managedStatusChangedTenants) {
Map<QueueKey, Set<TopicPartitionInfo>> newPartitions = changedQueueKeys.stream()
.collect(Collectors.toMap(queueKey -> queueKey, queueKey -> Collections.emptySet()));
return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap(), managedStatusChangedTenants);
}
private QueueKey queueKey(String queueName, TenantId tenantId) {
return new QueueKey(ServiceType.TB_RULE_ENGINE, queueName, tenantId);
}
}

2
rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java

@ -159,7 +159,7 @@ public class TbDeviceStateNodeTest {
given(ctxMock.isLocalEntity(eq(nonLocalDeviceId2))).willReturn(false);
// WHEN
node.onPartitionChangeMsg(ctxMock, new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE));
node.onPartitionChangeMsg(ctxMock, PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE));
// THEN
assertThat(rateLimits)

Loading…
Cancel
Save