Browse Source

rule-engine: broadcast partition changes only to affected tenant actors

AppActor.doProcess unconditionally broadcasts PARTITION_CHANGE_MSG to
every live TenantActor at high priority, regardless of whether a given
tenant's ownership actually changed. On a shared rule-engine instance
hosting many tenants, this means any single tenant's partition change
(e.g. moving to an isolated queue) interrupts every other tenant's
in-flight message processing, even though only one tenant's ownership
changed.

DefaultActorService now resolves which tenants are actually affected
from the partition-change diff it already has on hand (returning null
when the shared/non-isolated pool itself changed, since those tenants
aren't individually tracked and everyone must still be notified), and
AppActor uses that to broadcast only to the affected tenant actors,
reusing the existing TbEntityTypeActorIdPredicate filtering idiom.
Falls back to the original broadcast-to-everyone behavior whenever the
affected set can't be narrowed down.
pull/15961/head
Sergey Matvienko 5 months ago
parent
commit
1930624e1a
  1. 20
      application/src/main/java/org/thingsboard/server/actors/app/AppActor.java
  2. 32
      application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java
  3. 92
      application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java
  4. 64
      application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java

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

@ -11,6 +11,7 @@ import org.thingsboard.server.actors.TbActorException;
import org.thingsboard.server.actors.TbActorId;
import org.thingsboard.server.actors.TbActorRef;
import org.thingsboard.server.actors.TbEntityActorId;
import org.thingsboard.server.actors.TbEntityTypeActorIdPredicate;
import org.thingsboard.server.actors.device.SessionTimeoutCheckMsg;
import org.thingsboard.server.actors.service.ContextAwareActor;
import org.thingsboard.server.actors.service.ContextBasedCreator;
@ -18,6 +19,7 @@ import org.thingsboard.server.actors.service.DefaultActorService;
import org.thingsboard.server.actors.tenant.TenantActor;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.TenantProfileId;
import org.thingsboard.server.common.data.page.PageDataIterable;
@ -27,6 +29,7 @@ import org.thingsboard.server.common.msg.TbActorMsg;
import org.thingsboard.server.common.msg.ToCalculatedFieldSystemMsg;
import org.thingsboard.server.common.msg.aware.TenantAwareMsg;
import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg;
import org.thingsboard.server.common.msg.queue.RuleEngineException;
import org.thingsboard.server.common.msg.queue.ServiceType;
@ -75,6 +78,8 @@ public class AppActor extends ContextAwareActor {
case APP_INIT_MSG:
break;
case PARTITION_CHANGE_MSG:
onPartitionChangeMsg((PartitionChangeMsg) msg);
break;
case CF_PARTITIONS_CHANGE_MSG:
case CF_STATE_PARTITION_RESTORE_MSG:
ctx.broadcastToChildren(msg, true);
@ -202,6 +207,21 @@ 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) {
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);
}
}, true);
}
}
private Optional<TbActorRef> getOrCreateTenantActor(TenantId tenantId) {
if (deletedTenants.contains(tenantId)) {
return Optional.empty();

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

@ -19,14 +19,18 @@ import org.thingsboard.server.actors.TbActorSystemSettings;
import org.thingsboard.server.actors.app.AppActor;
import org.thingsboard.server.actors.app.AppInitMsg;
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;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
@Service
@Slf4j
@ -120,7 +124,33 @@ public class DefaultActorService extends TbApplicationEventListener<PartitionCha
@Override
protected void onTbApplicationEvent(PartitionChangeEvent event) {
log.info("Received partition change event.");
appActor.tellWithHighPriority(new PartitionChangeMsg(event.getServiceType()));
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());
}
@Override

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

@ -0,0 +1,92 @@
/**
* 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.
*/
package org.thingsboard.server.actors.app;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.actors.TbActorCtx;
import org.thingsboard.server.actors.TbActorId;
import org.thingsboard.server.actors.TbEntityActorId;
import org.thingsboard.server.common.data.id.DeviceId;
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.dao.tenant.TenantService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
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.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public 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"));
@Before
public void setUp() throws Exception {
ActorSystemContext systemContext = mock(ActorSystemContext.class);
TenantService tenantService = mock(TenantService.class);
when(systemContext.getTenantService()).thenReturn(tenantService);
when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false);
when(systemContext.getServiceInfoProvider()).thenReturn(mock(TbServiceInfoProvider.class));
appActor = (AppActor) new AppActor.ActorCreator(systemContext).createActor();
ctx = mock(TbActorCtx.class);
appActor.init(ctx);
appActor.doProcess(new AppInitMsg());
}
@Test
public void onPartitionChangeMsgWithAffectedTenants_onlyForwardsToThoseTenants() {
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant1));
appActor.doProcess(msg);
@SuppressWarnings("unchecked")
ArgumentCaptor<Predicate<TbActorId>> filterCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true));
Predicate<TbActorId> filter = filterCaptor.getValue();
assertTrue(filter.test(new TbEntityActorId(tenant1)));
assertFalse(filter.test(new TbEntityActorId(tenant2)));
assertFalse(filter.test(new TbEntityActorId(new DeviceId(UUID.randomUUID()))));
}
@Test
public void onPartitionChangeMsgWithNullAffectedTenants_broadcastsToEveryone() {
PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE);
appActor.doProcess(msg);
verify(ctx).broadcastToChildren(msg, true);
verify(ctx, never()).broadcastToChildren(any(), any(), anyBoolean());
}
}

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

@ -0,0 +1,64 @@
/**
* 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.
*/
package org.thingsboard.server.actors.service;
import org.junit.Test;
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 org.thingsboard.server.queue.discovery.event.PartitionChangeEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class DefaultActorServiceTest {
@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);
}
@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());
Set<TenantId> affected = DefaultActorService.resolveAffectedTenants(event);
assertNull(affected);
}
}
Loading…
Cancel
Save