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)