From 1eb8305d0f9c82728c52b4a01eaafd21dc5ecb87 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sat, 17 Oct 2026 22:12:48 +0200 Subject: [PATCH 01/14] rule-engine: don't init rule chains on partition change when rule engine execution is disabled TenantActor.onPartitionChangeMsg initialized rule chains for any managed tenant whose chains were not initialized yet, ignoring the API usage state. TenantActor.init and the API_USAGE_STATE lifecycle handler both respect isReExecEnabled(), so tenants with rule-engine execution disabled by API limits had no rule chains until the first partition change, which then materialized their whole rule-chain/rule-node actor tree on every rule-engine node (and failed to start script nodes when script execution is disabled too). Apply the same isReExecEnabled() gate on the partition-change path and cover it with two TenantActorTest cases. --- .../server/actors/tenant/TenantActor.java | 2 +- .../server/actors/tenant/TenantActorTest.java | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java index ebb5e181ee..49334da534 100644 --- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java @@ -285,7 +285,7 @@ public class TenantActor extends RuleChainManagerActor { log.info("[{}] Failed to init CF Actor.", tenantId, e); } } - if (!ruleChainsInitialized) { + if (!ruleChainsInitialized && getApiUsageState().isReExecEnabled()) { log.info("Tenant {} is now managed by this service, initializing rule chains", tenantId); initRuleChains(); } diff --git a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java index 2f5fdbfef6..b239ae928e 100644 --- a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java @@ -17,13 +17,17 @@ import org.thingsboard.server.actors.ruleChain.RuleChainToRuleChainMsg; import org.thingsboard.server.actors.service.DefaultActorService; import org.thingsboard.server.actors.shared.RuleChainErrorActor; import org.thingsboard.server.common.data.ApiUsageState; +import org.thingsboard.server.common.data.ApiUsageStateValue; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; +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.common.msg.rule.engine.DeviceDeleteMsg; @@ -99,6 +103,33 @@ public class TenantActorTest { verify(deviceActorRef, never()).tellWithHighPriority(any()); } + @Test + public void partitionChangeDoesNotInitRuleChainsWhenRuleEngineExecutionDisabled() throws Exception { + ApiUsageState disabledState = new ApiUsageState(); + disabledState.setReExecState(ApiUsageStateValue.DISABLED); + when(systemContext.getApiUsageStateService().getApiUsageState(tenantId)).thenReturn(disabledState); + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + + tenantActor.init(mock(TbActorCtx.class)); + tenantActor.doProcess(new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE)); + + verify(ruleChainService, never()).findTenantRuleChainsByType(any(), any(), any()); + } + + @Test + public void partitionChangeInitsRuleChainsWhenTenantBecomesManagedAndRuleEngineExecutionEnabled() throws Exception { + when(partitionService.isManagedByCurrentService(tenantId)).thenReturn(false); + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + + tenantActor.init(mock(TbActorCtx.class)); + verify(ruleChainService, never()).findTenantRuleChainsByType(any(), any(), any()); + + when(partitionService.isManagedByCurrentService(tenantId)).thenReturn(true); + tenantActor.doProcess(new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE)); + + verify(ruleChainService).findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any()); + } + @Test public void ruleChainErrorActorTest() throws Exception { TbActorSystemSettings settings = new TbActorSystemSettings(0, 0, 0); From 7f00ba5d1d3f1d12224a94e14bc1ce873aa4ab1e Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sat, 17 Oct 2026 23:54:36 +0200 Subject: [PATCH 02/14] rule-engine: init/destroy rule chains on API usage state change only on the owning rule engine service The API_USAGE_STATE lifecycle message is broadcast to every core and rule engine service, and the handler had no isRuleEngine or isManagedByCurrentService check. Every re-enable built the tenant's rule chains on all core and rule engine nodes, including the isolated tier, instead of only on the owner. --- .../server/actors/tenant/TenantActor.java | 18 ++++--- .../server/actors/tenant/TenantActorTest.java | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java index 49334da534..165b568140 100644 --- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java @@ -319,12 +319,18 @@ public class TenantActor extends RuleChainManagerActor { if (entityType.equals(EntityType.API_USAGE_STATE)) { ApiUsageState old = getApiUsageState(); apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId)); - if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) { - log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); - destroyRuleChains(); - } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) { - log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId); - initRuleChains(); + if (isRuleEngine) { + if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) { + if (ruleChainsInitialized) { + log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); + destroyRuleChains(); + } + } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) { + if (!ruleChainsInitialized && systemContext.getPartitionService().isManagedByCurrentService(tenantId)) { + log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId); + initRuleChains(); + } + } } } if (msg.getEntityId().getEntityType() == EntityType.DEVICE && ComponentLifecycleEvent.DELETED == msg.getEvent() && isMyPartition(msg.getEntityId())) { diff --git a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java index b239ae928e..6775ffa4b1 100644 --- a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java @@ -18,6 +18,7 @@ import org.thingsboard.server.actors.service.DefaultActorService; import org.thingsboard.server.actors.shared.RuleChainErrorActor; import org.thingsboard.server.common.data.ApiUsageState; import org.thingsboard.server.common.data.ApiUsageStateValue; +import org.thingsboard.server.common.data.id.ApiUsageStateId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; @@ -46,6 +47,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.thingsboard.server.actors.service.DefaultActorService.RULE_DISPATCHER_NAME; @@ -130,6 +132,51 @@ public class TenantActorTest { verify(ruleChainService).findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any()); } + @Test + public void apiUsageStateChangeDoesNotTouchRuleChainsOnCoreOnlyService() throws Exception { + when(systemContext.getServiceInfoProvider().isService(ServiceType.TB_RULE_ENGINE)).thenReturn(false); + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + + tenantActor.init(mock(TbActorCtx.class)); + processReExecStateChanges(ApiUsageStateValue.ENABLED, ApiUsageStateValue.DISABLED, ApiUsageStateValue.ENABLED); + + verify(ruleChainService, never()).findTenantRuleChainsByType(any(), any(), any()); + } + + @Test + public void apiUsageStateChangeDoesNotTouchRuleChainsWhenTenantNotManagedByCurrentService() throws Exception { + when(partitionService.isManagedByCurrentService(tenantId)).thenReturn(false); + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + + tenantActor.init(mock(TbActorCtx.class)); + processReExecStateChanges(ApiUsageStateValue.ENABLED, ApiUsageStateValue.DISABLED, ApiUsageStateValue.ENABLED); + + verify(ruleChainService, never()).findTenantRuleChainsByType(any(), any(), any()); + } + + @Test + public void apiUsageStateChangeDestroysAndInitsRuleChainsWhenTenantManagedByCurrentService() throws Exception { + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + + tenantActor.init(mock(TbActorCtx.class)); + verify(ruleChainService, times(1)).findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any()); + + processReExecStateChanges(ApiUsageStateValue.DISABLED); + verify(ruleChainService, times(2)).findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any()); + + processReExecStateChanges(ApiUsageStateValue.ENABLED); + verify(ruleChainService, times(3)).findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any()); + } + + private void processReExecStateChanges(ApiUsageStateValue... reExecStates) { + for (ApiUsageStateValue reExecState : reExecStates) { + ApiUsageState state = new ApiUsageState(); + state.setReExecState(reExecState); + when(systemContext.getApiUsageStateService().getApiUsageState(tenantId)).thenReturn(state); + tenantActor.doProcess(new ComponentLifecycleMsg(tenantId, new ApiUsageStateId(UUID.randomUUID()), ComponentLifecycleEvent.UPDATED)); + } + } + @Test public void ruleChainErrorActorTest() throws Exception { TbActorSystemSettings settings = new TbActorSystemSettings(0, 0, 0); From 1b79d977bb26404fdfcec5fd501afcb208e9a2ca Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 00:09:17 +0200 Subject: [PATCH 03/14] rule-engine: always destroy rule chains on API usage disable on rule engine services ruleChainsInitialized stays false when initRuleChains() fails part-way and when onRuleChainMsg creates rule chain actors lazily, so gating destroy on it could leave rule chain actors running for a disabled tenant. On enable the flag is redundant: after a disable it is always false. --- .../server/actors/tenant/TenantActor.java | 15 ++++++--------- .../server/actors/tenant/TenantActorTest.java | 13 +++++++++---- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java index 165b568140..037dcabfaa 100644 --- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java @@ -321,15 +321,12 @@ public class TenantActor extends RuleChainManagerActor { apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId)); if (isRuleEngine) { if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) { - if (ruleChainsInitialized) { - log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); - destroyRuleChains(); - } - } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) { - if (!ruleChainsInitialized && systemContext.getPartitionService().isManagedByCurrentService(tenantId)) { - log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId); - initRuleChains(); - } + log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); + destroyRuleChains(); + } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled() + && systemContext.getPartitionService().isManagedByCurrentService(tenantId)) { + log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId); + initRuleChains(); } } } diff --git a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java index 6775ffa4b1..37d60ae6e4 100644 --- a/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/tenant/TenantActorTest.java @@ -38,6 +38,7 @@ import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.apiusage.TbApiUsageStateService; +import java.util.List; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -144,14 +145,18 @@ public class TenantActorTest { } @Test - public void apiUsageStateChangeDoesNotTouchRuleChainsWhenTenantNotManagedByCurrentService() throws Exception { + public void apiUsageStateChangeDoesNotInitRuleChainsWhenTenantNotManagedByCurrentService() throws Exception { when(partitionService.isManagedByCurrentService(tenantId)).thenReturn(false); - when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())).thenReturn(PageData.emptyPageData()); + RuleChain ruleChain = new RuleChain(ruleChainId); + ruleChain.setType(RuleChainType.CORE); + when(ruleChainService.findTenantRuleChainsByType(eq(tenantId), eq(RuleChainType.CORE), any())) + .thenReturn(new PageData<>(List.of(ruleChain), 1, 1, false)); + TbActorCtx ctx = mock(TbActorCtx.class); - tenantActor.init(mock(TbActorCtx.class)); + tenantActor.init(ctx); processReExecStateChanges(ApiUsageStateValue.ENABLED, ApiUsageStateValue.DISABLED, ApiUsageStateValue.ENABLED); - verify(ruleChainService, never()).findTenantRuleChainsByType(any(), any(), any()); + verify(ctx, never()).getOrCreateChildActor(eq(new TbEntityActorId(ruleChainId)), any(), any(), any()); } @Test From 2aeceb6440e07052bcd0a77d9a4a4450bb5eaaaf Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 00:14:11 +0200 Subject: [PATCH 04/14] rule-engine: document the rule chain init checks in the API usage state handler --- .../java/org/thingsboard/server/actors/tenant/TenantActor.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java index 037dcabfaa..b81777aff4 100644 --- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java @@ -319,6 +319,8 @@ public class TenantActor extends RuleChainManagerActor { if (entityType.equals(EntityType.API_USAGE_STATE)) { ApiUsageState old = getApiUsageState(); apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId)); + // Rule chains are initialized only on the rule engine service that manages the tenant, with the same checks + // (isRuleEngine, isManagedByCurrentService, isReExecEnabled) as in init() and onPartitionChangeMsg() if (isRuleEngine) { if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) { log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); From 81c154ca5fd228e478b83148f518d53974a634eb Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:06:42 +0200 Subject: [PATCH 05/14] actor: add a filtered, priority-aware broadcastToChildren capability TbActorSystem/TbActorCtx already supported broadcasting to a filtered subset of children, and separately broadcasting to all children at a given priority, but not both together. Expose the existing internal implementation (already used for the priority-only case) as a public filtered + prioritized overload, so callers can target a subset of children without giving up delivery priority. --- .../server/actors/DefaultTbActorSystem.java | 3 ++- .../thingsboard/server/actors/TbActorCtx.java | 2 ++ .../server/actors/TbActorMailbox.java | 5 ++++ .../server/actors/TbActorSystem.java | 2 ++ .../server/actors/ActorSystemTest.java | 26 +++++++++++++++++++ 5 files changed, 37 insertions(+), 1 deletion(-) diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java b/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java index e93b649b24..e03c10ec0f 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java @@ -155,7 +155,8 @@ public class DefaultTbActorSystem implements TbActorSystem { broadcastToChildren(parent, childFilter, msg, false); } - private void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority) { + @Override + public void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority) { Set children = parentChildMap.get(parent); if (children != null) { children.stream().filter(childFilter).forEach(id -> { diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java index 7e409a3efc..6d7697d8c7 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java @@ -29,5 +29,7 @@ public interface TbActorCtx extends TbActorRef { void broadcastToChildren(TbActorMsg msg, Predicate childFilter); + void broadcastToChildren(TbActorMsg msg, Predicate childFilter, boolean highPriority); + List filterChildren(Predicate childFilter); } diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java index 4699eb6891..55f2c6d962 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java @@ -196,6 +196,11 @@ public final class TbActorMailbox implements TbActorCtx { system.broadcastToChildren(selfId, childFilter, msg); } + @Override + public void broadcastToChildren(TbActorMsg msg, Predicate childFilter, boolean highPriority) { + system.broadcastToChildren(selfId, childFilter, msg, highPriority); + } + @Override public List filterChildren(Predicate childFilter) { return system.filterChildren(selfId, childFilter); diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java index 2787524379..e9f040720d 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java @@ -39,5 +39,7 @@ public interface TbActorSystem { void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg); + void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority); + List filterChildren(TbActorId parent, Predicate childFilter); } diff --git a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java index 9dee47f948..e7a6f83fa2 100644 --- a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java +++ b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java @@ -184,6 +184,32 @@ public class ActorSystemTest { Assertions.assertEquals(2, testCtx.getInvocationCount().get()); } + @Test + public void testBroadcastToChildrenWithFilterAndPriority() throws InterruptedException { + executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass()); + 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)); + + TbActorId matchingChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); + ActorTestCtx matchingChildCtx = getActorTestCtx(1); + actorSystem.createChildActor(ROOT_DISPATCHER, + new TestRootActor.TestRootActorCreator(matchingChildId, matchingChildCtx), parentId); + + TbActorId otherChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); + ActorTestCtx otherChildCtx = getActorTestCtx(1); + actorSystem.createChildActor(ROOT_DISPATCHER, + new TestRootActor.TestRootActorCreator(otherChildId, otherChildCtx), parentId); + + actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(7), true); + + 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)); + } + @Test public void testFailedInit() throws InterruptedException { executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass()); From 1528864968e10f6c8d25fc7dbdea09d86f4c5341 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:06:51 +0200 Subject: [PATCH 06/14] msg: let PartitionChangeMsg optionally target specific tenants PartitionChangeMsg only carried the affected ServiceType, so a consumer had no way to know which specific tenants (if any) a given partition change actually affects versus all of them. Add an optional affectedTenants set: null preserves today's meaning ("could affect anyone, notify everyone"), a non-null set means only those tenants are affected. Existing single-arg construction is unchanged and keeps defaulting to null. --- .../common/msg/queue/PartitionChangeMsg.java | 22 ++++++++- .../msg/queue/PartitionChangeMsgTest.java | 47 +++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java index f5673c6dcb..72550a48cf 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java @@ -3,19 +3,37 @@ package org.thingsboard.server.common.msg.queue; import lombok.Data; -import lombok.Getter; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.MsgType; import org.thingsboard.server.common.msg.TbActorMsg; +import java.util.Set; + /** * @author Andrew Shvayka */ @Data public final class PartitionChangeMsg implements TbActorMsg { - @Getter 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. + */ + private final Set affectedTenants; + + public PartitionChangeMsg(ServiceType serviceType) { + this(serviceType, null); + } + + public PartitionChangeMsg(ServiceType serviceType, Set affectedTenants) { + this.serviceType = serviceType; + this.affectedTenants = affectedTenants; + } + @Override public MsgType getMsgType() { return MsgType.PARTITION_CHANGE_MSG; diff --git a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java new file mode 100644 index 0000000000..6e01879941 --- /dev/null +++ b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java @@ -0,0 +1,47 @@ +/** + * 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.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.Set; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PartitionChangeMsgTest { + + @Test + public void singleArgConstructor_defaultsAffectedTenantsToNull() { + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE); + + assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); + assertNull(msg.getAffectedTenants()); + assertEquals(MsgType.PARTITION_CHANGE_MSG, msg.getMsgType()); + } + + @Test + public void twoArgConstructor_carriesAffectedTenants() { + TenantId tenant = new TenantId(UUID.randomUUID()); + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant)); + + assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); + assertEquals(Set.of(tenant), msg.getAffectedTenants()); + } +} From 1930624e1a2fd510098a5b8df2edb9dd176bdad2 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:07:01 +0200 Subject: [PATCH 07/14] 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. --- .../server/actors/app/AppActor.java | 20 ++++ .../actors/service/DefaultActorService.java | 32 ++++++- .../server/actors/app/AppActorTest.java | 92 +++++++++++++++++++ .../service/DefaultActorServiceTest.java | 64 +++++++++++++ 4 files changed, 207 insertions(+), 1 deletion(-) create mode 100644 application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java create mode 100644 application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java index 93b94542a0..1b503a37f2 100644 --- a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java +++ b/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 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 getOrCreateTenantActor(TenantId tenantId) { if (deletedTenants.contains(tenantId)) { return Optional.empty(); diff --git a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java index 0c42f4406f..18da74075d 100644 --- a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java +++ b/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 + * Despite its name, {@link PartitionChangeEvent#getNewPartitions()} carries only the + * changed subset 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". + *

+ * 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 resolveAffectedTenants(PartitionChangeEvent event) { + Set 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 diff --git a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java new file mode 100644 index 0000000000..8d6fef3995 --- /dev/null +++ b/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> filterCaptor = ArgumentCaptor.forClass(Predicate.class); + verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true)); + Predicate 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()); + } +} diff --git a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java new file mode 100644 index 0000000000..d4e747defc --- /dev/null +++ b/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> 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 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> newPartitions = Map.of(sharedMainQueue, Collections.emptySet()); + PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of()); + + Set affected = DefaultActorService.resolveAffectedTenants(event); + + assertNull(affected); + } +} From 65364922cf2fa07bda32412def24da3cd2c06f04 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 11:26:31 +0200 Subject: [PATCH 08/14] 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. --- .../server/actors/app/AppActor.java | 6 +- .../actors/service/DefaultActorService.java | 36 +---- .../server/actors/app/AppActorTest.java | 151 +++++++++++------- .../service/DefaultActorServiceTest.java | 99 +++++++----- .../discovery/HashPartitionServiceTest.java | 36 +++++ .../server/actors/ActorSystemTest.java | 69 ++++++-- .../common/msg/queue/PartitionChangeMsg.java | 36 +++-- .../msg/queue/PartitionChangeMsgTest.java | 56 +++---- .../queue/discovery/HashPartitionService.java | 33 +++- .../discovery/event/PartitionChangeEvent.java | 30 ++++ .../event/PartitionChangeEventTest.java | 88 ++++++++++ .../engine/action/TbDeviceStateNodeTest.java | 2 +- 12 files changed, 451 insertions(+), 191 deletions(-) create mode 100644 common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java diff --git a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java index 1b503a37f2..994b5dae60 100644 --- a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java +++ b/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 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); } diff --git a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java index 18da74075d..e7919db97c 100644 --- a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java +++ b/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 - * Despite its name, {@link PartitionChangeEvent#getNewPartitions()} carries only the - * changed subset 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". - *

- * 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 resolveAffectedTenants(PartitionChangeEvent event) { - Set 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 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 diff --git a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java index 8d6fef3995..6d6d0129de 100644 --- a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java +++ b/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 tenant1Msgs; + private List tenant2Msgs; + private List 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> filterCaptor = ArgumentCaptor.forClass(Predicate.class); - verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true)); - Predicate 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 createRecordingChild(TbActorId actorId) { + List 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; } + } diff --git a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java index d4e747defc..f03f4dccf3 100644 --- a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java +++ b/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> 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 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> 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 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 captor = ArgumentCaptor.forClass(PartitionChangeMsg.class); + verify(appActor).tellWithHighPriority(captor.capture()); + return captor.getValue(); + } + } diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 0eeb11c0f4..32059096f4 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/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 ruleEngines = new ArrayList<>(); diff --git a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java index e7a6f83fa2..7ff794930f 100644 --- a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java +++ b/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 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 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 values; + + RecordingActorCreator(TbActorId actorId, List 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; + } + }; + } + } + } diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java index 72550a48cf..ec7681aea5 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java +++ b/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 affectedTenants; - public PartitionChangeMsg(ServiceType serviceType) { - this(serviceType, null); - } - - public PartitionChangeMsg(ServiceType serviceType, Set affectedTenants) { + private PartitionChangeMsg(ServiceType serviceType, Set 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 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; diff --git a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java index 6e01879941..9bdc98755d 100644 --- a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java +++ b/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 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()); } + } diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 57a8023548..380d452f5e 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -108,6 +108,8 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); + // managed status of isolated tenants, as of the last published rule engine partition change event + private Map 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 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 updateIsolatedTenantsManagedStatus() { + Map 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 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 toTpiList(QueueKey queueKey, List partitions) { if (partitions == null) { return Collections.emptySet(); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java index 4560a2dec1..a089195e98 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java +++ b/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> newPartitions; @Getter private final Map> oldPartitions; + @Getter + @ToString.Exclude + private final Set managedStatusChangedTenants; public PartitionChangeEvent(Object source, ServiceType serviceType, Map> newPartitions, Map> oldPartitions) { + this(source, serviceType, newPartitions, oldPartitions, Collections.emptySet()); + } + + public PartitionChangeEvent(Object source, ServiceType serviceType, + Map> newPartitions, + Map> oldPartitions, + Set 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. + *

+ * {@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 getAffectedTenants() { + if (serviceType != ServiceType.TB_RULE_ENGINE || newPartitions.isEmpty() || + newPartitions.keySet().stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId())) { + return null; + } + Set affectedTenants = new HashSet<>(managedStatusChangedTenants); + newPartitions.keySet().forEach(queueKey -> affectedTenants.add(queueKey.getTenantId())); + return affectedTenants; } public Set getCorePartitions() { diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java new file mode 100644 index 0000000000..ca1a36e378 --- /dev/null +++ b/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 changedQueueKeys, Set managedStatusChangedTenants) { + Map> 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); + } + +} diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java index 9ec169df9b..a2a6b59c36 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java +++ b/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) From 4418f99ddac4bf23536b75ad72efa4e460e59581 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 11:37:56 +0200 Subject: [PATCH 09/14] rule-engine: keep isolated tenants without dedicated servers managed by regular servers HashPartitionService.resolveByPartitionIdx caches the fallback (regular) servers of an isolated profile without dedicated servers in responsibleServices. isManagedByCurrentService then saw a non-empty list for that profile and reported its tenants as not managed on the regular servers, although those servers own the tenants' partitions. This happens as soon as any dedicated server exists in the cluster. Remember which profiles have dedicated servers before the fallback entries are added, and use that set in isManagedByCurrentService. --- .../discovery/HashPartitionServiceTest.java | 43 +++++++++++++++++++ .../queue/discovery/HashPartitionService.java | 11 +++-- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 0eeb11c0f4..750751ab1a 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java @@ -369,6 +369,49 @@ public class HashPartitionServiceTest { }); } + @Test + public void testIsManagedByCurrentService_isolatedProfileWithoutDedicatedServers() { + 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 commonPartitionService = createPartitionService(); + commonPartitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); + assertThat(commonPartitionService.isManagedByCurrentService(tenantId)).isTrue(); + assertThat(commonPartitionService.isManagedByCurrentService(otherTenantId)).isTrue(); + + // a dedicated server for another profile joins + commonPartitionService.recalculatePartitions(commonRuleEngine, List.of(dedicatedRuleEngine)); + assertThat(commonPartitionService.resolve(ServiceType.TB_RULE_ENGINE, DataConstants.MAIN_QUEUE_NAME, tenantId, tenantId).isMyPartition()).isTrue(); + assertThat(commonPartitionService.isManagedByCurrentService(tenantId)).isTrue(); + assertThat(commonPartitionService.isManagedByCurrentService(otherTenantId)).isFalse(); + // stays the same on the next recalculation + commonPartitionService.recalculatePartitions(commonRuleEngine, List.of(dedicatedRuleEngine)); + assertThat(commonPartitionService.isManagedByCurrentService(tenantId)).isTrue(); + + when(serviceInfoProvider.getAssignedTenantProfiles()).thenReturn(Set.of(profileWithDedicatedServer.getId())); + HashPartitionService dedicatedPartitionService = createPartitionService(); + dedicatedPartitionService.recalculatePartitions(dedicatedRuleEngine, List.of(commonRuleEngine)); + assertThat(dedicatedPartitionService.isManagedByCurrentService(tenantId)).isFalse(); + assertThat(dedicatedPartitionService.isManagedByCurrentService(otherTenantId)).isTrue(); + } + @Test public void testPartitionsDistribution_sameTenantDifferentQueues() { List ruleEngines = new ArrayList<>(); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 57a8023548..67ef7e965d 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -21,7 +21,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantProfileId; import org.thingsboard.server.common.data.integration.IntegrationType; import org.thingsboard.server.common.data.job.JobType; -import org.thingsboard.server.common.data.util.CollectionsUtil; import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.gen.transport.TransportProtos; @@ -108,6 +107,7 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); + private volatile Set profilesWithDedicatedServices = Collections.emptySet(); private HashFunction hashFunction; @@ -319,7 +319,7 @@ public class HashPartitionService implements PartitionService { TenantRoutingInfo routingInfo = getRoutingInfo(tenantId); if (isRegular) { if (routingInfo.isIsolated()) { - isManaged = hasDedicatedService(routingInfo.getProfileId()); + isManaged = !profilesWithDedicatedServices.contains(routingInfo.getProfileId()); } else { isManaged = true; } @@ -334,10 +334,6 @@ public class HashPartitionService implements PartitionService { return isManaged; } - private boolean hasDedicatedService(TenantProfileId profileId) { - return CollectionsUtil.isEmpty(responsibleServices.get(profileId)); - } - @Override public TopicPartitionInfo resolve(ServiceType serviceType, String queueName, TenantId tenantId, EntityId entityId) { QueueKey queueKey = getQueueKey(serviceType, queueName, tenantId); @@ -447,6 +443,8 @@ public class HashPartitionService implements PartitionService { } queueServicesMap.values().forEach(list -> list.sort(Comparator.comparing(ServiceInfo::getServiceId))); responsibleServices.values().forEach(list -> list.sort(Comparator.comparing(ServiceInfo::getServiceId))); + // resolveByPartitionIdx adds the fallback servers for profiles without dedicated services to responsibleServices + Set profilesWithDedicatedServices = Set.copyOf(responsibleServices.keySet()); final ConcurrentMap> newPartitions = new ConcurrentHashMap<>(); partitionSizesMap.forEach((queueKey, size) -> { @@ -463,6 +461,7 @@ public class HashPartitionService implements PartitionService { } }); this.responsibleServices = responsibleServices; + this.profilesWithDedicatedServices = profilesWithDedicatedServices; final ConcurrentMap> oldPartitions = myPartitions; myPartitions = newPartitions; From 23a0263d01f734bac8716946077e8644e61be41f Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 13:19:34 +0200 Subject: [PATCH 10/14] rule-engine: remove unused responsibleServices field from HashPartitionService After the managed-status fix the field was only written, never read. It also held the fallback entries added by resolveByPartitionIdx, so reading it later as "profiles with dedicated servers" would bring the bug back. --- .../server/queue/discovery/HashPartitionService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 67ef7e965d..5f160135e9 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -106,7 +106,6 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); - private volatile Map> responsibleServices = Collections.emptyMap(); private volatile Set profilesWithDedicatedServices = Collections.emptySet(); private HashFunction hashFunction; @@ -460,7 +459,6 @@ public class HashPartitionService implements PartitionService { } } }); - this.responsibleServices = responsibleServices; this.profilesWithDedicatedServices = profilesWithDedicatedServices; final ConcurrentMap> oldPartitions = myPartitions; From ed77b56100e87cbfa2e1e3344925e1b9f0372976 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 14:23:30 +0200 Subject: [PATCH 11/14] Fixed flaky AgentControllerTest getAgentInfosByIds test /api/agentInfos?agentIds=... is served by a derived JPA 'id IN (...)' query with no ORDER BY, so PostgreSQL may return rows in any order (e.g. physical tuple order after an UPDATE). The test asserted infos.get(0) == first and infos.get(1) == second, and failed whenever the rows came back reversed. Match the returned infos by id instead. --- .../server/controller/AgentControllerTest.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java index 5e1123d037..a929c654e7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java @@ -12,13 +12,18 @@ import org.thingsboard.server.common.data.agent.AgentAppEvent; import org.thingsboard.server.common.data.agent.AgentAppEventInfo; import org.thingsboard.server.common.data.agent.AgentInfo; import org.thingsboard.server.common.data.agent.AgentInstructions; +import org.thingsboard.server.common.data.id.AgentId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -104,10 +109,12 @@ public class AgentControllerTest extends AbstractControllerTest { List infos = doGetTyped("/api/agentInfos?agentIds=" + first.getId().getId() + "," + second.getId().getId() + "," + UUID.randomUUID(), new TypeReference<>() {}); + // The endpoint does not guarantee result order (SQL "id IN (...)" without ORDER BY), so match by id Assert.assertEquals(2, infos.size()); - Assert.assertEquals(first.getId(), infos.get(0).getId()); - Assert.assertEquals(first.getName(), infos.get(0).getName()); - Assert.assertEquals(second.getId(), infos.get(1).getId()); + Map infosById = infos.stream().collect(Collectors.toMap(AgentInfo::getId, Function.identity())); + Assert.assertEquals(Set.of(first.getId(), second.getId()), infosById.keySet()); + Assert.assertEquals(first.getName(), infosById.get(first.getId()).getName()); + Assert.assertEquals(second.getName(), infosById.get(second.getId()).getName()); } @Test From f823a7412364f636a6447e1cbeae7d00a7fc825c Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 14:24:18 +0200 Subject: [PATCH 12/14] Fix flaky QrCodeSettingsControllerTest deep link host test WhiteLabelingControllerTest saves the system-level login white-labeling params with baseUrl "https://domain.com" and never restores them. The params persist in the shared test database, so when QrCodeSettingsControllerTest runs later in the same JVM, getBaseUrl() resolves the system base URL to domain.com and testGetMobileDeepLink fails with expected "localhost" but was "domain.com". Reset system white-labeling settings after every WhiteLabelingControllerTest test, and reset them in QrCodeSettingsControllerTest setup as well. --- .../server/controller/QrCodeSettingsControllerTest.java | 3 ++- .../server/controller/WhiteLabelingControllerTest.java | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java index c2e2b953b2..15fe14f895 100644 --- a/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java @@ -53,7 +53,8 @@ public class QrCodeSettingsControllerTest extends AbstractControllerTest { @Before public void setUp() throws Exception { - loginSysAdmin(); + // Deep link host is derived from the login white-labeling base URL; start from system defaults + resetSysAdminWhiteLabelingSettings(); MobileApp androidApp = validMobileApp( "my.android.package", PlatformType.ANDROID); StoreInfo androidStoreInfo = StoreInfo.builder() diff --git a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java index 83eb9384bf..8574bd7bd0 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java @@ -36,7 +36,11 @@ public class WhiteLabelingControllerTest extends AbstractControllerTest { WhiteLabelingDao whiteLabelingDao; @After - public void afterTest() { + public void afterTest() throws Exception { + // System-level login/white-labeling params are shared by every test class in the same DB; + // restore defaults so the base URL set here (e.g. "https://domain.com") does not leak. + resetSysAdminWhiteLabelingSettings(); + if (tenantId != null) { WhiteLabelingCompositeKey key = new WhiteLabelingCompositeKey(tenantId, WhiteLabelingType.MAIL_TEMPLATES); if (whiteLabelingDao.findById(SYS_TENANT_ID, key) != null) { From 3db4deb692b8e9c05c7f4803aae260cad3285b45 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 14:34:41 +0200 Subject: [PATCH 13/14] Fixed flaky HttpIntegrationTest integration start wait HttpIntegrationTest creates the integration disabled and enables it right away, which produces CREATED and UPDATED lifecycle messages. The CREATED task reads the integration configuration when it runs. If the enable has already been committed, that task starts the integration (STARTED), and the UPDATED task that follows calls update() on the running integration and persists an UPDATED event. waitUntilIntegrationStarted required the latest lifecycle event to be STARTED, so it timed out after 30 s even though the integration was up. Accept a successful STARTED or UPDATED as the latest lifecycle event. --- .../integration/AbstractIntegrationTest.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/integration/AbstractIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/integration/AbstractIntegrationTest.java index 2d72b6b6db..4164eb4eb2 100644 --- a/application/src/test/java/org/thingsboard/server/service/integration/AbstractIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/integration/AbstractIntegrationTest.java @@ -164,6 +164,14 @@ public abstract class AbstractIntegrationTest extends AbstractControllerTest { return targetMsgs; } + /** + * Waits until the latest lifecycle event says the integration is running. + *

+ * An integration that is created disabled and then enabled right away gets two lifecycle messages, CREATED and UPDATED. + * The CREATED task reads the configuration when it runs. If the enable is already committed by then, that task + * starts the integration and persists STARTED, and the UPDATED task that follows persists UPDATED on the running + * integration. So the latest event can be either STARTED or UPDATED, and both mean the integration is up. + */ protected void waitUntilIntegrationStarted(TenantId tenantId, IntegrationId integrationId) { Awaitility .await() @@ -176,8 +184,11 @@ public abstract class AbstractIntegrationTest extends AbstractControllerTest { } EventInfo event = events.getData().stream().max(Comparator.comparingLong(EventInfo::getCreatedTime)).orElse(null); - return event != null - && "STARTED".equals(event.getBody().get("event").asText()) + if (event == null) { + return false; + } + String eventType = event.getBody().get("event").asText(); + return ("STARTED".equals(eventType) || "UPDATED".equals(eventType)) && "true".equals(event.getBody().get("success").asText()); }); } From 4294c3a20cd84a2ace2920789295ac33f9dcdea7 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 19:20:46 +0200 Subject: [PATCH 14/14] rule-engine: drop managed-status tracking from partition change events The tracking compensated for isManagedByCurrentService reporting isolated tenants of a profile without dedicated servers as not managed (a dedicated server for any other profile flipped it). That root cause is fixed in #16345, after which a tenant's managed status changes only together with its own queue ownership, and its queue keys are already in the partition change event. Replace the test that pinned the old flip with one that checks the affected tenants when a dedicated server for the tenant's own profile joins and leaves. --- .../discovery/HashPartitionServiceTest.java | 26 ++++++++------- .../queue/discovery/HashPartitionService.java | 33 +------------------ .../discovery/event/PartitionChangeEvent.java | 17 +--------- .../event/PartitionChangeEventTest.java | 22 ++++--------- 4 files changed, 23 insertions(+), 75 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 32059096f4..c05423756d 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java @@ -370,24 +370,21 @@ public class HashPartitionServiceTest { } @Test - public void testPartitionChangeEvent_includesIsolatedTenantWithChangedManagedStatus() { + public void testPartitionChangeEvent_affectedTenantsIncludeIsolatedTenantWhenItsDedicatedServerChanges() { 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()); + TenantProfileId tenantProfileId = 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()) + .addAssignedTenantProfiles(tenantProfileId.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))); + mockRoutingInfo(tenantId, tenantProfileId, true); + mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3))); when(serviceInfoProvider.isService(eq(ServiceType.TB_RULE_ENGINE))).thenReturn(true); when(serviceInfoProvider.getAssignedTenantProfiles()).thenReturn(Collections.emptySet()); @@ -395,14 +392,19 @@ public class HashPartitionServiceTest { partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue(); + // a dedicated server for the tenant's own profile joins: the tenant is no longer managed here 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())); + Set.of(tenantId).equals(event.getAffectedTenants())); + + // the dedicated server leaves: the tenant is managed here again + Mockito.reset(applicationEventPublisher); + partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); + assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue(); + verifyPartitionChangeEvent(event -> event.getServiceType() == ServiceType.TB_RULE_ENGINE && + Set.of(tenantId).equals(event.getAffectedTenants())); } @Test diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 380d452f5e..57a8023548 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -108,8 +108,6 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); - // managed status of isolated tenants, as of the last published rule engine partition change event - private Map isolatedTenantsManagedStatus = Collections.emptyMap(); private HashFunction hashFunction; @@ -540,9 +538,7 @@ public class HashPartitionService implements PartitionService { .map(tpi -> tpi.getPartition().orElse(-1).toString()).sorted() .collect(Collectors.joining(", ")) + "]") .collect(Collectors.joining(System.lineSeparator()))); - Set managedStatusChangedTenants = ServiceType.TB_RULE_ENGINE.equals(serviceType) ? - updateIsolatedTenantsManagedStatus() : Collections.emptySet(); - PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions, managedStatusChangedTenants); + PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions); try { applicationEventPublisher.publishEvent(event); } catch (Exception e) { @@ -550,33 +546,6 @@ 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 updateIsolatedTenantsManagedStatus() { - Map 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 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 toTpiList(QueueKey queueKey, List partitions) { if (partitions == null) { return Collections.emptySet(); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java index a089195e98..460b1d9009 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java @@ -12,8 +12,6 @@ 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; @@ -30,25 +28,14 @@ public class PartitionChangeEvent extends TbApplicationEvent { private final Map> newPartitions; @Getter private final Map> oldPartitions; - @Getter - @ToString.Exclude - private final Set managedStatusChangedTenants; public PartitionChangeEvent(Object source, ServiceType serviceType, Map> newPartitions, Map> oldPartitions) { - this(source, serviceType, newPartitions, oldPartitions, Collections.emptySet()); - } - - public PartitionChangeEvent(Object source, ServiceType serviceType, - Map> newPartitions, - Map> oldPartitions, - Set managedStatusChangedTenants) { super(source); this.serviceType = serviceType; this.newPartitions = newPartitions; this.oldPartitions = oldPartitions; - this.managedStatusChangedTenants = managedStatusChangedTenants; } /** @@ -62,9 +49,7 @@ public class PartitionChangeEvent extends TbApplicationEvent { newPartitions.keySet().stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId())) { return null; } - Set affectedTenants = new HashSet<>(managedStatusChangedTenants); - newPartitions.keySet().forEach(queueKey -> affectedTenants.add(queueKey.getTenantId())); - return affectedTenants; + return newPartitions.keySet().stream().map(QueueKey::getTenantId).collect(Collectors.toSet()); } public Set getCorePartitions() { diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java index ca1a36e378..856d8b8167 100644 --- a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java +++ b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java @@ -23,28 +23,20 @@ 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()); + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant2))); 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()); + PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID))); assertThat(event.getAffectedTenants()).isNull(); } @@ -53,14 +45,14 @@ class PartitionChangeEventTest { 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)); + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1))); assertThat(event.getAffectedTenants()).isNull(); } @Test void noQueuesChanged_returnsNull() { - PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet(), Set.of(tenant3)); + PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet()); assertThat(event.getAffectedTenants()).isNull(); } @@ -70,15 +62,15 @@ class PartitionChangeEventTest { 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)); + Map.of(queueKey, Collections.emptySet()), Collections.emptyMap()); assertThat(event.getAffectedTenants()).isNull(); } - private PartitionChangeEvent ruleEngineEvent(Set changedQueueKeys, Set managedStatusChangedTenants) { + private PartitionChangeEvent ruleEngineEvent(Set changedQueueKeys) { Map> newPartitions = changedQueueKeys.stream() .collect(Collectors.toMap(queueKey -> queueKey, queueKey -> Collections.emptySet())); - return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap(), managedStatusChangedTenants); + return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap()); } private QueueKey queueKey(String queueName, TenantId tenantId) {